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
goribun/naive-rpc
naive-client/src/main/java/com/goribun/naive/client/poxy/RpcProxy.java
[ "public class OkHttpUtil {\n\n private static OkHttpClient CLIENT = new OkHttpClient();\n\n private OkHttpUtil() {\n }\n\n public static OkHttpClient getOkHttpClient() {\n return CLIENT;\n }\n\n}", "public enum SysErCode {\n IO_ERROR(0001, \"IO异常\"),\n OK_HTTP_ERROR(0002, \"okhttp请求错误\"),\n RPC_ERROR(0003, \"RPC调用失败\"),\n INIT_SERVER_ERR0R(0004, \"初始化服务端失败\"),\n PROVIDE_ERR0R(0005, \"提供rpc服务失败\"),\n ZK_ERR0R(0006, \"zookeeper服务失败\");\n private int erCode;\n private String msg;\n\n SysErCode(int erCode, String msg) {\n this.erCode = erCode;\n this.msg = msg;\n }\n\n public int getErCode() {\n return erCode;\n }\n\n public String getMsg() {\n return msg;\n }\n\n public SysErCode getSysErCode(int erCode) {\n for (SysErCode sys : SysErCode.values()) {\n if (sys.getErCode() == erCode) {\n return sys;\n }\n }\n return null;\n }\n}", "public class SysException extends RuntimeException {\n\n private static final long serialVersionUID = 2363088507608422727L;\n\n private int errorCode;\n\n public SysException(SysErCode sysErCode) {\n super(sysErCode.getMsg());\n this.errorCode = sysErCode.getErCode();\n }\n\n public SysException(SysErCode sysErCode, Throwable cause) {\n super(sysErCode.getMsg(), cause);\n this.errorCode = sysErCode.getErCode();\n }\n}", "public class Protocol<T> implements Serializable {\n\n private static final long serialVersionUID = -7464366914176464832L;\n\n //编码\n private int code;\n //消息\n private String message;\n //异常信息\n private ExceptionDetail exceptionDetail;\n //数据\n private T data;\n\n public int getCode() {\n return code;\n }\n\n public void setCode(int code) {\n this.code = code;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\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 ExceptionDetail getExceptionDetail() {\n return exceptionDetail;\n }\n\n public void setExceptionDetail(ExceptionDetail exceptionDetail) {\n this.exceptionDetail = exceptionDetail;\n }\n}", "public class ProtocolStatus {\n\n public static final int SUCCESS = 0;\n public static final int FAILURE = -1;\n\n}", "public class MethodCallEntity {\n private String returnType;\n private LinkedList<ParameterEntity> argList = Lists.newLinkedList();\n\n //无参构造\n public MethodCallEntity() {\n\n }\n\n public MethodCallEntity(Method method, Object[] args) {\n\n this.returnType = method.getReturnType().getName();\n\n Class[] classes = method.getParameterTypes();\n if (args != null && args.length != 0) {\n for (int i=0;i<args.length;i++) {\n ParameterEntity parameterEntity =new ParameterEntity(classes[i].getName(),args[i]);\n argList.add(parameterEntity);\n }\n }\n }\n\n public String getReturnType() {\n return returnType;\n }\n\n public LinkedList<ParameterEntity> getArgList() {\n return argList;\n }\n\n public void setReturnType(String returnType) {\n this.returnType = returnType;\n }\n\n public void setArgList(LinkedList<ParameterEntity> argList) {\n this.argList = argList;\n }\n}", "public class MethodCallUtil {\n public static MethodCallEntity getMethodCallEntity(String args) {\n return JSONObject.parseObject(args, MethodCallEntity.class);\n }\n\n public static String getMethodCallStr(MethodCallEntity entity) {\n return JSONObject.toJSONStringWithDateFormat(entity, Const.DEFAULT_DATE_FORMAT);\n }\n\n /**\n * 判断是否是JSONObject\n */\n public static boolean isJSONObject(Object obj) {\n return obj != null && obj instanceof JSONObject;\n }\n}", "public class ExceptionUtil {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionUtil.class);\n\n\n private ExceptionUtil() {\n }\n\n /**\n * 构造异常信息(序列化)\n */\n public static ExceptionDetail formatException(Throwable throwable) {\n if (throwable == null) {\n return null;\n }\n ExceptionDetail exceptionDetail = new ExceptionDetail();\n exceptionDetail.setName(throwable.getClass().getName());\n exceptionDetail.setMsg(throwable.getMessage());\n exceptionDetail.setCause(formatException(throwable.getCause()));\n if (PropertyUtil.getBooleanProperty(Const.IS_TRACE_STACK, false)) {\n LOGGER.debug(\"The exception message will return trace info\");\n try {\n StringWriter errors = new StringWriter();\n throwable.printStackTrace(new PrintWriter(errors));\n exceptionDetail.setStack(errors.toString());\n } catch (Exception e) {\n LOGGER.warn(\"Return trace info error\", e);\n }\n }\n return exceptionDetail;\n }\n\n /**\n * 实例化异常(反序列化)\n */\n\n public static Throwable instanceThrowable(ExceptionDetail exceptionMessage) {\n Throwable throwable;\n try {\n Class<?> cl = Class.forName(exceptionMessage.getName());\n Class[] params = {String.class};\n Constructor constructor = cl.getConstructor(params);\n throwable = (Throwable) constructor.newInstance(exceptionMessage.getMsg());\n } catch (Exception e) {\n LOGGER.error(\"Instantiation exception error\");\n return e;\n }\n\n return throwable;\n }\n}" ]
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import com.alibaba.fastjson.JSON; import com.goribun.naive.client.http.OkHttpUtil; import com.goribun.naive.core.constants.SysErCode; import com.goribun.naive.core.exception.SysException; import com.goribun.naive.core.protocol.Protocol; import com.goribun.naive.core.protocol.ProtocolStatus; import com.goribun.naive.core.serial.MethodCallEntity; import com.goribun.naive.core.serial.MethodCallUtil; import com.goribun.naive.core.utils.ExceptionUtil; import okhttp3.Request; import okhttp3.Response;
package com.goribun.naive.client.poxy; /** * Rpc代理 * * @author wangxuesong */ public class RpcProxy implements InvocationHandler { private String serviceName; private String host; public RpcProxy(String host, String serviceName) { this.host = host; this.serviceName = serviceName; } /** * 发送请求 * 列入:http://127.0.0.1:8080/service/类名/方法名?args={key1:value1,key2:value2} */ @SuppressWarnings("unchecked") @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); if ("toString".equals(methodName)) { return String.format("host:%s->service:%s", host, serviceName); } if ("hashCode".equals(methodName)) { return null; } String url = host + "/service/" + serviceName + "/" + method.getName(); MethodCallEntity entity = new MethodCallEntity(method, args); String argsJson = MethodCallUtil.getMethodCallStr(entity); url += "?args=" + argsJson; Class returnType = method.getReturnType(); Request request = new Request.Builder().url(url).build(); Response response = OkHttpUtil.getOkHttpClient().newCall(request).execute(); if (response.isSuccessful()) { String resultString = response.body().string(); //接收到的协议体 Protocol protocol = JSON.parseObject(resultString, Protocol.class); if (protocol.getCode() == ProtocolStatus.FAILURE) { throw ExceptionUtil.instanceThrowable(protocol.getExceptionDetail()); } if ("void".equals(returnType.getName()) && "void".equals(resultString)) { return null; } //返回反序列化的值 return JSON.parseObject(JSON.toJSONString(protocol.getData()), returnType); } else {
throw new SysException(SysErCode.OK_HTTP_ERROR);
1
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/dicom/ApplicationActivityEvent.java
[ "public abstract class DICOMActiveParticipantRoleIdCodes extends CodedValueType\n{\n\tprotected DICOMActiveParticipantRoleIdCodes(String value, String meaning)\n\t{\n\t\tsetCodeSystemName(\"DCM\");\n\t\tsetCode(value);\n\t\tsetOriginalText(meaning);\n\t}\n\t/**\n\t * \"DCM\",\"110150\", \"Application\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class Application extends DICOMActiveParticipantRoleIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110150\", \"Application\"\n\t\t */\n\t\tpublic Application()\n\t\t{\n\t\t\tsuper(\"110150\", \"Application\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110151\", \"Application Launcher\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class ApplicationLauncher extends DICOMActiveParticipantRoleIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110151\", \"Application Launcher\"\n\t\t */\n\t\tpublic ApplicationLauncher()\n\t\t{\n\t\t\tsuper(\"110151\", \"Application Launcher\");\n\t\t}\n\t}\n\t\n\t/**\n\t * \"DCM\",\"110152\", \"Destination Role ID\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class Destination extends DICOMActiveParticipantRoleIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110152\", \"Destination Role ID\"\n\t\t */\n\t\tpublic Destination()\n\t\t{\n\t\t\tsuper(\"110152\", \"Destination\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110153\", \"Source Role ID\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class Source extends DICOMActiveParticipantRoleIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110153\", \"Source Role ID\"\n\t\t */\n\t\tpublic Source()\n\t\t{\n\t\t\tsuper(\"110153\", \"Source\");\n\t\t}\n\t}\n\t/**\n\t *\n\t * \"DCM\",\"110154\", \"Destination Media\"\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class DestinationMedia extends DICOMActiveParticipantRoleIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110154\", \"Destination Media\"\n\t\t */\n\t\tpublic DestinationMedia()\n\t\t{\n\t\t\tsuper(\"110154\", \"Destination Media\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110155\", \"Source Media\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class SourceMedia extends DICOMActiveParticipantRoleIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\n\t\t */\n\t\tpublic SourceMedia()\n\t\t{\n\t\t\tsuper(\"110155\", \"Source Media\");\n\t\t}\n\t}\n\n}", "public abstract class DICOMEventIdCodes extends CodedValueType\n{\n\t\n\tprotected DICOMEventIdCodes(String value, String meaning)\n\t{\n\t\tsetCodeSystemName(\"DCM\");\n\t\tsetCode(value);\n\t\tsetOriginalText(meaning);\n\t}\n\t\n\t/**\n\t * \"DCM\",\"110100\",\"Application Activity\"\n\t * \n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static final class ApplicationActivity extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110100\",\"Application Activity\"\n\t\t */\n\t\tpublic ApplicationActivity()\n\t\t{\n\t\t\tsuper(\"110100\",\"Application Activity\");\n\t\t}\t\n\t}\n\n\t\n\t/**\n\t * \"DCM\",\"110101\",\"Audit Log Used\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class AuditLogUsed extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110101\",\"Audit Log Used\"\n\t\t */\n\t\tpublic AuditLogUsed()\n\t\t{\n\t\t\tsuper(\"110101\",\"Audit Log Used\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110102\",\"Begin Transferring DICOM Instances\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class BeginTransferringDICOMInstances extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110102\",\"Begin Transferring DICOM Instances\"\n\t\t */\n\t\tpublic BeginTransferringDICOMInstances()\n\t\t{\n\t\t\tsuper(\"110102\",\"Begin Transferring DICOM Instances\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110103\",\"DICOM Instances Accessed\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class DICOMInstancesAccessed extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110103\",\"DICOM Instances Accessed\"\n\t\t */\n\t\tpublic DICOMInstancesAccessed()\n\t\t{\n\t\t\tsuper(\"110103\",\"DICOM Instances Accessed\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110104\",\"DICOM Instances Transferred\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class DICOMInstancesTransferred extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110104\",\"DICOM Instances Transferred\"\n\t\t */\n\t\tpublic DICOMInstancesTransferred()\n\t\t{\n\t\t\tsuper(\"110104\",\"DICOM Instances Transferred\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110105\",\"DICOM Study Deleted\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class DICOMStudyDeleted extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110105\",\"DICOM Study Deleted\"\n\t\t */\n\t\tpublic DICOMStudyDeleted()\n\t\t{\n\t\t\tsuper(\"110105\",\"DICOM Study Deleted\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110106\",\"Export\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class Export extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110106\",\"Export\"\n\t\t */\n\t\tpublic Export()\n\t\t{\n\t\t\tsuper(\"110106\",\"Export\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110107\",\"Import\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class Import extends DICOMEventIdCodes\n\t{\t\n\t\t/**\n\t\t * \"DCM\",\"110107\",\"Import\"\n\t\t */\n\t\tpublic Import()\n\t\t{ \n\t\t\tsuper(\"110107\",\"Import\");\n\t\t}\n\t}\n\t\n\t/**\n\t * \"DCM\",\"110108\",\"Network Activity\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class NetworkEntry extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110108\",\"Network Entry\"\n\t\t */\n\t\tpublic NetworkEntry()\n\t\t{\n\t\t\tsuper(\"110108\",\"Network Entry\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110109\",\"Order Record\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class OrderRecord extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110109\",\"Order Record\"\n\t\t */\n\t\tpublic OrderRecord()\n\t\t{\n\t\t\tsuper(\"110109\",\"Order Record\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110110\",\"Patient Record\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class PatientRecord extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110110\",\"Patient Record\"\n\t\t */\n\t\tpublic PatientRecord()\n\t\t{\n\t\t\tsuper(\"110110\",\"Patient Record\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110111\",\"Procedure Record\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class ProcedureRecord extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110111\",\"Procedure Record\"\n\t\t */\n\t\tpublic ProcedureRecord()\n\t\t{\n\t\t\tsuper(\"110111\",\"Procedure Record\");\n\t\t}\n\t}\n\t/**\n\t *\n\t * \"DCM\",\"110112\",\"Query\"\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class Query extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110112\",\"Query\"\n\t\t */\n\t\tpublic Query()\n\t\t{\n\t\t\tsuper(\"110112\",\"Query\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110113\",\"Security Alert\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class SecurityAlert extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110113\",\"Security Alert\"\n\t\t */\n\t\tpublic SecurityAlert()\n\t\t{\n\t\t\tsuper(\"110113\",\"Security Alert\");\n\t\t}\n\t}\n\t/**\n\t * \"DCM\",\"110114\", \"User Authentication\"\n\t *\n\t * @since Eclipse OHF IHE 0.1.0\n\t */\n\tpublic static class UserAuthentication extends DICOMEventIdCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110114\", \"User Authentication\"\n\t\t */\n\t\tpublic UserAuthentication()\n\t\t{\n\t\t\tsuper(\"110114\", \"User Authentication\");\n\t\t}\n\t}\n\t\n}", "public abstract class DICOMEventTypeCodes extends CodedValueType\n{\n\n\tprotected DICOMEventTypeCodes(String value, String meaning)\n\t{\n\t\tsetCodeSystemName(\"DCM\");\n\t\tsetCode(value);\n\t\tsetOriginalText(meaning);\n\t}\n\n\n\tpublic static class ApplicationStart extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110120\",\"Application Start\"\n\t\t */\n\t\tpublic ApplicationStart()\n\t\t{\n\t\t\tsuper(\"110120\",\"Application Start\");\n\t\t}\n\t}\n\n\tpublic static class ApplicationStop extends DICOMEventTypeCodes \n\t{\n\t\t/**\n\t\t * \"DCM\",\"110121\",\"Application Stop\"\n\t\t */\n\t\tpublic ApplicationStop()\n\t\t{\n\t\t\tsuper(\"110121\",\"Application Stop\");\n\t\t}\n\t}\n\n\tpublic static class Login extends DICOMEventTypeCodes \n\t{\n\t\t/**\n\t\t * \"DCM\",\"110122\",\"Login\"\n\t\t */\n\t\tpublic Login()\n\t\t{\n\t\t\tsuper(\"110122\",\"Login\");\n\t\t}\n\t}\n\n\tpublic static class Logout extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110123\", \"Logout\"\n\t\t */\n\t\tpublic Logout()\n\t\t{\n\t\t\tsuper(\"110123\", \"Logout\");\n\t\t}\n\t}\n\n\tpublic static class Attach extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110124\", \"Attach\"\n\t\t */\n\t\tpublic Attach()\n\t\t{\n\t\t\tsuper(\"110124\", \"Attach\");\n\t\t}\n\t}\n\n\tpublic static class Detach extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110125\", \"Detach\"\n\t\t */\n\t\tpublic Detach()\n\t\t{\n\t\t\tsuper(\"110125\", \"Detach\");\n\t\t}\n\t}\n\n\tpublic static class NodeAuthentication extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110126\", \"Node Authentication\"\n\t\t */\n\t\tpublic NodeAuthentication()\n\t\t{\n\t\t\tsuper(\"110126\", \"Node Authentication\");\n\t\t}\n\t}\n\n\tpublic static class EmergencyOverrideStarted extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110127\", \"Emergency Override Started\"\n\t\t */\n\t\tpublic EmergencyOverrideStarted()\n\t\t{\n\t\t\tsuper(\"110127\", \"Emergency Override Started\");\n\t\t}\n\t}\n\n\tpublic static class NetworkConfiguration extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110128\", \"Network Configuration\"\n\t\t */\n\t\tpublic NetworkConfiguration()\n\t\t{\n\t\t\tsuper(\"110128\", \"Network Configuration\");\n\t\t}\n\t}\n\n\tpublic static class SecurityConfiguration extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110129\", \"Security Configuration\"\n\t\t */\n\t\tpublic SecurityConfiguration()\n\t\t{\n\t\t\tsuper(\"110129\", \"Security Configuration\");\n\t\t}\n\t}\n\n\tpublic static class HardwareConfiguration extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110130\", \"Hardware Configuration\"\n\t\t */\n\t\tpublic HardwareConfiguration()\n\t\t{\n\t\t\tsuper(\"110130\", \"Hardware Configuration\");\n\t\t}\n\t}\n\n\tpublic static class SoftwareConfiguration extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110131\", \"Software Configuration\"\n\t\t */\n\t\tpublic SoftwareConfiguration()\n\t\t{\n\t\t\tsuper(\"110131\", \"Software Configuration\");\n\t\t}\n\t}\n\n\tpublic static class UseOfRestrictedFunction extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110132\", \"Use of Restricted Function\"\n\t\t */\n\t\tpublic UseOfRestrictedFunction()\n\t\t{\n\t\t\tsuper(\"110132\", \"Use of Restricted Function\");\n\t\t}\n\t}\n\n\tpublic static class AuditRecordingStopped extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110133\", \"Audit Recording Stopped\"\n\t\t */\n\t\tpublic AuditRecordingStopped()\n\t\t{\n\t\t\tsuper(\"110133\", \"Audit Recording Stopped\");\n\t\t}\n\t}\n\n\tpublic static class AuditRecordingStarted extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110134\", \"Audit Recording Started\"\n\t\t */\n\t\tpublic AuditRecordingStarted()\n\t\t{\n\t\t\tsuper(\"110134\", \"Audit Recording Started\");\n\t\t}\n\t}\n\n\tpublic static class ObjectSecurityAttributesChanged extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110135\", \"Object Security Attributes Changed\"\n\t\t */\n\t\tpublic ObjectSecurityAttributesChanged()\n\t\t{\n\t\t\tsuper(\"110135\", \"Object Security Attributes Changed\");\n\t\t}\n\t}\n\n\tpublic static class SecurityRolesChanged extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110136\", \"Security Roles Changed\"\n\t\t */\n\t\tpublic SecurityRolesChanged()\n\t\t{\n\t\t\tsuper(\"110136\", \"Security Roles Changed\");\n\t\t}\n\t}\n\n\tpublic static class UserSecurityAttributesChanged extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110137\", \"User Security Attributes Changed\"\n\t\t */\n\t\tpublic UserSecurityAttributesChanged()\n\t\t{\n\t\t\tsuper(\"110137\", \"User Security Attributes Changed\");\n\t\t}\n\t}\n\n\tpublic static class EmergencyOverrideStopped extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110138\", \"Emergency Override Stopped\"\n\t\t */\n\t\tpublic EmergencyOverrideStopped()\n\t\t{\n\t\t\tsuper(\"110138\", \"Emergency Override Stopped\");\n\t\t}\n\t}\n\n\tpublic static class RemoteServiceOperationStarted extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110139\", \"Remote Service Operation Started\"\n\t\t */\n\t\tpublic RemoteServiceOperationStarted()\n\t\t{\n\t\t\tsuper(\"110139\", \"Remote Service Operation Started\");\n\t\t}\n\t}\n\n\tpublic static class RemoteServiceOperationStopped extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110140\", \"Remote Service Operation Stopped\"\n\t\t */\n\t\tpublic RemoteServiceOperationStopped()\n\t\t{\n\t\t\tsuper(\"110140\", \"Remote Service Operation Stopped\");\n\t\t}\n\t}\n\n\tpublic static class LocalServiceOperationStarted extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110141\", \"Local Service Operation Started\"\n\t\t */\n\t\tpublic LocalServiceOperationStarted()\n\t\t{\n\t\t\tsuper(\"110141\", \"Local Service Operation Started\");\n\t\t}\n\t}\n\n\tpublic static class LocalServiceOperationStopped extends DICOMEventTypeCodes\n\t{\n\t\t/**\n\t\t * \"DCM\",\"110142\", \"Local Service Operation Stopped\"\n\t\t */\n\t\tpublic LocalServiceOperationStopped()\n\t\t{\n\t\t\tsuper(\"110142\", \"Local Service Operation Stopped\");\n\t\t}\n\t}\n\n}", "public interface RFC3881EventCodes\n{\n\t/**\n\t * Event Action codes defined by RFC 3881\n\t * \n\t * @author <a href=\"mailto:[email protected]\">Matthew Davis</a>\n\t * @since OHT IHE Profiles 0.4.0\n\t */\n\tpublic enum RFC3881EventActionCodes\n\t{\n\t\t/**\n\t\t * \"C\", Create\n\t\t */\n\t\tCREATE(\"C\"),\n\t\t/**\n\t\t * \"R\", Read\n\t\t */\n\t\tREAD(\"R\"),\n\t\t/**\n\t\t * \"U\", Update\n\t\t */\n\t\tUPDATE(\"U\"),\n\t\t/**\n\t\t * \"D\", Delete\n\t\t */\n\t\tDELETE(\"D\"),\n\t\t/**\n\t\t * \"E\", Execute\n\t\t */\n\t\tEXECUTE(\"E\");\n\t\t\n\t\tprivate String code;\n\t\t\n\t\tprivate RFC3881EventActionCodes(String code)\n\t\t{\n\t\t\tthis.code = code;\n\t\t}\n\t\t\n\t\tpublic String getCode()\n\t\t{\n\t\t\treturn this.code;\n\t\t}\n\t}\n\n\t\n\t/**\n\t * Event Outcome Indicator codes defined by RFC 3881\n\t * \n\t * @author <a href=\"mailto:[email protected]\">Matthew Davis</a>\n\t * @since OHT IHE Profiles 0.4.0\n\t */\n\tpublic enum RFC3881EventOutcomeCodes\n\t{\n\t\t/**\n\t\t * \"0\", Success\n\t\t */\n\t\tSUCCESS (0),\n\t\t/**\n\t\t * \"4\", Minor Failure\n\t\t */\n\t\tMINOR_FAILURE (4),\n\t\t/**\n\t\t * \"8\", Serious Failure\n\t\t */\n\t\tSERIOUS_FAILURE (8),\n\t\t/**\n\t\t * \"12\", Major Failure\n\t\t */\n\t\tMAJOR_FAILURE (12);\n\t\t\n\t\tprivate Integer code;\n\t\t\n\t\tprivate RFC3881EventOutcomeCodes(int code)\n\t\t{\n\t\t\tthis.code = code;\n\t\t}\n\t\t\n\t\tpublic Integer getCode()\n\t\t{\n\t\t\treturn this.code;\n\t\t}\n\t\t\n\t\tpublic static RFC3881EventOutcomeCodes getCodeForInt(int value)\n\t\t{\n\t\t\tswitch (value) {\n\t\t\t\tcase 4: return MINOR_FAILURE;\n\t\t\t\tcase 8: return SERIOUS_FAILURE;\n\t\t\t\tcase 12: return MAJOR_FAILURE;\n\t\t\t\tdefault: return SUCCESS;\n\t\t\t}\n\t\t}\n\t}\n}", "public enum RFC3881EventOutcomeCodes\n{\n\t/**\n\t * \"0\", Success\n\t */\n\tSUCCESS (0),\n\t/**\n\t * \"4\", Minor Failure\n\t */\n\tMINOR_FAILURE (4),\n\t/**\n\t * \"8\", Serious Failure\n\t */\n\tSERIOUS_FAILURE (8),\n\t/**\n\t * \"12\", Major Failure\n\t */\n\tMAJOR_FAILURE (12);\n\t\t\n\tprivate Integer code;\n\t\t\n\tprivate RFC3881EventOutcomeCodes(int code)\n\t{\n\t\tthis.code = code;\n\t}\n\t\t\n\tpublic Integer getCode()\n\t{\n\t\treturn this.code;\n\t}\n\t\t\n\tpublic static RFC3881EventOutcomeCodes getCodeForInt(int value)\n\t{\n\t\tswitch (value) {\n\t\t\tcase 4: return MINOR_FAILURE;\n\t\t\tcase 8: return SERIOUS_FAILURE;\n\t\t\tcase 12: return MAJOR_FAILURE;\n\t\t\tdefault: return SUCCESS;\n\t\t}\n\t}\n}", "public class GenericAuditEventMessageImpl extends AbstractAuditEventMessageImpl\n{\n\n\tpublic GenericAuditEventMessageImpl( RFC3881EventOutcomeCodes outcome,\n\t\t\t\t\t\t\t\t\t\t RFC3881EventActionCodes action,\n\t\t\t\t\t\t\t\t\t\t CodedValueType id, CodedValueType[] type,\n\t\t\t\t\t\t\t\t\t\t Date eventDateTime,\n\t\t\t\t\t\t\t\t\t\t List<CodedValueType> purposesOfUse)\n\t{\n\t\tsuper(eventDateTime);\n\t\tsetEventIdentification(outcome,action,id,type, purposesOfUse);\n\t}\n\n\tpublic GenericAuditEventMessageImpl( RFC3881EventOutcomeCodes outcome,\n\t\t\t\t\t\t\t\t\t\t RFC3881EventActionCodes action,\n\t\t\t\t\t\t\t\t\t\t CodedValueType id, CodedValueType[] type,\n\t\t\t\t\t\t\t\t\t\t List<CodedValueType> purposesOfUse)\n\t{\n\t\tthis(outcome,action,id,type, new Date(), purposesOfUse);\n\t}\n\n\t@Deprecated\n public GenericAuditEventMessageImpl( RFC3881EventOutcomeCodes outcome,\n RFC3881EventActionCodes action,\n CodedValueType id, CodedValueType[] type)\n {\n this(outcome, action, id, type, null);\n }\n\n\n /**\n\t * Sets a Audit Source Identification block for a given Audit Source ID\n\t * @param sourceId The Audit Source ID to use\n\t */\n\tpublic void setAuditSourceId(String sourceId)\n\t{\n\t\tsetAuditSourceId(sourceId, null, (RFC3881AuditSourceTypes[])null);\n\t}\n\t\n\t/**\n\t * Sets a Audit Source Identification block for a given Audit Source ID\n\t * and Audit Source Enterprise Site ID\n\t * @param sourceId The Audit Source ID to use\n\t * @param enterpriseSiteId The Audit Enterprise Site ID to use\n\t */\n\tpublic void setAuditSourceId(String sourceId, String enterpriseSiteId)\n\t{\n\t\tsetAuditSourceId(sourceId, enterpriseSiteId, (RFC3881AuditSourceTypes[])null);\n\t}\n\t\n\t/**\n\t * Sets a Audit Source Identification block for a given Audit Source ID,\n\t * Audit Source Enterprise Site ID, and a list of audit source type codes\n\t * @param sourceId The Audit Source ID to use\n\t * @param enterpriseSiteId The Audit Enterprise Site ID to use\n\t * @param typeCodes The RFC 3881 Audit Source Type codes to use\n\t *\n\t * @deprecated use {@link #setAuditSourceId(String, String, RFC3881AuditSourceTypes[])}\n\t */\n\tpublic void setAuditSourceId(String sourceId, String enterpriseSiteId, RFC3881AuditSourceTypeCodes[] typeCodes)\n\t{\n\t\taddAuditSourceIdentification(sourceId, enterpriseSiteId, typeCodes);\n\t}\n\n\t/**\n\t * Sets a Audit Source Identification block for a given Audit Source ID,\n\t * Audit Source Enterprise Site ID, and a list of audit source type codes\n\t * @param sourceId The Audit Source ID to use\n\t * @param enterpriseSiteId The Audit Enterprise Site ID to use\n\t * @param typeCodes The RFC 3881 Audit Source Type codes to use\n\t */\n\tpublic void setAuditSourceId(String sourceId, String enterpriseSiteId, RFC3881AuditSourceTypes[] typeCodes)\n\t{\n\t\taddAuditSourceIdentification(sourceId, enterpriseSiteId, typeCodes);\n\t}\n\n}" ]
import org.openhealthtools.ihe.atna.auditor.codes.dicom.DICOMActiveParticipantRoleIdCodes; import org.openhealthtools.ihe.atna.auditor.codes.dicom.DICOMEventIdCodes; import org.openhealthtools.ihe.atna.auditor.codes.dicom.DICOMEventTypeCodes; import org.openhealthtools.ihe.atna.auditor.codes.rfc3881.RFC3881EventCodes; import org.openhealthtools.ihe.atna.auditor.codes.rfc3881.RFC3881EventCodes.RFC3881EventOutcomeCodes; import org.openhealthtools.ihe.atna.auditor.events.GenericAuditEventMessageImpl; import java.util.Collections;
/******************************************************************************* * Copyright (c) 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.openhealthtools.ihe.atna.auditor.events.dicom; /** * Audit Event representing a DICOM 95 Application Activity event (DCM 110100) * * @author <a href="mailto:[email protected]">Matthew Davis</a> */ public class ApplicationActivityEvent extends GenericAuditEventMessageImpl { /** * Creates an application activity event for a given outcome and * DICOM Event Type (e.g. Application Start or Application Stop) * @param outcome Event outcome indicator * @param type The DICOM 95 Event Type */
public ApplicationActivityEvent(RFC3881EventOutcomeCodes outcome, DICOMEventTypeCodes type)
4
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/search/facet/JresTermsFacetTest.java
[ "public class BaseJresTest {\n\n @BeforeClass\n public static void startLocalElasticSearch() {\n ElasticSearchTestInstance.triggerStaticInit();\n }\n\n /**\n * Configured to connect to a local ElasticSearch instance created specifically for unit testing\n */\n protected Jres jres = new Jres(Suppliers.ofInstance(\"http://localhost:9201\"));\n\n}", "public class TermsFacet extends Facet {\n\n private List<Term> terms;\n\n public List<Term> getTerms() {\n return terms;\n }\n\n public static class Term {\n\n private String term;\n private Long count;\n\n public Term() {\n }\n\n public Term(String term, Long count) {\n this.term = term;\n this.count = count;\n }\n\n public String getTerm() {\n return term;\n }\n\n public Long getCount() {\n return count;\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 Term term1 = (Term) o;\n\n if (count != null ? !count.equals(term1.count) : term1.count != null) return false;\n if (term != null ? !term.equals(term1.term) : term1.term != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = term != null ? term.hashCode() : 0;\n result = 31 * result + (count != null ? count.hashCode() : 0);\n return result;\n }\n }\n}", "public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> {\n\n private final String index;\n private final Object settings;\n\n public JresCreateIndex(String index) {\n this(index, null);\n }\n\n public JresCreateIndex(String index, String settingsJson) {\n super(JresAcknowledgedReply.class);\n this.index = index;\n this.settings = settingsJson;\n }\n\n @Override\n public String getHttpMethod() {\n return HttpPut.METHOD_NAME;\n }\n\n @Override\n public String getPath() {\n return index;\n }\n\n @Override\n public Object getPayload() {\n return settings;\n }\n\n}", "@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)\npublic class JresIndexDocument extends JresJsonRequest<JresIndexDocumentReply> implements JresBulkable {\n\n private final @Nullable String index;\n private final @Nullable String type;\n\n private final @Nullable String id;\n private final Object document;\n\n private final Boolean createOnly;\n\n /**\n * Index a document with no specified id. ElasticSearch will generate one. `index` or `type` are nullable\n * if this operation is to be included in a {@link JresBulk} request which specifies a default index or type,\n * respectively.\n */\n public JresIndexDocument(@Nullable String index, @Nullable String type, Object document) {\n this(index, type, null, document);\n }\n\n /**\n * Index a document with a specified id. ElasticSearch will replace any existing document with this id.\n * `index` or `type` are nullable if this operation is to be included in a {@link JresBulk} request which specifies\n * a default index or type, respectively.\n */\n public JresIndexDocument(@Nullable String index, @Nullable String type, @Nullable String id, Object document) {\n this(index, type, id, document, false);\n }\n\n /**\n * Index a document with the specified id. If <code>`create`</code> ElasticSearch will error on an attempt to\n * update an existing document at the given id. `index` or `type` are nullable if this operation is to be included\n * in a {@link JresBulk} request which specifies a default index or type, respectively.\n */\n @JsonCreator\n public JresIndexDocument(@JsonProperty(\"index\") @Nullable String index,\n @JsonProperty(\"type\") @Nullable String type,\n @JsonProperty(\"id\") @Nullable String id,\n @JsonProperty(\"document\") Object document,\n @JsonProperty(\"createOnly\") boolean createOnly) {\n super(JresIndexDocumentReply.class);\n this.index = index;\n this.type = type;\n this.id = id;\n this.document = document;\n this.createOnly = createOnly;\n }\n\n @Override\n @Nullable\n @JsonProperty\n public String getIndex() {\n return index;\n }\n\n @Override\n @Nullable\n @JsonProperty\n public String getType() {\n return type;\n }\n\n @Override\n @Nullable\n @JsonProperty\n public String getId() {\n return id;\n }\n\n @JsonProperty\n public Object getDocument() {\n return document;\n }\n\n @JsonProperty\n public Boolean getCreateOnly() {\n return createOnly;\n }\n\n @Override\n public String getJsonTypeInfo() {\n return JresIndexDocument.class.getName();\n }\n\n @Override\n public String getHttpMethod() {\n return id == null ? HttpPost.METHOD_NAME : HttpPut.METHOD_NAME;\n }\n\n @Override\n public String getPath() {\n String path = slashedPath(index, type) + (id == null ? \"\" : id);\n if (createOnly) {\n path = slashedPath(path) + \"?op_type=create\";\n }\n return path;\n }\n\n @Override\n public Object getAction() {\n return ImmutableMap.of(\"index\", NoNullsMap.of(\n \"_index\", index,\n \"_type\", type,\n \"_id\", id,\n \"op_type\", createOnly ? \"create\" : null\n ));\n }\n\n @Override\n public Object getPayload() {\n return document;\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 JresIndexDocument that = (JresIndexDocument) o;\n\n if (createOnly != null ? !createOnly.equals(that.createOnly) : that.createOnly != null) return false;\n if (document != null ? !document.equals(that.document) : that.document != null) return false;\n if (id != null ? !id.equals(that.id) : that.id != null) return false;\n if (index != null ? !index.equals(that.index) : that.index != null) return false;\n if (type != null ? !type.equals(that.type) : that.type != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = index != null ? index.hashCode() : 0;\n result = 31 * result + (type != null ? type.hashCode() : 0);\n result = 31 * result + (id != null ? id.hashCode() : 0);\n result = 31 * result + (document != null ? document.hashCode() : 0);\n result = 31 * result + (createOnly != null ? createOnly.hashCode() : 0);\n return result;\n }\n}", "public class JresRefresh extends JresJsonRequest<JresShardsReply> {\n\n private final String index;\n\n public JresRefresh(String index) {\n super(JresShardsReply.class);\n this.index = index;\n }\n\n @Override\n public String getHttpMethod() {\n return HttpPost.METHOD_NAME;\n }\n\n @Override\n public String getPath() {\n return JresPaths.slashedPath(index) + \"_refresh\";\n }\n\n @Override\n public Object getPayload() {\n return null;\n }\n}", "public class JresPutMapping extends JresJsonRequest<JresAcknowledgedReply> {\n\n private final String index;\n private final String type;\n private final String mappingJson;\n\n public JresPutMapping(String index, String type) {\n this(index, type, String.format(\"{\\\"%s\\\":{}}\", type));\n }\n\n public JresPutMapping(String index, String type, String mappingJson) {\n super(JresAcknowledgedReply.class);\n this.index = index;\n this.type = type;\n this.mappingJson = mappingJson;\n }\n\n @Override\n public String getHttpMethod() {\n return HttpPut.METHOD_NAME;\n }\n\n @Override\n public String getPath() {\n return JresPaths.slashedPath(index) + JresPaths.slashedPath(type) + \"_mapping\";\n }\n\n @Override\n public Object getPayload() {\n return mappingJson;\n }\n\n}", "public class JresSearch extends JresJsonRequest<JresSearchReply> {\n\n private final @Nullable String index;\n private final @Nullable String type;\n private final Object searchBody;\n\n public JresSearch() {\n this(null, null, new JresSearchBody());\n }\n\n public JresSearch(JresSearchBody searchBody) {\n this(null, null, searchBody);\n }\n\n public JresSearch(@Nullable String index) {\n this(index, null, new JresSearchBody());\n }\n\n public JresSearch(@Nullable String index, @Nullable String type) {\n this(index, type, new JresSearchBody());\n }\n\n public JresSearch(@Nullable String index, @Nullable String type, JresSearchBody searchBody) {\n this(index, type, (Object) searchBody);\n }\n\n public JresSearch(@Nullable String index, @Nullable String type, Object searchBody) {\n super(JresSearchReply.class);\n this.searchBody = searchBody;\n this.index = index;\n this.type = type;\n }\n\n @Override\n public String getHttpMethod() {\n return HttpPost.METHOD_NAME;\n }\n\n @Override\n public String getPath() {\n return JresPaths.slashedPath(index) + JresPaths.slashedPath(type) + \"_search\";\n }\n\n @Override\n public Object getPayload() {\n return searchBody;\n }\n\n}", "public class JresSearchBody {\n\n /**\n * Single entry from {@link JresQuery#queryType()} to the JresQuery itself. Values are objects to support\n * {@link Jres#load(URL, Class)} which isn't smartened up to determine a query's corresponding JresQuery subclass.\n */\n private Map<String, Object> query;\n private List<String> fields;\n private Map<String, Object> facets;\n private Integer size;\n /**\n * Each map is single-keyed from {@link JresSort#sortType()} to the JresSort itself. Values are objects to support\n * {@link Jres#load(URL, Class)} which isn't smartened up to determine a query's corresponding JresQuery subclass.\n */\n private List<Map<String, Object>> sort;\n\n public JresSearchBody query(JresQuery query) {\n this.query = ImmutableMap.<String, Object>of(query.queryType(), query);\n return this;\n }\n\n /**\n * @param queryType e.g. \"match\", \"bool\", \"term\", ...\n * @param queryParams the body of that query, e.g. for \"match\" might be simply\n * <code>ImmutableMap.of(\"field\", \"find this value\")</code>\n */\n public JresSearchBody query(String queryType, Object queryParams) {\n this.query = ImmutableMap.<String, Object>of(queryType, queryParams);\n return this;\n }\n\n /**\n * Replaces the current set of fields in this search. Note that invoking this method with no arguments will set\n * the list of fields to an empty list, which is different than not setting it at all, which would tell\n * elasticsearch to return the default set of fields.\n */\n public JresSearchBody fields(String... fields) {\n this.fields = ImmutableList.<String>builder().add(fields).build();\n return this;\n }\n\n /**\n * Replaces the current set of facets in this search.\n */\n public JresSearchBody facets(JresFacet... facets) {\n ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();\n for (JresFacet facet : facets) {\n builder.put(facet.facetName(), ImmutableMap.of(facet.facetType(), facet));\n }\n this.facets = builder.build();\n return this;\n }\n\n /**\n * Sets the max size of the query results for this search.\n */\n public JresSearchBody size(Integer size) {\n this.size = size;\n return this;\n }\n\n /**\n * Replaces the current set of sorts in this search.\n */\n public JresSearchBody sort(JresSort... sorts) {\n ImmutableList.Builder<Map<String, Object>> builder = ImmutableList.builder();\n for (JresSort sort : sorts) {\n builder.add(ImmutableMap.<String, Object>of(sort.sortType(), sort));\n }\n this.sort = builder.build();\n return this;\n }\n\n /**\n * A means to pull the polymorphic, contained {@link JresQuery} out of this search body. If this JresSearchBody has\n * previously been given {@link #query(JresQuery)} of type {@link JresBoolQuery}, you can get the contained\n * JresBoolQuery back out via <code>JresBoolQuery bool = searchBody.getQuery(JresBoolQuery.class);</code>\n *\n * @param queryClass instance of the type of query of this search\n * @throws RuntimeException if the asked-for type is not the contained query type.\n */\n @SuppressWarnings(\"unchecked\")\n public <T extends JresQuery> T getQuery(Class<T> queryClass) throws RuntimeException {\n final T sampleInstance;\n try {\n sampleInstance = queryClass.newInstance();\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n\n assert getQuery().size() <= 1;\n\n // Polymorphism makes handling this a little tricky. Check the query key, e.g. \"bool\", \"term\", ...\n if (!sampleInstance.queryType().equals(getQuery().keySet().iterator().next())) {\n throw new RuntimeException(\"Contained query is not of the given type, \" + queryClass);\n }\n\n Object queryObj = getQuery().get(sampleInstance.queryType());\n JsonNode queryNode = ObjectMappers.NORMAL.valueToTree(queryObj);\n T querySubtype = ObjectMappers.fromJson(queryNode, queryClass);\n // Swap this instance in, so we can return the one that the caller can modify.\n getQuery().put(querySubtype.queryType(), querySubtype);\n return querySubtype;\n }\n\n ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n // Serializable getter properties\n\n /**\n * see {@link #getQuery(Class)} to retrieve the contained JresQuery\n */\n public Map<String, Object> getQuery() {\n return query;\n }\n\n public List<String> getFields() {\n return fields;\n }\n\n public Map<String, Object> getFacets() {\n return facets;\n }\n\n public Integer getSize() {\n return size;\n }\n\n public List<Map<String, Object>> getSort() {\n return sort;\n }\n}", "public class JresSearchReply extends JresJsonReply {\n\n private Integer took;\n\n @JsonProperty(\"timed_out\")\n private Boolean timedOut;\n\n @JsonProperty(\"_shards\")\n private Shards shards;\n\n private Hits hits;\n\n private Facets facets;\n\n\n public Integer getTook() {\n return took;\n }\n\n public Boolean isTimedOut() {\n return timedOut;\n }\n\n public Shards getShards() {\n return shards;\n }\n\n public Hits getHits() {\n return hits;\n }\n\n public Facets getFacets() {\n return facets;\n }\n\n /**\n * Shortcut to {@link Hit#getSourceAsType(Class)}\n */\n public <T> List<T> getHitsAsType(final Class<T> klass) {\n return Lists.transform(getHits().getHits(), new Function<Hit, T>() {\n @Override\n public T apply(Hit hit) {\n return hit.getSourceAsType(klass);\n }\n });\n }\n\n /**\n * Shortcut to {@link Hit#getSourceAsType(TypeReference)}\n */\n public <T> List<T> getHitsAsType(final TypeReference<T> typeReference) {\n return Lists.transform(getHits().getHits(), new Function<Hit, T>() {\n @Override\n public T apply(Hit hit) {\n return hit.getSourceAsType(typeReference);\n }\n });\n }\n}" ]
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.model.search.TermsFacet; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.request.index.JresIndexDocument; import com.blacklocus.jres.request.index.JresRefresh; import com.blacklocus.jres.request.mapping.JresPutMapping; import com.blacklocus.jres.request.search.JresSearch; import com.blacklocus.jres.request.search.JresSearchBody; import com.blacklocus.jres.response.search.JresSearchReply; import com.google.common.collect.ImmutableMap; import org.junit.Assert; import org.junit.Test; import java.util.Arrays;
/** * Copyright 2015 BlackLocus * * 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.blacklocus.jres.request.search.facet; public class JresTermsFacetTest extends BaseJresTest { @Test public void testTerms() { String index = "JresTermsFacetTest.testTerms".toLowerCase(); String type = "test"; jres.quest(new JresCreateIndex(index)); jres.quest(new JresPutMapping(index, type)); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "one"))); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "two"))); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "two"))); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "three"))); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "three"))); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "three"))); jres.quest(new JresRefresh(index)); JresSearchBody search = new JresSearchBody().size(0).facets(new JresTermsFacet("the_terms", "value"));
JresSearchReply reply = jres.quest(new JresSearch(index, type, search));
8
ds84182/OpenGX
src/main/java/ds/mods/opengx/Glasses.java
[ "public class ComponentButton extends Component implements ManagedEnvironment {\n\t\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentButton>> serverCGX = new WeakHashMap<World,HashMap<UUID,ComponentButton>>();\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentButton>> clientCGX = new WeakHashMap<World,HashMap<UUID,ComponentButton>>();\n\t\n\tpublic static ComponentButton get(UUID uuid, World w, int tier)\n\t{\n\t\tWeakHashMap<World,HashMap<UUID,ComponentButton>> cgxm = w.isRemote ? clientCGX : serverCGX;\n\t\tif (!cgxm.containsKey(w))\n\t\t{\n\t\t\tcgxm.put(w, new HashMap<UUID,ComponentButton>());\n\t\t}\n\t\tHashMap<UUID,ComponentButton> m = cgxm.get(w);\n\t\tif (!m.containsKey(uuid))\n\t\t{\n\t\t\tm.put(uuid, new ComponentButton(uuid, w, tier));\n\t\t}\n\t\treturn m.get(uuid);\n\t}\n\t\n\tNode node = Network.newNode(this, Visibility.Neighbors).withComponent(\"buttons\").create();\n\tpublic EnumSet<Button> downButtons = EnumSet.noneOf(Button.class);\n\t\n\tpublic ComponentButton(UUID uui, World world, int t) {\n\t\tsuper(uui, world, t);\n\t}\n\n\t@Override\n\tpublic Node node() {\n\t\treturn node;\n\t}\n\n\t@Override\n\tpublic void onConnect(Node node) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void onDisconnect(Node node) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void onMessage(Message message) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void load(NBTTagCompound nbt) {\n\t\tif (node != null)\n\t\t\tnode.load(nbt);\n\t}\n\n\t@Override\n\tpublic void save(NBTTagCompound nbt) {\n\t\tif (node != null)\n\t\t\tnode.save(nbt);\n\t}\n\n\t@Override\n\tpublic boolean canUpdate() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic void update() {\n\t\t\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] isDown(Context context, Arguments arguments)\n\t{\n\t\tButton b = null;\n\t\tString arg = arguments.checkString(0).toLowerCase();\n\t\tif (arg.equals(\"action1\"))\n\t\t{\n\t\t\tb = Button.ACTION1;\n\t\t}\n\t\telse if (arg.equals(\"action2\"))\n\t\t{\n\t\t\tb = Button.ACTION2;\n\t\t}\n\t\telse if (arg.equals(\"actionmod\"))\n\t\t{\n\t\t\tb = Button.ACTIONM;\n\t\t}\n\t\telse\n\t\t\tthrow new RuntimeException(\"invalid button id\");\n\t\tSystem.out.println(downButtons.contains(b));\n\t\treturn new Object[]{downButtons.contains(b)};\n\t}\n\n}", "public class ComponentGX extends Component implements ManagedEnvironment {\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentGX>> serverCGX = new WeakHashMap<World,HashMap<UUID,ComponentGX>>();\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentGX>> clientCGX = new WeakHashMap<World,HashMap<UUID,ComponentGX>>();\n\t\n\tpublic static ComponentGX get(UUID uuid, World w, int tier)\n\t{\n\t\tWeakHashMap<World,HashMap<UUID,ComponentGX>> cgxm = w.isRemote ? clientCGX : serverCGX;\n\t\tif (!cgxm.containsKey(w))\n\t\t{\n\t\t\tcgxm.put(w, new HashMap<UUID,ComponentGX>());\n\t\t}\n\t\tHashMap<UUID,ComponentGX> m = cgxm.get(w);\n\t\tif (!m.containsKey(uuid))\n\t\t{\n\t\t\tm.put(uuid, new ComponentGX(uuid, w, tier));\n\t\t}\n\t\treturn m.get(uuid);\n\t}\n\t\n\tpublic static final String serverGXFormat = \"ds.mods.opengx.gx.tier%d.Tier%dGX\";\n\tpublic static final String clientGXFormat = \"ds.mods.opengx.client.gx.tier%d.ClientTier%dGX\";\n\t\n\tNode node = Network.newNode(this, Visibility.Network).withComponent(\"gx\").create();\n\tManagedEnvironment romGX = FileSystem.asManagedEnvironment(FileSystem.fromClass(OpenGX.class, \"opengx\", \"lua/component/gx\"), \"gx\");\n\n\tpublic IGX gx;\n\tpublic ByteArrayDataOutput fifo;\n\tpublic int fifoBytes;\n\tpublic int fifoSize;\n\tpublic boolean initd = false;\n\t\n\tpublic ComponentMonitor monitor;\n\tpublic String monitorAddress;\n\tpublic int monitorDiscoveryCountDown = 10;\n\tpublic MonitorDiscovery currentDiscovery;\n\tpublic int discoverCountDown = 10;\n\tpublic int monitorAddressFailures = 0;\n\t\n\tpublic ComponentGX(UUID uui, World world, int t) {\n\t\tsuper(uui, world, t);\n\t}\n\t\n\t@Override\n\tpublic Node node() {\n\t\treturn node;\n\t}\n\t\n\tpublic void init()\n\t{\n\t\tmonitorAddressFailures = 0;\n\t\tgx = null;\n\t\tfifoSize = (int) Math.pow(2, 11+tier);\n\t\tfifo = ByteStreams.newDataOutput(fifoSize);\n\t\t\n\t\tinitd = true;\n\t}\n\n\t@Override\n\tpublic void onConnect(Node node)\n\t{\n\t\tif (!initd)\n\t\t\tinit();\n\t\tif (node.host() instanceof Context)\n\t\t{\n\t\t\tnode.connect(romGX.node());\n\t\t\tif (monitor != null) node.connect(monitor.node());\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onDisconnect(Node node)\n\t{\n\t\tSystem.out.println(\"Discon\");\n\t\tif (node.host() instanceof Context)\n\t\t{\n\t\t\tnode.disconnect(romGX.node());\n\t\t\tif (monitor != null) node.disconnect(monitor.node());\n\t\t}\n\t\telse if (monitor != null && monitor.node().address().equals(node.address()))\n\t\t{\n\t\t\tmonitor = null;\n\t\t\tfor (Node n : node().reachableNodes())\n\t\t\t{\n\t\t\t\tif (n.host() instanceof Context)\n\t\t\t\t{\n\t\t\t\t\tn.disconnect(node);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (node == node())\n\t\t{\n\t\t\tfor (Node n : romGX.node().reachableNodes())\n\t\t\t{\n\t\t\t\tif (n.host() instanceof Context)\n\t\t\t\t{\n\t\t\t\t\tn.disconnect(romGX.node());\n\t\t\t\t\tif (monitor != null) n.disconnect(monitor.node());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onMessage(Message message) {\n\t\t\n\t}\n\t\n\tpublic void tryInitGX()\n\t{\n\t\tif (gx == null && tier > 0)\n\t\t{\n\t\t\ttry {\n\t\t\t\tgx = (IGX)Class.forName(String.format(worldObj.isRemote ? clientGXFormat : serverGXFormat, tier, tier)).newInstance();\n\t\t\t} catch (InstantiationException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void load(NBTTagCompound nbt) {\n\t\tif (node != null)\n\t\t\tnode.load(nbt);\n\t\ttier = nbt.getInteger(\"tier\")+1;\n\t\tmonitorAddress = nbt.getString(\"monitor\");\n\t\tif (monitorAddress.length() == 0)\n\t\t\tmonitorAddress = null;\n\t\tinit();\n if (romGX != null) {\n \tromGX.load(nbt.getCompoundTag(\"oc:romnode\"));\n }\n \n NBTTagList stateReloadPackets = nbt.getTagList(\"state\", 10);\n if (stateReloadPackets != null)\n {\n \tfor (int i=0; i<stateReloadPackets.tagCount(); i++)\n \t{\n \t\tNBTTagCompound pkt = stateReloadPackets.getCompoundTagAt(i);\n \t\tIGX.DataType type = IGX.DataType.values()[pkt.getInteger(\"type\")];\n \t\tbyte[] data = nbt.getByteArray(\"data\");\n \t\tByteArrayDataInput dat = ByteStreams.newDataInput(data);\n \t\tswitch (type)\n \t\t{\n\t\t\t\tcase FIFO:\n\t\t\t\t\tgx.uploadFIFO(dat,data);\n\t\t\t\t\tbreak;\n\t\t\t\tcase TEXTURE:\n\t\t\t\t\tint id = dat.readShort();\n\t\t\t\t\tint fmt = dat.readByte();\n\t\t\t\t\tint size = dat.readInt();\n\t\t\t\t\tbyte[] texdata = new byte[size];\n\t\t\t\t\tdat.readFully(texdata);\n\t\t\t\t\tgx.uploadTexture((short) id, new ByteArrayInputStream(texdata), (byte) fmt);\n\t\t\t\t\tbreak;\n \t\t}\n \t}\n }\n\t}\n\n\t@Override\n\tpublic void save(NBTTagCompound nbt) {\n\t\tnode.save(nbt);\n\t\tnbt.setInteger(\"tier\", tier-1);\n if (monitorAddress != null)\n \tnbt.setString(\"monitor\",monitorAddress);\n if (romGX != null) {\n final NBTTagCompound nodeNbt = new NBTTagCompound();\n romGX.save(nodeNbt);\n nbt.setTag(\"oc:romnode\",nodeNbt);\n }\n //ArrayList<Pair<DataType, byte[]>> pkts = gx.createMegaUpdate();\n\t}\n\n\t@Override\n\tpublic boolean canUpdate() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic void update() {\n\t\ttryInitGX();\n\t\tif (monitor == null && node != null)\n\t\t{\n\t\t\tif (monitorAddress == null)\n\t\t\t{\n\t\t\t\tif (currentDiscovery == null)\n\t\t\t\t{\n\t\t\t\t\tmonitorDiscoveryCountDown--;\n\t\t\t\t\tif (monitorDiscoveryCountDown <= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmonitorDiscoveryCountDown = 10;\n\t\t\t\t\t\tdiscoverCountDown = 10;\n\t\t\t\t\t\tcurrentDiscovery = new MonitorDiscovery(this);\n\t\t\t\t\t\tnode.sendToVisible(\"monitor_discovery\", currentDiscovery);\n\t\t\t\t\t\tSystem.out.println(\"DISCOVER\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdiscoverCountDown--;\n\t\t\t\t\tif (discoverCountDown <= 0 && currentDiscovery.foundMonitors.size() > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tComponentMonitor closestMonitor = currentDiscovery.foundMonitors.get(0);\n\t\t\t\t\t\t/*double dist = Double.MAX_VALUE;\n\t\t\t\t\t\tfor (TileEntityMonitor te : currentDiscovery.foundMonitors)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (distance(te) < dist)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdist = distance(te);\n\t\t\t\t\t\t\t\tclosestMonitor = te;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}*/\n\t\t\t\t\t\tSystem.out.println(currentDiscovery.foundMonitors.size());\n\t\t\t\t\t\tif (closestMonitor != null)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmonitor = closestMonitor;\n\t\t\t\t\t\t\tmonitor.setOwner(this);\n\t\t\t\t\t\t\tfor (Node noe : node().reachableNodes())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (noe.host() instanceof Context)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tSystem.out.println(\"CTX\");\n\t\t\t\t\t\t\t\t\tnoe.connect(monitor.node());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentDiscovery = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//find it in reachable nodes\n\t\t\t\tfor (Node n : node.reachableNodes())\n\t\t\t\t{\n\t\t\t\t\tif (n.address().equals(monitorAddress))\n\t\t\t\t\t{\n\t\t\t\t\t\tmonitor = (ComponentMonitor) n.host();\n\t\t\t\t\t\tmonitor.setOwner(this);\n\t\t\t\t\t\tfor (Node noe : node().reachableNodes())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (noe.host() instanceof Context)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tSystem.out.println(\"CTX\");\n\t\t\t\t\t\t\t\tnoe.connect(monitor.node());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (monitor == null)\n\t\t\t\t\tmonitorAddressFailures++;\n\t\t\t\tif (monitorAddressFailures > 5)\n\t\t\t\t{\n\t\t\t\t\tmonitorAddress = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\n\t\t}\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] writeInt(Context context, Arguments arguments)\n\t{\n\t\tif (fifoBytes+(4*arguments.count()) > fifoSize)\n\t\t{\n\t\t\treturn new Object[]{false};\n\t\t}\n\t\tfifoBytes += (4*arguments.count());\n\t\tfor (int i = 0; i < arguments.count(); i++)\n\t\t\tfifo.writeInt(arguments.checkInteger(i));\n\t\treturn new Object[]{true};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] writeFloat(Context context, Arguments arguments)\n\t{\n\t\tif (fifoBytes+(4*arguments.count()) > fifoSize)\n\t\t{\n\t\t\treturn new Object[]{false};\n\t\t}\n\t\tfifoBytes += (4*arguments.count());\n\t\tfor (int i = 0; i < arguments.count(); i++)\n\t\t\tfifo.writeFloat((float) arguments.checkDouble(i));\n\t\treturn new Object[]{true};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] writeShort(Context context, Arguments arguments)\n\t{\n\t\tif (fifoBytes+(arguments.count()*2) > fifoSize)\n\t\t{\n\t\t\treturn new Object[]{false};\n\t\t}\n\t\tfifoBytes+=(arguments.count()*2);\n\t\tfor (int i = 0; i < arguments.count(); i++)\n\t\t\tfifo.writeShort(arguments.checkInteger(i));\n\t\treturn new Object[]{true};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] writeByte(Context context, Arguments arguments)\n\t{\n\t\tif (fifoBytes+arguments.count() > fifoSize)\n\t\t{\n\t\t\treturn new Object[]{false};\n\t\t}\n\t\tfifoBytes+=arguments.count();\n\t\tfor (int i = 0; i < arguments.count(); i++)\n\t\t\tfifo.writeByte(arguments.checkInteger(i));\n\t\treturn new Object[]{true};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] writeBytes(Context context, Arguments arguments)\n\t{\n\t\tbyte[] arr = arguments.checkByteArray(0);\n\t\tif (fifoBytes+arr.length > fifoSize)\n\t\t{\n\t\t\treturn new Object[]{false};\n\t\t}\n\t\tfifoBytes+=arr.length;\n\t\tfifo.write(arr);\n\t\treturn new Object[]{true};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] upload(Context context, Arguments arguments)\n\t{\n\t\t//convert fifo to byte array\n\t\tbyte[] data = fifo.toByteArray();\n\t\ttry\n\t\t{\n\t\t\tgx.uploadFIFO(ByteStreams.newDataInput(data),data);\n\t\t\tGXFifoUploadMessage msg = new GXFifoUploadMessage();\n\t\t\tmsg.uuid = uuid;\n\t\t\tmsg.tier = tier;\n\t\t\tmsg.data = data;\n\t\t\tOpenGX.network.sendToAllAround(msg, new TargetPoint(worldObj.provider.dimensionId, own.x(), own.y(), own.z(), 64));\n\t\t}\n\t\tcatch (Exception ex)\n\t\t{\n\t\t\tex.printStackTrace();\n\t\t}\n\t\tdouble waitTime = (((double)fifoBytes)/((double)fifoSize))*(1D/15D);\n\t\t//System.out.println(waitTime);\n\t\t//context.pause(waitTime);\n\t\tfifoBytes = 0;\n\t\tfifo = ByteStreams.newDataOutput(fifoSize);\n\t\treturn null;\n\t}\n\t\n\t@Callback(limit=5)\n\tpublic Object[] uploadTexture(Context context, Arguments arguments)\n\t{\n\t\tbyte id = (byte) arguments.checkInteger(0);\n\t\tbyte[] data = arguments.checkByteArray(1);\n\t\tbyte fmt = (byte) arguments.checkInteger(2);\n\t\t\n\t\tGXTextureUploadMessage msg = new GXTextureUploadMessage();\n\t\tmsg.uuid = uuid;\n\t\tmsg.tier = tier;\n\t\tmsg.id = id;\n\t\tmsg.fmt = fmt;\n\t\tmsg.data = data;\n\t\tOpenGX.network.sendToAllAround(msg, new TargetPoint(worldObj.provider.dimensionId, own.x(), own.y(), own.z(), 64));\n\t\tgx.uploadTexture(id, new ByteArrayInputStream(data), fmt);\n\t\t//technically, the fifo would have to be copied into memory in order for a texture to upload\n\t\t//context.pause((data.length/1024D)*(1/5D));\n\t\t\n\t\treturn null;\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] getFifo(Context context, Arguments arguments)\n\t{\n\t\treturn new Object[]{fifo.toByteArray()};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] getFifoUsage(Context context, Arguments arguments)\n\t{\n\t\treturn new Object[]{fifoBytes};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] getFifoSize(Context context, Arguments arguments)\n\t{\n\t\treturn new Object[]{fifoSize};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] clearFifo(Context context, Arguments arguments)\n\t{\n\t\tfifoBytes = 0;\n\t\tfifo = ByteStreams.newDataOutput(fifoSize);\n\t\treturn null;\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] getError(Context context, Arguments arguments)\n\t{\n\t\treturn new Object[]{gx.getError(), gx.getErrorString()};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] get(Context context, Arguments arguments)\n\t{\n\t\treturn new Object[]{gx.getValue(arguments.checkInteger(0), arguments.checkInteger(1), arguments.checkInteger(2), arguments.checkInteger(3))};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] getTier(Context context, Arguments arguments)\n\t{\n\t\treturn new Object[]{tier};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] getMonitorAddress(Context context, Arguments arguments)\n\t{\n\t\tif (monitor != null)\n\t\t{\n\t\t\tcontext.node().connect(monitor.node());\n\t\t\treturn new Object[]{monitor.node().address()};\n\t\t}\n\t\treturn null;\n\t}\n}", "public class ComponentMonitor extends Component implements ManagedEnvironment {\n\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentMonitor>> serverCGX = new WeakHashMap<World,HashMap<UUID,ComponentMonitor>>();\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentMonitor>> clientCGX = new WeakHashMap<World,HashMap<UUID,ComponentMonitor>>();\n\t\n\tpublic static ComponentMonitor get(UUID uuid, World w, int tier)\n\t{\n\t\tWeakHashMap<World,HashMap<UUID,ComponentMonitor>> cgxm = w.isRemote ? clientCGX : serverCGX;\n\t\tif (!cgxm.containsKey(w))\n\t\t{\n\t\t\tcgxm.put(w, new HashMap<UUID,ComponentMonitor>());\n\t\t}\n\t\tHashMap<UUID,ComponentMonitor> m = cgxm.get(w);\n\t\tif (!m.containsKey(uuid))\n\t\t{\n\t\t\tm.put(uuid, new ComponentMonitor(uuid, w, tier));\n\t\t}\n\t\treturn m.get(uuid);\n\t}\n\t\n\tNode node = Network.newNode(this, Visibility.Network).withComponent(\"gxmonitor\").create();\n\t\n\t@SideOnly(Side.CLIENT)\n\tpublic GXFramebuffer fb;\n\tpublic boolean isInRenderList = false;\n\t\n\tpublic ComponentGX owner;\n\tpublic int width = 128;\n\tpublic int height = 96;\n\t\n\tpublic int countdown = 100;\n\t\n\tpublic Runnable changed;\n\t\n\tpublic ComponentMonitor(UUID uui, World world, int t) {\n\t\tsuper(uui, world, t);\n\t}\n\n\t@Override\n\tpublic Node node() {\n\t\treturn node;\n\t}\n\n\t@Override\n\tpublic void onConnect(Node node) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void onDisconnect(Node node) {\n\t\tSystem.out.println(\"Dis\");\n\t\tif (owner != null && owner.node() == node)\n\t\t{\n\t\t\tsetOwner(null);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onMessage(Message message) {\n\t\tif (message.name().equals(\"monitor_discovery\") && owner == null)\n\t\t{\n\t\t\t((MonitorDiscovery)message.data()[0]).foundMonitors.add(this);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void load(NBTTagCompound nbt) {\n\t\tif (node != null)\n\t\t\tnode.load(nbt);\n\t\twidth = nbt.getInteger(\"width\");\n\t\theight = nbt.getInteger(\"height\");\n\t\tonChanged();\n\t}\n\n\t@Override\n\tpublic void save(NBTTagCompound nbt) {\n\t\tnode.save(nbt);\n\t\tnbt.setInteger(\"width\", width);\n\t\tnbt.setInteger(\"height\", height);\n\t}\n\t\n\tpublic void setOwner(ComponentGX gx)\n\t{\n\t\tif (owner != null)\n\t\t\towner.monitor = null;\n\t\towner = gx;\n\t\tMonitorOwnMessage m = new MonitorOwnMessage();\n\t\tm.muuid = uuid;\n\t\t\n\t\tif (gx != null)\n\t\t{\n\t\t\tm.hasOwner = true;\n\t\t\tm.uuid = gx.uuid;\n\t\t\tm.tier = gx.tier;\n\t\t\tgx.monitor = this;\n\t\t\t\n\t\t\tif (gx.gx != null)\n\t\t\t\tgx.gx.requestRerender();\n\t\t}\n\t\t\n\t\tSystem.out.println(\"set owner of \"+uuid);\n\t\tOpenGX.network.sendToAllAround(m, new TargetPoint(worldObj.provider.dimensionId, own.x(), own.y(), own.z(), 64));\n\t}\n\n\t@Override\n\tpublic boolean canUpdate() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic void update() {\n\t\tif (width<=0) width=128;\n\t\tif (height<=0) height=96;\n\t\tif (countdown-- == 0)\n\t\t{\n\t\t\tcountdown = 100;\n\t\t\tMonitorSizeMessage msm = new MonitorSizeMessage();\n\t\t\tmsm.uuid = uuid;\n\t\t\tmsm.w = width;\n\t\t\tmsm.h = height;\n\t\t\tOpenGX.network.sendToAllAround(msm, new TargetPoint(worldObj.provider.dimensionId, own.x(), own.y(), own.z(), 64));\n\t\t}\n\t}\n\t\n\tpublic void onChanged()\n\t{\n\t\tcountdown = 0;\n\t\tif (changed != null)\n\t\t\tchanged.run();\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] getSize(Context context, Arguments arguments)\n\t{\n\t\treturn new Object[]{width, height};\n\t}\n\t\n\t@Callback(limit=1)\n\tpublic Object[] setSize(Context context, Arguments arguments)\n\t{\n\t\tint w = arguments.checkInteger(0), h = arguments.checkInteger(1);\n\t\tif (w<1 || h<1 || w>512 || h>512)\n\t\t\treturn new Object[]{false, \"Size out of bounds (<0 or >512)\"};\n\t\twidth = w;\n\t\theight = h;\n\t\tonChanged();\n\t\treturn new Object[]{true};\n\t}\n}", "public class ComponentPROM extends Component implements ManagedEnvironment {\n\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentPROM>> serverCGX = new WeakHashMap<World,HashMap<UUID,ComponentPROM>>();\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentPROM>> clientCGX = new WeakHashMap<World,HashMap<UUID,ComponentPROM>>();\n\t\n\tpublic static ComponentPROM get(UUID uuid, World w, int tier)\n\t{\n\t\tWeakHashMap<World,HashMap<UUID,ComponentPROM>> cgxm = w.isRemote ? clientCGX : serverCGX;\n\t\tif (!cgxm.containsKey(w))\n\t\t{\n\t\t\tcgxm.put(w, new HashMap<UUID,ComponentPROM>());\n\t\t}\n\t\tHashMap<UUID,ComponentPROM> m = cgxm.get(w);\n\t\tif (!m.containsKey(uuid))\n\t\t{\n\t\t\tm.put(uuid, new ComponentPROM(uuid, w, tier));\n\t\t}\n\t\treturn m.get(uuid);\n\t}\n\t\n\tNode node = Network.newNode(this, Visibility.Neighbors).withComponent(\"prom\").create();\n\tbyte[] prom = new byte[0];\n\t\n\tpublic ComponentPROM(UUID uui, World world, int t) {\n\t\tsuper(uui, world, t);\n\t}\n\t\n\t@Override\n\tpublic Node node() {\n\t\treturn node;\n\t}\n\n\t@Override\n\tpublic void onConnect(Node node) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void onDisconnect(Node node) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void onMessage(Message message) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void load(NBTTagCompound nbt) {\n\t\tif (node != null)\n\t\t\tnode.load(nbt);\n\t\tprom = nbt.getByteArray(\"data\");\n\t\tSystem.err.println(\"loaded \"+prom.length+\" bytes from nbt \"+prom);\n\t}\n\n\t@Override\n\tpublic void save(NBTTagCompound nbt) {\n\t\tnode.save(nbt);\n\t\tnbt.setByteArray(\"data\", prom);\n\t\tSystem.err.println(\"saved \"+prom.length+\" bytes to nbt\");\n\t\tif (nbt != saveUpper && saveUpper != null)\n\t\t{\n\t\t\tsave(saveUpper);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean canUpdate() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic void update() {\n\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] get(Context context, Arguments arguments)\n\t{\n\t\treturn new Object[]{prom};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] read(Context context, Arguments arguments)\n\t{\n\t\tint index = arguments.checkInteger(0);\n\t\tif (index<1) throw new RuntimeException(\"Index < 1\");\n\t\tif (index>prom.length) throw new RuntimeException(\"Index > \"+prom.length);\n\t\tindex--;\n\t\tint n = arguments.checkInteger(1);\n\t\tif (n<1) throw new RuntimeException(\"N < 1\");\n\t\tif (index+n>prom.length) n = prom.length-index;\n\t\treturn new Object[]{Arrays.copyOfRange(prom, index, index+n)};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] size(Context context, Arguments arguments)\n\t{\n\t\treturn new Object[]{prom.length};\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] set(Context context, Arguments arguments)\n\t{\n\t\tbyte[] nprom = arguments.checkByteArray(0);\n\t\tif (nprom.length > 16384) throw new RuntimeException(\"attempt to write \"+nprom.length+\" bytes (limit 16384)\");\n\t\tprom = nprom;\n\t\treturn null;\n\t}\n\t\n\t@Callback(direct=true)\n\tpublic Object[] log(Context context, Arguments arguments)\n\t{\n\t\tSystem.err.println(arguments.checkString(0));\n\t\treturn null;\n\t}\n\n}", "public class ComponentSensor extends Component implements ManagedEnvironment {\n\t\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentSensor>> serverCGX = new WeakHashMap<World,HashMap<UUID,ComponentSensor>>();\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentSensor>> clientCGX = new WeakHashMap<World,HashMap<UUID,ComponentSensor>>();\n\t\n\tpublic static ComponentSensor get(UUID uuid, World w, int tier)\n\t{\n\t\tWeakHashMap<World,HashMap<UUID,ComponentSensor>> cgxm = w.isRemote ? clientCGX : serverCGX;\n\t\tif (!cgxm.containsKey(w))\n\t\t{\n\t\t\tcgxm.put(w, new HashMap<UUID,ComponentSensor>());\n\t\t}\n\t\tHashMap<UUID,ComponentSensor> m = cgxm.get(w);\n\t\tif (!m.containsKey(uuid))\n\t\t{\n\t\t\tm.put(uuid, new ComponentSensor(uuid, w, tier));\n\t\t}\n\t\treturn m.get(uuid);\n\t}\n\t\n\tNode node = Network.newNode(this, Visibility.Neighbors).withComponent(\"sensors\").create();\n\tpublic Glasses own;\n\t\n\tpublic ComponentSensor(UUID uui, World world, int t) {\n\t\tsuper(uui, world, t);\n\t}\n\n\t@Override\n\tpublic Node node() {\n\t\treturn node;\n\t}\n\n\t@Override\n\tpublic void onConnect(Node node) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void onDisconnect(Node node) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void onMessage(Message message) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void load(NBTTagCompound nbt) {\n\t\tif (node != null)\n\t\t\tnode.load(nbt);\n\t}\n\n\t@Override\n\tpublic void save(NBTTagCompound nbt) {\n\t\tif (node != null)\n\t\t\tnode.save(nbt);\n\t}\n\n\t@Override\n\tpublic boolean canUpdate() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic void update() {\n\t\t\n\t}\n\t\n\t@Callback(direct = true)\n\tpublic Object[] gyro(Context context, Arguments arguments)\n\t{\n\t\treturn new Object[]{own.holder.rotationPitch, own.holder.rotationYawHead};\n\t}\n\t\n\t@Callback(direct = true)\n\tpublic Object[] lookVector(Context context, Arguments arguments)\n\t{\n\t\tVec3 vec = own.holder.getLookVec();\n\t\treturn new Object[]{vec.xCoord,vec.yCoord,vec.zCoord};\n\t}\n\n\t@Callback(direct = true)\n\tpublic Object[] motion(Context context, Arguments arguments)\n\t{\n\t\treturn new Object[]{\n\t\t\t\town.holder.posX-own.holder.lastTickPosX+own.holder.motionX,\n\t\t\t\town.holder.posY-own.holder.lastTickPosY+own.holder.motionY,\n\t\t\t\town.holder.posZ-own.holder.lastTickPosZ+own.holder.motionZ\n\t\t\t};\n\t}\n}", "public class GlassesButtonEventMessage implements IMessage {\n\tpublic Button button;\n\tpublic boolean released;\n\tpublic int duration;\n\n\t@Override\n\tpublic void fromBytes(ByteBuf buf) {\n\t\tbutton = Button.values()[buf.readInt()];\n\t\treleased = buf.readBoolean();\n\t\tif (released)\n\t\t{\n\t\t\tduration = buf.readInt();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void toBytes(ByteBuf buf) {\n\t\tbuf.writeInt(button.ordinal());\n\t\tbuf.writeBoolean(released);\n\t\tif (released)\n\t\t{\n\t\t\tbuf.writeInt(duration);\n\t\t}\n\t}\n\n\tpublic static enum Button {\n\t\tONOFF,\n\t\tSCREENPOWER,\n\t\tACTION1,\n\t\tACTION2,\n\t\tACTIONM\n\t}\n}", "public class GlassesComponentUUIDMessage implements IMessage {\n\tpublic UUID uuid;\n\tpublic HashMap<Integer,Pair<UUID,Integer>> uuids = new HashMap<Integer,Pair<UUID,Integer>>();\n\n\t@Override\n\tpublic void fromBytes(ByteBuf buf) {\n\t\tuuid = new UUID(buf.readLong(),buf.readLong());\n\t\tint num = buf.readInt();\n\t\twhile (num-->0)\n\t\t{\n\t\t\tuuids.put(buf.readInt(), Pair.of(new UUID(buf.readLong(),buf.readLong()), buf.readInt()));\n\t\t}\n\t}\n\n\t@Override\n\tpublic void toBytes(ByteBuf buf) {\n\t\tbuf.writeLong(uuid.getMostSignificantBits());\n\t\tbuf.writeLong(uuid.getLeastSignificantBits());\n\t\tint num = uuids.size();\n\t\tbuf.writeInt(num);\n\t\tfor (Entry<Integer,Pair<UUID,Integer>> e : uuids.entrySet())\n\t\t{\n\t\t\tbuf.writeInt(e.getKey());\n\t\t\tbuf.writeLong(e.getValue().getLeft().getMostSignificantBits());\n\t\t\tbuf.writeLong(e.getValue().getLeft().getLeastSignificantBits());\n\t\t\tbuf.writeInt(e.getValue().getRight());\n\t\t}\n\t}\n\n}", "public class GlassesErrorMessage implements IMessage {\n\tpublic UUID uuid;\n\tpublic String error;\n\n\t@Override\n\tpublic void fromBytes(ByteBuf buf) {\n\t\tuuid = new UUID(buf.readLong(),buf.readLong());\n\t\tint len = buf.readInt();\n\t\tbyte[] er = new byte[len];\n\t\tbuf.readBytes(er);\n\t\terror = new String(er);\n\t}\n\n\t@Override\n\tpublic void toBytes(ByteBuf buf) {\n\t\tbuf.writeLong(uuid.getMostSignificantBits());\n\t\tbuf.writeLong(uuid.getLeastSignificantBits());\n\t\tbuf.writeInt(error.length());\n\t\tbuf.writeBytes(error.getBytes());\n\t}\n\n}" ]
import java.util.ArrayList; import java.util.Iterator; import java.util.Map.Entry; import java.util.UUID; import java.util.WeakHashMap; import li.cil.oc.api.FileSystem; import li.cil.oc.api.Machine; import li.cil.oc.api.Network; import li.cil.oc.api.driver.Container; import li.cil.oc.api.machine.Owner; import li.cil.oc.api.network.ManagedEnvironment; import li.cil.oc.api.network.Node; import li.cil.oc.server.component.WirelessNetworkCard; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import org.apache.commons.lang3.tuple.Pair; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; import cpw.mods.fml.relauncher.Side; import ds.mods.opengx.component.ComponentButton; import ds.mods.opengx.component.ComponentGX; import ds.mods.opengx.component.ComponentMonitor; import ds.mods.opengx.component.ComponentPROM; import ds.mods.opengx.component.ComponentSensor; import ds.mods.opengx.network.GlassesButtonEventMessage; import ds.mods.opengx.network.GlassesComponentUUIDMessage; import ds.mods.opengx.network.GlassesErrorMessage;
package ds.mods.opengx; public class Glasses implements Owner, Container { public static WeakHashMap<World, ArrayList<Glasses>> svmap = new WeakHashMap<World, ArrayList<Glasses>>(); public static WeakHashMap<World, ArrayList<Glasses>> clmap = new WeakHashMap<World, ArrayList<Glasses>>(); public static WeakHashMap<World, ArrayList<Glasses>> getMap() { return FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT ? clmap : svmap; } public static Glasses get(UUID uuid, World w) { WeakHashMap<World, ArrayList<Glasses>> map = getMap(); Glasses g = null; if (map.get(w) == null) { System.out.println("NO ARRAY LIST"); return null; } for (Glasses _g : map.get(w)) { if (_g.uuid.equals(uuid)) { g = _g; break; } } return g; } public static void updateAll() { Iterator<Entry<World, ArrayList<Glasses>>> iter = getMap().entrySet().iterator(); while (iter.hasNext()) { Entry<World, ArrayList<Glasses>> e = iter.next(); Iterator<Glasses> giter = e.getValue().iterator(); while (giter.hasNext()) { Glasses g = giter.next(); if (g.hasntUpdatedIn++ > 200) { //turn off! g.turnOff(); giter.remove(); } } } } public int hasntUpdatedIn = 0; public li.cil.oc.api.machine.Machine machine = null; public EntityPlayer holder; public ItemStack stack; public UUID uuid = UUID.randomUUID(); public ComponentSensor sensors; public ComponentButton buttons; public ComponentGX gx;
public ComponentMonitor monitor;
2
CodeAndMagic/android-deferred-object
core/src/test/java/org/codeandmagic/promise/tests/PipePromisesTests.java
[ "public class DeferredObject<Success> extends AbstractPromise<Success> {\n\n public static <S> DeferredObject<S> successful(S value) {\n final DeferredObject<S> deferredObject = new DeferredObject<S>();\n deferredObject.success(value);\n return deferredObject;\n }\n\n public static <S> DeferredObject<S> failed(Throwable value) {\n final DeferredObject<S> deferredObject = new DeferredObject<S>();\n deferredObject.failure(value);\n return deferredObject;\n }\n\n public static <T, S extends T> DeferredObject<T[]> merge(Class<T> clazz, Promise<S>... promises) {\n return new MergePromise<T, S>(clazz, 0, promises);\n }\n\n public static <T, S extends T> DeferredObject<T[]> merge(Class<T> clazz, int allowedFailures, Promise<S>... promises) {\n return new MergePromise<T, S>(clazz, allowedFailures, promises);\n }\n\n @Override\n public void success(Success resolved) {\n super.success(resolved);\n }\n\n @Override\n public void failure(Throwable throwable) {\n super.failure(throwable);\n }\n\n @Override\n public void progress(Float progress) {\n super.progress(progress);\n }\n\n public static class MergePromise<T, S extends T> extends DeferredObject<T[]> {\n\n private final Promise<S>[] mPromises;\n private final int mLength;\n private final int mAllowedFailures;\n\n private final Throwable[] mFailures;\n private final T[] mSuccesses;\n private int mCountCompleted = 0;\n private int mCountFailures = 0;\n\n\n private Callback<Throwable> newFailureCallback(final int index) {\n return new Callback<Throwable>() {\n @Override\n public void onCallback(Throwable result) {\n synchronized (MergePromise.this) {\n mFailures[index] = result;\n mCountCompleted++;\n mCountFailures++;\n MergePromise.this.progress((float) mCountCompleted);\n\n if (mCountFailures > mAllowedFailures) {\n MergePromise.this.failure(new MergeFailure(\"Failed MergePromise because more than '\"\n + mAllowedFailures + \"' promises have failed.\", mFailures));\n }\n }\n }\n };\n }\n\n private Callback<S> newSuccessCallback(final int index) {\n return new Callback<S>() {\n @Override\n public void onCallback(S result) {\n synchronized (MergePromise.this) {\n mSuccesses[index] = result;\n mCountCompleted++;\n MergePromise.this.progress((float) mCountCompleted);\n\n if (mCountCompleted == mLength) {\n MergePromise.this.success(mSuccesses);\n }\n }\n }\n };\n }\n\n public MergePromise(Class<T> clazz, int allowedFailures, Promise<S>... promises) {\n if (promises.length < 1) {\n throw new IllegalArgumentException(\"You need at least one promise.\");\n }\n\n mPromises = promises;\n mLength = promises.length;\n mAllowedFailures = allowedFailures < 0 ? promises.length : allowedFailures;\n\n mFailures = new Throwable[mLength];\n mSuccesses = (T[]) Array.newInstance(clazz, mLength);\n\n for (int i = 0; i < mLength; ++i) {\n final Promise<S> promise = promises[i];\n promise.onSuccess(newSuccessCallback(i));\n promise.onFailure(newFailureCallback(i));\n }\n }\n }\n}", "public interface Pipe<T1, T2> {\n\n Promise<T2> transform(T1 value);\n}", "public interface Promise<Success> extends Promise3<Success, Throwable, Float> {\n\n @Override\n public Promise<Success> onSuccess(Callback<Success> onSuccess);\n\n @Override\n public Promise<Success> onFailure(Callback<Throwable> onFailure);\n\n @Override\n public Promise<Success> onProgress(Callback<Float> onProgress);\n\n @Override\n public Promise<Success> onComplete(Callback<Either<Throwable, Success>> onComplete);\n\n @Override\n public <Success2> Promise<Success2> map(final Transformation<Success, Success2> transform);\n\n @Override\n public <Success2> Promise<Success2> flatMap(final Transformation<Success, Either<Throwable, Success2>> transform);\n\n @Override\n public Promise<Success> andThen(Callback<Success> onSuccess,\n Callback<Throwable> onFailure,\n Callback<Float> onProgress);\n\n @Override\n public Promise<Success> flatRecover(final Transformation<Throwable, Either<Throwable, Success>> transform);\n\n @Override\n public Promise<Success> recover(final Transformation<Throwable, Success> transform);\n\n\n public <Success2> Promise<Success2> pipe(final Pipe<Success, Success2> transform);\n\n public Promise<Success> recoverWith(final Pipe<Throwable, Success> transform);\n\n @Override\n public Promise<Success> runOnUiThread();\n\n /**\n * <b>IMPORTANT NOTE</b>\n * This method operates on the assumption that the Success of this Promise is an {@link java.util.Collection<T1>}.\n * If not, it will fail with a {@link ClassCastException}.\n * <p/>\n * This method creates a list of Promises by applying a {@link Pipe} to each\n * element in the {@link java.util.Collection<T1>}.\n * <p/>\n *\n * @param transform the {@link Transformation} to be applied to each element\n * @param <T1>\n * @param <T2>\n * @return\n */\n public <T1, T2> Promises<T2> split(Pipe<T1, T2> transform);\n}", "public interface Pipe3<T1, T2, Failure> {\n\n Promise3<T2, Failure, Void> transform(T1 value);\n}", "public class DeferredObject3<Success, Failure, Progress> extends AbstractPromise3<Success, Failure, Progress> {\n\n public static <S, F, P> DeferredObject3<S, F, P> successful(S value) {\n final DeferredObject3<S, F, P> deferredObject = new DeferredObject3<S, F, P>();\n deferredObject.success(value);\n return deferredObject;\n }\n\n public static <S, F, P> DeferredObject3<S, F, P> failed(F value) {\n final DeferredObject3<S, F, P> deferredObject = new DeferredObject3<S, F, P>();\n deferredObject.failure(value);\n return deferredObject;\n }\n\n @Override\n public final void progress(Progress progress) {\n super.progress(progress);\n }\n\n @Override\n public final void success(Success resolved) {\n super.success(resolved);\n }\n\n @Override\n public final void failure(Failure failure) {\n super.failure(failure);\n }\n}" ]
import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; import org.codeandmagic.promise.*; import org.codeandmagic.promise.impl.DeferredObject; import org.codeandmagic.promise.Pipe; import org.codeandmagic.promise.Promise; import org.codeandmagic.promise.Pipe3; import org.codeandmagic.promise.impl.DeferredObject3; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static java.lang.System.currentTimeMillis;
/* * Copyright (c) 2014 Cristian Vrabie, Evelina Vrabie. * * This file is part of android-promise. * android-deferred-object 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. * * android-promise 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 android-promise * If not, see <http://www.gnu.org/licenses/>. */ package org.codeandmagic.promise.tests; /** * Created by cristian on 11/02/2014. */ @RunWith(JUnit4.class) public class PipePromisesTests { public Promise<Integer> deferredInt(final int number) { final DeferredObject<Integer> deferredObject = new DeferredObject<Integer>(); new Thread() { @Override public void run() { try { Thread.sleep(1000); deferredObject.success(number); } catch (InterruptedException e) { deferredObject.failure(e); } } }.start(); return deferredObject; } public Promise<Integer> deferredException() { final DeferredObject<Integer> deferredObject = new DeferredObject<Integer>(); new Thread() { @Override public void run() { try { Thread.sleep(1000); deferredObject.failure(new Exception("Failed!")); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); return deferredObject; } @Test public void testPipe() { Callback<String> onSuccess = mock(Callback.class); Callback<Throwable> onFailure = mock(Callback.class); DeferredObject3.<Integer, Throwable, Void>successful(3).pipe(new Pipe3<Integer, String, Throwable>() { @Override public Promise3<String, Throwable, Void> transform(Integer value) { return DeferredObject3.<String, Throwable, Void>failed(new Exception("Failed")); } }).onSuccess(onSuccess).onFailure(onFailure); verify(onSuccess, never()).onCallback(anyString()); verify(onFailure, only()).onCallback(any(Exception.class)); } @Test @Ignore public void testPipeMultiThreaded() { Callback<Integer> onSuccess1 = mock(Callback.class); Callback<Throwable> onFailure1 = mock(Callback.class); Callback<Integer> onSuccess2 = mock(Callback.class); Callback<Throwable> onFailure2 = mock(Callback.class); long start = currentTimeMillis(); Promise<Integer> exception = deferredException().onSuccess(onSuccess1).onFailure(onFailure1);
Promise<Integer> number = exception.recoverWith(new Pipe<Throwable, Integer>() {
1
fiware-cybercaptor/cybercaptor-server
src/main/java/org/fiware/cybercaptor/server/remediation/DeployableRemediation.java
[ "public class AttackPath extends MulvalAttackGraph implements Cloneable {\n\n /**\n * The scoring of the attack path (should be between 0 and 1)\n */\n public double scoring = 0;\n /**\n * The goal of the attacker\n */\n Vertex goal = null;\n\n /**\n * @param leavesToCorrect the list of leaves that should be corrected\n * @param indexInPath the index where we are in the list of leaves\n * @param howToRemediateLeaves a vector of how each leaf can be corrected\n * @return The list of remediation actions : A1 OR A2 OR A3 where A1 = A1.1 AND A1.2 AND A1.3 ...\n */\n static private List<List<RemediationAction>> computeRemediationToPathWithLeafRemediations(List<Vertex> leavesToCorrect, int indexInPath, HashMap<Integer, List<List<RemediationAction>>> howToRemediateLeaves) {\n\n //Recursive function on the number of remaining leaves to correct\n\n if (indexInPath > leavesToCorrect.size() - 1) { //path empty\n //Normally this case should never happen\n\n return new ArrayList<List<RemediationAction>>();\n } else if (indexInPath == leavesToCorrect.size() - 1) { //one leaf\n //Stop case of the recursion, we return the mean to correct only one leaf\n Vertex currentLeaf = leavesToCorrect.get(indexInPath);\n\n return howToRemediateLeaves.get(currentLeaf.id);\n } else { //more than one leaf in path\n Vertex currentLeaf = leavesToCorrect.get(indexInPath);\n\n //First we correct the other leaves and get the result\n List<List<RemediationAction>> result_remediation_path_without_last_leaf = computeRemediationToPathWithLeafRemediations(leavesToCorrect, indexInPath + 1, howToRemediateLeaves);\n\n List<List<RemediationAction>> resultWithoutLastLeaf = new ArrayList<List<RemediationAction>>();\n for (List<RemediationAction> aResult_remediation_path_without_last_leaf1 : result_remediation_path_without_last_leaf) {\n List<RemediationAction> contentResultToDuplicate = new ArrayList<RemediationAction>(aResult_remediation_path_without_last_leaf1);\n resultWithoutLastLeaf.add(contentResultToDuplicate);\n }\n\n List<List<RemediationAction>> result_to_duplicate = new ArrayList<List<RemediationAction>>();\n for (List<RemediationAction> aResult_remediation_path_without_last_leaf : result_remediation_path_without_last_leaf) {\n List<RemediationAction> contentResultToDuplicate = new ArrayList<RemediationAction>(aResult_remediation_path_without_last_leaf);\n result_to_duplicate.add(contentResultToDuplicate);\n }\n\n\n List<List<RemediationAction>> result = new ArrayList<List<RemediationAction>>();\n\n //Then, we add each element of remediation concerning the current leaf:\n List<List<RemediationAction>> howToRemediateLeaf = howToRemediateLeaves.get(currentLeaf.id);\n\n //FOR ALL OR CONDITIONS (remediations of the current leaf)\n //we duplicate the old result (result_remediation_path_without_last_leaf) howToRemediateLeaf.size() - 1 times\n //and add all the howToRemediateLeaf.get(i) to each duplicates\n\n //For the first OR, no duplicate is useful\n //Add the howToRemediateLeaf.get(i) to all OR elements\n for (List<RemediationAction> aResultWithoutLastLeaf : resultWithoutLastLeaf) {\n aResultWithoutLastLeaf.addAll(new ArrayList<RemediationAction>(howToRemediateLeaf.get(0)));\n }\n result.addAll(resultWithoutLastLeaf);\n\n //For the other OR, we can duplicate\n for (int i = 1; i < howToRemediateLeaf.size(); i++) {\n //Create the duplicate and add the howToRemediateLeaf.get(i) results into it\n List<List<RemediationAction>> duplicate = new ArrayList<List<RemediationAction>>();\n for (List<RemediationAction> aResult_to_duplicate : result_to_duplicate) {\n List<RemediationAction> duplicateContent = new ArrayList<RemediationAction>(aResult_to_duplicate);\n duplicate.add(duplicateContent);\n }\n\n //For all OR of the duplicate, add the howToRemediateLeaf.get(i)\n for (List<RemediationAction> aDuplicate : duplicate) {\n aDuplicate.addAll(new ArrayList<RemediationAction>(howToRemediateLeaf.get(i)));\n }\n result.addAll(duplicate);\n }\n\n return result;\n }\n }\n\n /**\n * Compute all possible combination of k integers < to n\n *\n * @param k integer < n\n * @param n integer\n * @return the list of list of k integers\n */\n public static List<List<Integer>> combination(int k, int n) {\n List<Integer> listNumber = new ArrayList<Integer>();\n for (int i = 0; i < n; i++) {\n listNumber.add(i);\n }\n List<List<Integer>> result = new ArrayList<List<Integer>>();\n combinationRecursive(k, listNumber, 0, new ArrayList<Integer>(), result);\n return result;\n }\n\n /**\n * Main recursive function used to calculate the combination list combination(k,n)\n */\n private static void combinationRecursive(int k, List<Integer> listNumber, int startListNumber, List<Integer> temporaryResult, List<List<Integer>> result) {\n if (k == 0) {\n result.add(new ArrayList<Integer>(temporaryResult));\n temporaryResult.clear();\n return;\n }\n if (listNumber.size() == startListNumber) return;\n\n List<Integer> temporaryResult2 = new ArrayList<Integer>(temporaryResult);\n temporaryResult.add(listNumber.get(startListNumber));\n combinationRecursive(k - 1, listNumber, startListNumber + 1, temporaryResult, result);\n combinationRecursive(k, listNumber, startListNumber + 1, temporaryResult2, result);\n }\n\n /**\n * Get all the machines that are involved in this attack path considered only as a list of vertices\n *\n * @param topology the Network topology\n * @param attackPath the attack path to explore\n * @return the list of machine involved in this attack path\n * @throws Exception\n */\n public static List<InformationSystemHost> getInvolvedMachines(InformationSystem topology, List<Vertex> attackPath) throws Exception {\n List<InformationSystemHost> result = new ArrayList<InformationSystemHost>();\n for (Vertex vertex : attackPath) {\n if (vertex.fact != null && vertex.fact.type != FactType.RULE) {\n InformationSystemHost machine = vertex.getRelatedMachine(topology);\n result.add(machine);\n }\n }\n return result;\n }\n\n public static List<AttackPath> loadAttackPathsFromFile(String attackPathsFilePath, AttackGraph relatedAttackGraph) throws Exception {\n FileInputStream file = new FileInputStream(attackPathsFilePath);\n SAXBuilder sxb = new SAXBuilder();\n Document document = sxb.build(file);\n Element root = document.getRootElement();\n\n List<AttackPath> result = new ArrayList<AttackPath>();\n\n List<Element> attackPathsElements = root.getChildren(\"attack_path\");\n if (!attackPathsElements.isEmpty()) {\n for (Element attackPathElement : attackPathsElements) {\n if (attackPathElement != null) {\n AttackPath attackPath = new AttackPath();\n attackPath.loadFromDomElementAndAttackGraph(attackPathElement, relatedAttackGraph);\n result.add(attackPath);\n }\n }\n }\n sortAttackPaths(result);\n\n return result;\n\n }\n\n /**\n * Sort attack paths with their scoring in descending order\n */\n public static void sortAttackPaths(List<AttackPath> attackPathList) {\n Collections.sort(attackPathList, new AttackPath.AttackPathComparator());\n }\n\n /**\n * @return the leaves of the attack graph\n */\n public List<Vertex> getLeavesThatCanBeRemediated() {\n List<Vertex> result = new ArrayList<Vertex>();\n for (int i : this.vertices.keySet()) {\n Vertex vertex = this.vertices.get(i);\n vertex.computeParentsAndChildren(this);\n if (vertex.parents.size() == 0) {\n if (vertex.fact != null && vertex.fact.datalogCommand != null\n && vertex.fact.datalogCommand.command != null) {\n String command = vertex.fact.datalogCommand.command;\n if (command.equals(\"vulExists\") || command.equals(\"hacl\") || command.equals(\"haclprimit\") || command.toLowerCase().contains(\"vlan\") || command.contains(\"attackerLocated\"))\n result.add(vertex);\n }\n } else {\n if (vertex.fact != null && vertex.fact.datalogCommand != null\n && vertex.fact.datalogCommand.command != null && vertex.fact.datalogCommand.command.equals(\"hacl\")) {\n result.add(vertex);\n }\n }\n }\n return result;\n }\n\n /**\n * @return the goal of the attack graph\n */\n public Vertex getGoal() {\n if (goal == null) {\n for (int i : this.vertices.keySet()) {\n Vertex vertex = this.vertices.get(i);\n vertex.computeParentsAndChildren(this);\n if (vertex.children.size() == 0)\n goal = vertex;\n }\n }\n return goal;\n }\n\n /**\n * @param topology the network topology\n * @param conn database connection\n * @return the list of possible remediation actions to remediate this attack path : remediation[1] OR remediation[2] OR remediation[3] ; remediation[1] = remediation[1][1] AND remediation[1][2]...\n */\n public List<List<RemediationAction>> getRemediationAction(InformationSystem topology, Connection conn, String costParametersFolder) throws Exception {\n List<List<RemediationAction>> result = new ArrayList<List<RemediationAction>>();\n\n\n List<Vertex> leaves = this.getLeavesThatCanBeRemediated();\n\n //Compute all possible sufficient combination of leaves to cut the attack path\n List<List<Vertex>> sufficientLeavesToCutPath = new ArrayList<List<Vertex>>();\n List<Vertex> remainingLeaves = new ArrayList<Vertex>(leaves);\n int simultaneousLeavesNumber = 1;\n\n while (simultaneousLeavesNumber <= remainingLeaves.size()) { //While we take a number of leaves lower than the number of remaining leaves\n List<List<Integer>> combination = combination(simultaneousLeavesNumber, remainingLeaves.size());\n List<Vertex> leavesSufficient = new ArrayList<Vertex>();\n\n for (List<Integer> aCombination : combination) {\n List<Vertex> leavesToTest = new ArrayList<Vertex>();\n for (Integer anACombination : aCombination) {\n leavesToTest.add(remainingLeaves.get(anACombination));\n }\n if (leavesMandatoryForGoal(leavesToTest)) {\n sufficientLeavesToCutPath.add(leavesToTest);\n leavesSufficient.addAll(leavesToTest);\n }\n }\n\n for (Vertex aLeavesSufficient : leavesSufficient) {\n remainingLeaves.remove(aLeavesSufficient);\n }\n\n simultaneousLeavesNumber++;\n }\n\n //Create a hashlist of the list of remediation for each leaf (possible_actions[1] OR possible_actions[2] OR possible_actions[3] .... with possible_actions[1] = possible_actions[1][1] AND possible_actions[1][2] AND possible_actions[1][3]\n HashMap<Integer, List<List<RemediationAction>>> howToRemediateLeaves = new HashMap<Integer, List<List<RemediationAction>>>();\n for (Vertex leaf : leaves) {\n howToRemediateLeaves.put(leaf.id, getRemediationActionForLeaf(leaf, topology, conn, costParametersFolder));\n }\n\n\n //Try to see how to remediate each list of leaf\n for (List<Vertex> aSufficientLeavesToCutPath : sufficientLeavesToCutPath) {\n //List<RemediationAction> pathRemediations = new ArrayList<RemediationAction>();\n boolean pathCanBeRemediated = true;\n\n //For all leaf list that can cut the attack path\n for (Vertex leaf : aSufficientLeavesToCutPath) {\n if (howToRemediateLeaves.get(leaf.id).isEmpty())\n pathCanBeRemediated = false;\n\n }\n if (pathCanBeRemediated) {\n result.addAll(computeRemediationToPathWithLeafRemediations(aSufficientLeavesToCutPath, 0, howToRemediateLeaves));\n }\n }\n\n return result;\n }\n\n /**\n * @param topology the network topology\n * @param conn database connection\n * @return the list of possible remediation actions to remediate this attack path : remediation[1] OR remediation[2] OR remediation[3] ; remediation[1] = remediation[1][1] AND remediation[1][2]... [Withour snort rules]\n */\n public List<List<RemediationAction>> getRemedationActions(InformationSystem topology, Connection conn, String costParametersFolder) throws Exception {\n List<List<RemediationAction>> result = new ArrayList<List<RemediationAction>>();\n\n\n List<Vertex> leaves = this.getLeavesThatCanBeRemediated();\n\n //Compute all possible sufficient combination of leaves to cut the attack path\n List<List<Vertex>> sufficientLeavesToCutPath = new ArrayList<List<Vertex>>();\n List<Vertex> remainingLeaves = new ArrayList<Vertex>(leaves);\n int simultaneousLeavesNumber = 1;\n\n while (simultaneousLeavesNumber <= remainingLeaves.size()) { //While we take a number of leaves lower than the number of remaining leaves\n List<List<Integer>> combination = combination(simultaneousLeavesNumber, remainingLeaves.size());\n List<Vertex> leavesSufficient = new ArrayList<Vertex>();\n\n //TODO : improve this function : can be much faster.\n for (List<Integer> aCombination : combination) {\n List<Vertex> leavesToTest = new ArrayList<Vertex>();\n for (Integer anACombination : aCombination) {\n leavesToTest.add(remainingLeaves.get(anACombination));\n }\n if (leavesMandatoryForGoal(leavesToTest)) {\n sufficientLeavesToCutPath.add(leavesToTest);\n leavesSufficient.addAll(leavesToTest);\n }\n }\n\n for (Vertex aLeavesSufficient : leavesSufficient) {\n remainingLeaves.remove(aLeavesSufficient);\n }\n\n simultaneousLeavesNumber++;\n }\n\n //Create a hashlist of the list of remediation for each leaf (possible_actions[1] OR possible_actions[2] OR possible_actions[3] .... with possible_actions[1] = possible_actions[1][1] AND possible_actions[1][2] AND possible_actions[1][3]\n HashMap<Integer, List<List<RemediationAction>>> howToRemediateLeaves = new HashMap<Integer, List<List<RemediationAction>>>();\n for (Vertex leaf : leaves) {\n howToRemediateLeaves.put(leaf.id, getRemediationActionForLeaf(leaf, topology, conn, costParametersFolder, true));\n }\n\n\n //Try to see how to remediate each list of leaf\n for (List<Vertex> aSufficientLeavesToCutPath : sufficientLeavesToCutPath) {\n //List<RemediationAction> pathRemediations = new ArrayList<RemediationAction>();\n boolean pathCanBeRemediated = true;\n\n //For all leaf list that can cut the attack path\n for (Vertex leaf : aSufficientLeavesToCutPath) {\n if (howToRemediateLeaves.get(leaf.id).isEmpty())\n pathCanBeRemediated = false;\n\n }\n if (pathCanBeRemediated) {\n result.addAll(computeRemediationToPathWithLeafRemediations(aSufficientLeavesToCutPath, 0, howToRemediateLeaves));\n }\n }\n\n return result;\n }\n\n /**\n * @param topology the network topology\n * @param conn the database connection\n * @param costParametersFolder the folder where the cost parameters are stored\n * @return the list of deployable remediations without snort rules\n * @throws Exception\n */\n public List<DeployableRemediation> getDeployableRemediations(InformationSystem topology, Connection conn, String costParametersFolder) throws Exception {\n List<List<RemediationAction>> remediationActions = this.getRemedationActions(topology, conn, costParametersFolder);\n List<DeployableRemediation> result = new ArrayList<DeployableRemediation>();\n\n //For all \"OR\" remediations\n for (List<RemediationAction> remediationAction1 : remediationActions) {\n List<DeployableRemediation> result_tmp = new ArrayList<DeployableRemediation>(); //Result for only this group of remediations\n DeployableRemediation dr = new DeployableRemediation(this, topology);\n dr.setActions(new ArrayList<DeployableRemediationAction>());\n result_tmp.add(dr);\n\n //For all \"AND\" remediations\n for (RemediationAction remediationAction : remediationAction1) {\n if (remediationAction.getPossibleMachines().size() > 1) {\n //ALL MACHINES EXCEPT THE FIRST ONE\n List<DeployableRemediation> resultForThisRemediationAction = new ArrayList<DeployableRemediation>(); //Result for only this group of remediations\n for (int m = 1; m < remediationAction.getPossibleMachines().size(); m++) {\n //For all the previously added Deployable Remediation Actions\n for (DeployableRemediation aResult_tmp : result_tmp) {\n DeployableRemediation newdr = new DeployableRemediation(this, topology);\n resultForThisRemediationAction.add(newdr);\n newdr.getActions().addAll(aResult_tmp.getActions());\n DeployableRemediationAction deployableRemediationAction = new DeployableRemediationAction();\n deployableRemediationAction.setRemediationAction(remediationAction);\n deployableRemediationAction.setHost(remediationAction.getPossibleMachines().get(m));\n newdr.getActions().add(deployableRemediationAction);\n }\n }\n //FIRST MACHINE\n for (DeployableRemediation aResult_tmp : result_tmp) { //For all the previously added Deployable Remediation Actions\n DeployableRemediationAction deployableRemediationAction = new DeployableRemediationAction();\n deployableRemediationAction.setRemediationAction(remediationAction);\n deployableRemediationAction.setHost(remediationAction.getPossibleMachines().get(0));\n aResult_tmp.getActions().add(deployableRemediationAction);\n }\n result_tmp.addAll(resultForThisRemediationAction);\n } else if (remediationAction.getPossibleMachines().size() == 1) {\n for (DeployableRemediation aResult_tmp : result_tmp) {\n DeployableRemediationAction deployableRemediationAction = new DeployableRemediationAction();\n deployableRemediationAction.setRemediationAction(remediationAction);\n deployableRemediationAction.setHost(remediationAction.getPossibleMachines().get(0));\n aResult_tmp.getActions().add(deployableRemediationAction);\n }\n }\n }\n\n //Add all the non empty Deployable Remediation Action to the result\n for (DeployableRemediation aResult_tmp : result_tmp) {\n if (aResult_tmp.getActions().size() > 0)\n result.add(aResult_tmp);\n }\n }\n\n //Compute the cost of all remediation action\n for (DeployableRemediation aResult : result) {\n aResult.computeCost();\n }\n\n Collections.sort(result, new DeployableRemediationComparator());\n\n return result;\n }\n\n /**\n * This function compute the scoring of this attack path (float between 0 and 1 : 1 = will arrive ; 0 = can't arrive\n */\n public void computeScoring() {\n scoring = 1.;\n for (int i : this.vertices.keySet()) {\n Vertex vertex = this.vertices.get(i);\n if (vertex.fact != null && vertex.fact.type == FactType.DATALOG_FACT) {\n DatalogCommand command = vertex.fact.datalogCommand;\n if (command.command.equals(\"vulExists\")) {\n scoring *= 1. / 2;\n }\n if (command.command.equals(\"cvss\") && command.params[1].equals(\"l\")) {\n scoring *= 1. / 5;\n }\n if (command.command.equals(\"cvss\") && command.params[1].equals(\"m\")) {\n scoring *= 1. / 10;\n }\n if (command.command.equals(\"cvss\") && command.params[1].equals(\"h\")) {\n scoring *= 1. / 20;\n } else if (command.command.equals(\"inCompetent\")) {\n scoring *= 1. / 100;\n }\n //Cheat to have the good attack path for demo first :\n if (command.command.equals(\"vulExists\") && command.params[1].equals(\"CVE-2004-1315\")) {\n scoring *= 10;\n }\n if (command.command.equals(\"vulExists\") && command.params[1].equals(\"CVE-2012-3951\")) {\n scoring *= 10;\n }\n if (command.command.equals(\"networkServiceInfo\") && command.params[1].equals(\"sonicwall_scrutinizer\")) {\n scoring *= 10;\n }\n if (command.command.equals(\"hacl\") && command.params[0].equals(\"192.168.240.200\") && command.params[1].equals(\"192.168.240.100\") && command.params[3].equals(\"3306\")) {\n scoring *= 10;\n }\n if (command.command.equals(\"hacl\") && command.params[0].equals(\"internet\") && command.params[1].equals(\"192.168.240.200\") && command.params[3].equals(\"80\")) {\n scoring *= 10;\n }\n if (command.command.equals(\"execCode\") && command.params[0].equals(\"192.168.240.100\")) {\n scoring *= 10;\n }\n if (command.command.equals(\"execCode\") && command.params[0].equals(\"192.168.240.200\")) {\n scoring *= 10;\n }\n if (command.command.equals(\"netAccess\") && command.params[0].equals(\"192.168.240.200\")) {\n scoring *= 10;\n }\n }\n }\n }\n\n /**\n * Print the list of remediations that could be applied to prevent the attack\n *\n * @param topology the network topology\n * @param conn the database connection\n * @throws Exception\n */\n public void printListRemediations(InformationSystem topology, Connection conn) throws Exception {\n List<Vertex> leaves = this.getLeavesThatCanBeRemediated();\n if (this.getGoal() != null) {\n System.out.print(\"The goal of this attack is vertex \" + this.getGoal().id);\n if (this.getGoal().fact != null && this.getGoal().fact.factString != null)\n System.out.print(\" : \" + this.getGoal().fact.factString);\n System.out.println();\n }\n System.out.println(\"The attack path contains \" + leaves.size() + \" leaves : \");\n\n List<List<Vertex>> sufficientLeavesToCutPath = new ArrayList<List<Vertex>>();\n List<Vertex> remainingLeaves = new ArrayList<Vertex>(leaves);\n int simultaneousLeavesNumber = 1;\n\n while (simultaneousLeavesNumber <= remainingLeaves.size()) { //While we take a number of leaves lower than the number of remaining leaves\n List<List<Integer>> combination = combination(simultaneousLeavesNumber, remainingLeaves.size());\n List<Vertex> leavesSufficient = new ArrayList<Vertex>();\n\n for (List<Integer> aCombination : combination) {\n List<Vertex> leavesToTest = new ArrayList<Vertex>();\n for (Integer anACombination : aCombination) {\n leavesToTest.add(remainingLeaves.get(anACombination));\n }\n if (leavesMandatoryForGoal(leavesToTest)) {\n sufficientLeavesToCutPath.add(leavesToTest);\n leavesSufficient.addAll(leavesToTest);\n }\n }\n\n for (Vertex aLeavesSufficient : leavesSufficient) {\n remainingLeaves.remove(aLeavesSufficient);\n }\n\n simultaneousLeavesNumber++;\n }\n\n System.out.println(\"Here are the list of all the combinations of leaves that permit to cut the attack path \");\n for (int i = 0; i < sufficientLeavesToCutPath.size(); i++) {\n System.out.print(\"Combination \" + (i + 1) + \" : \");\n for (int j = 0; j < sufficientLeavesToCutPath.get(i).size(); j++) {\n System.out.print(\"Leaf \" + sufficientLeavesToCutPath.get(i).get(j).id);\n if (j < sufficientLeavesToCutPath.get(i).size() - 1)\n System.out.print(\" + \");\n }\n System.out.println();\n }\n\n System.out.println(\"\\n------------------------------------\");\n System.out.println(\"Here is how to remediate each leaf :\");\n System.out.println(\"------------------------------------\");\n\n for (Vertex leaf : leaves) {\n System.out.print(remediateLeaf(leaf, topology, conn));\n System.out.println(\"----------------------------------\");\n }\n\n }\n\n /**\n * @param leaf An attack path leaf\n * @param topology the network topology\n * @param conn the database connection\n * @return The string that contains the text to remediate a leaf\n * @throws Exception\n */\n public String remediateLeaf(Vertex leaf, InformationSystem topology, Connection conn) throws Exception {\n String result = \"\";\n result += \"* Leaf \" + leaf.id + \"\\n\";\n if (leaf.fact != null && leaf.fact.type == FactType.DATALOG_FACT && leaf.fact.datalogCommand != null) {\n DatalogCommand command = leaf.fact.datalogCommand;\n result += \"Datalog fact : \" + command.command + \"\\n\";\n\n switch (command.command) {\n case \"vulExists\": {\n Vulnerability vuln = new Vulnerability(conn, Vulnerability.getIdVulnerabilityFromCVE(command.params[1], conn));\n List<List<InformationSystemHost>> attackerPath = getAttackerRouteToAVulnerability(leaf, topology);\n result += \"To exploit the vulnerability \" + vuln.cve + \" the packets of the attacker will pass the following machines : \" + \"\\n\";\n for (int j = 0; j < attackerPath.size(); j++) {\n if (attackerPath.size() > 1)\n result += \"Path \" + (j + 1) + \" : \" + \"\\n\";\n result += \"- \";\n for (int k = 0; k < attackerPath.get(j).size(); k++) {\n result += attackerPath.get(j).get(k).getName();\n if (k < attackerPath.get(j).size() - 1)\n result += \" -> \";\n }\n result += \"\\n\";\n List<Patch> patches = vuln.getPatchs(conn);\n List<Rule> rules = vuln.getRules(conn);\n if (patches.size() > 0) {\n result += \"To protect against this vulnerability, the following patch(es) can be applied on machine \\\"\" + leaf.getRelatedMachine(topology).getName() + \"\\\" : \" + \"\\n\";\n for (int m = 0; m < patches.size(); m++) {\n result += patches.get(m).getLink();\n if (m < patches.size() - 1)\n result += \" ; \";\n }\n result += \"\\n\";\n }\n if (rules.size() > 0) {\n result += \"To protect against this vulnerability, the following rule(s) can be used on at least one machine of the attacker path : \" + \"\\n\";\n for (Rule rule : rules) {\n result += \"-\" + rule.getRule() + \"\\n\";\n }\n }\n }\n break;\n }\n case \"inCompetent\":\n result += \"To protect against this attack, the user \\\"\" + command.params[0] + \"\\\" should be trained \" + \"\\n\";\n break;\n case \"attackerLocated\":\n result += \"To protect against this attack, people should know that the attacker is located on \\\"\" + command.params[0] + \"\\\" \\n\";\n break;\n case \"hasAccount\":\n result += \"To protect against this attack, the account \\\"\" + command.params[2] + \"\\\" on the machine \\\"\" + leaf.getRelatedMachine(topology).getName() + \"\\\" should be closed\\n\";\n break;\n case \"hacl\": {\n InformationSystemHost from = topology.getHostByNameOrIPAddress(command.params[0]);\n InformationSystemHost to = topology.getHostByNameOrIPAddress(command.params[1]);\n List<List<InformationSystemHost>> attackerPath = command.getRoutesBetweenHostsOfHacl(topology);\n result += \"The attacker packets will use one of the following paths : \\n\";\n for (int j = 0; j < attackerPath.size(); j++) {\n if (attackerPath.size() > 1)\n result += \"Path \" + (j + 1) + \" : \" + \"\\n\";\n result += \"- \";\n for (int k = 0; k < attackerPath.get(j).size(); k++) {\n result += attackerPath.get(j).get(k).getName();\n if (k < attackerPath.get(j).size() - 1)\n result += \" -> \";\n }\n result += \"\\n\";\n }\n System.out.println(\"The following firewall rule should be deployed on all the paths between \\\"\" + from.getName() + \"\\\" and \\\"\" + to.getName() + \"\\\". (See above)\");\n if (command.params[0].equals(\"internet\")) {\n result += \"DROP\\t\" + Protocol.getProtocolFromString(command.params[2]) + \"\\t--\\t0.0.0.0/0\\t\" + to.getFirstIPAddress().getAddress() + \"/32\\t\" + \"dpt:\" + Service.portStringToInt(command.params[3]) + \"\\n\";\n } else if (command.params[1].equals(\"internet\")) {\n result += \"DROP\\t\" + Protocol.getProtocolFromString(command.params[2]) + \"\\t--\\t\" + from.getFirstIPAddress().getAddress() + \"/32\\t0.0.0.0/0\\t\" + \"dpt:\" + Service.portStringToInt(command.params[3]) + \"\\n\";\n } else {\n result += \"DROP\\t\" + Protocol.getProtocolFromString(command.params[2]) + \"\\t--\\t\" + from.getFirstIPAddress().getAddress() + \"/32\\t\" + to.getFirstIPAddress().getAddress() + \"/32\\t\" + \"dpt:\" + Service.portStringToInt(command.params[3]) + \"\\n\";\n }\n break;\n }\n }\n } else {\n throw new Exception(\"Leaf is not a datalog fact\");\n }\n if (leafMandatoryForGoal(leaf))\n result += \"If this can be corrected, this attack path will be broken\" + \"\\n\";\n else\n result += \"Deleting only this vulnerability is not sufficient to cut the attack path\" + \"\\n\";\n return result;\n }\n\n /**\n * @param leaf An attack path leaf\n * @param topology the network topology\n * @param conn the database connection\n * @return the possible remediation action to remediate this leaf. To remediate the leaf, we can apply remediation[1] OR remadiation[2] OR remediation[3]\n * the remediation[1] is remediation[1][1] AND remediation[1][2] AND remediation[1][3] etc...\n * @throws Exception\n */\n public List<List<RemediationAction>> getRemediationActionForLeaf(Vertex leaf, InformationSystem topology, Connection conn, String costParametersFolder) throws Exception {\n return getRemediationActionForLeaf(leaf, topology, conn, costParametersFolder, true);\n }\n\n /**\n * @param leaf An attack path leaf\n * @param topology the network topology\n * @param conn the database connection\n * @param useSnortRule : if true, use the snort rules else don't use it for remediation\n * @return the possible remediation action to remediate this leaf. To remediate the leaf, we can apply remediation[1] OR remadiation[2] OR remediation[3]\n * the remediation[1] is remediation[1][1] AND remediation[1][2] AND remediation[1][3] etc...\n * @throws Exception\n */\n public List<List<RemediationAction>> getRemediationActionForLeaf(Vertex leaf, InformationSystem topology, Connection conn, String costParametersFolder, boolean useSnortRule) throws Exception {\n List<List<RemediationAction>> result = new ArrayList<List<RemediationAction>>();\n if (leaf.fact != null && leaf.fact.type == FactType.DATALOG_FACT && leaf.fact.datalogCommand != null) {\n DatalogCommand command = leaf.fact.datalogCommand;\n\n switch (command.command) {\n case \"vulExists\": {\n List<RemediationAction> remediateVulnerability = new ArrayList<RemediationAction>();\n Vulnerability vulnerability = new Vulnerability(conn, Vulnerability.getIdVulnerabilityFromCVE(command.params[1], conn));\n List<List<InformationSystemHost>> attackerPath = getAttackerRouteToAVulnerability(leaf, topology);\n\n List<Patch> patches = vulnerability.getPatchs(conn); //Get the path of this vulnerability\n\n List<Rule> rules = vulnerability.getRules(conn); //Get the snort rules related to this vulnerability\n\n if (patches.size() > 0) {\n RemediationAction remediation = new RemediationAction(ActionType.APPLY_PATCH, costParametersFolder);\n remediation.setRelatedVertex(leaf);\n remediation.getPossibleMachines().add(leaf.getRelatedMachine(topology));\n\n for (Patch patche : patches) {\n remediation.getRemediationParameters().add(patche);\n }\n remediateVulnerability.add(remediation);\n result.add(remediateVulnerability);\n }\n if (rules.size() > 0 && useSnortRule) {\n //If there is a rule, to remediate the leaf, we can deploy rule 1 OR rule 2 OR rule 3 but on ALL possible paths\n List<RemediationAction> detectVulnerabilityOnAllPath = new ArrayList<RemediationAction>();\n //For all possible path\n for (List<InformationSystemHost> anAttackerPath : attackerPath) {\n\n RemediationAction remediation = new RemediationAction(ActionType.DEPLOY_SNORT_RULE, costParametersFolder);\n remediation.setRelatedVertex(leaf);\n for (Rule rule : rules) {\n rule.setRule(rule.getRule().replaceFirst(\"alert\", \"reject\"));\n remediation.getRemediationParameters().add(rule);\n }\n\n for (InformationSystemHost anAnAttackerPath : anAttackerPath) {\n //TODO : Add the machine to the \"possible machines\" only if snort is installed (need a way to specify this in the input file)\n //if(attackerPath.get(j).get(incr).getServices().containsKey(\"snort\"))\n remediation.getPossibleMachines().add(anAnAttackerPath); //The path\n }\n\n detectVulnerabilityOnAllPath.add(remediation);\n }\n //Add the detection of vulnerability on all path\n result.add(detectVulnerabilityOnAllPath);\n }\n break;\n }\n case \"inCompetent\":\n List<RemediationAction> trainUser = new ArrayList<RemediationAction>();\n RemediationAction remediation = new RemediationAction(ActionType.TRAIN_USER, costParametersFolder);\n remediation.setRelatedVertex(leaf);\n remediation.getRemediationParameters().add(command.params[0]);\n trainUser.add(remediation);\n result.add(trainUser);\n break;\n case \"hacl\":\n case \"haclprimit\": {\n InformationSystemHost from = topology.getHostByNameOrIPAddress(command.params[0]);\n InformationSystemHost to = topology.getHostByNameOrIPAddress(command.params[1]);\n List<List<InformationSystemHost>> attackerPath = command.getRoutesBetweenHostsOfHacl(topology);\n\n //For HACL Rules, we can block the packets with firewall rules\n //These rules can be deployed either on the input firewall table or on the output firewall table\n //It depends of the machines\n //TODO : things needs to be corrected, to add remediations with \"alternating\" between INPUT and OUTPUT rules\n //FIRST LET'S DO THE INPUT RULES\n\n List<RemediationAction> blockAttackerOnAllPath = new ArrayList<RemediationAction>();\n //For all possible path\n for (List<InformationSystemHost> anAttackerPath1 : attackerPath) {\n\n remediation = new RemediationAction(ActionType.DEPLOY_FIREWALL_RULE, costParametersFolder);\n remediation.setRelatedVertex(leaf);\n if (command.params[0].equals(\"internet\")) {\n FirewallRule fwRule = new FirewallRule(Action.DROP, Protocol.getProtocolFromString(command.params[2]), new IPAddress(\"0.0.0.0\"), new IPAddress(\"0.0.0.0\"), new PortRange(true), to.getFirstIPAddress(), new IPAddress(\"255.255.255.255\"), PortRange.fromString(command.params[3]), Table.INPUT);\n remediation.getRemediationParameters().add(fwRule);\n } else if (command.params[1].equals(\"internet\")) {\n FirewallRule fwRule = new FirewallRule(Action.DROP, Protocol.getProtocolFromString(command.params[2]), from.getFirstIPAddress(), new IPAddress(\"255.255.255.255\"), new PortRange(true), new IPAddress(\"0.0.0.0\"), new IPAddress(\"0.0.0.0\"), PortRange.fromString(command.params[3]), Table.INPUT);\n remediation.getRemediationParameters().add(fwRule);\n } else {\n FirewallRule fwRule = new FirewallRule(Action.DROP, Protocol.getProtocolFromString(command.params[2]), from.getFirstIPAddress(), new IPAddress(\"255.255.255.255\"), new PortRange(true), to.getFirstIPAddress(), new IPAddress(\"255.255.255.255\"), PortRange.fromString(command.params[3]), Table.INPUT);\n remediation.getRemediationParameters().add(fwRule);\n }\n //The only thing that change between INPUT and OUTPUT is the machines on which this rule can be deployed\n for (InformationSystemHost currentAttackerPathHost : anAttackerPath1) {\n if (command.params[0].equals(\"internet\")) {//Source packet is internet, input will block on all hosts\n remediation.getPossibleMachines().add(currentAttackerPathHost);\n } else {\n InformationSystemHost sourceHost = topology.existingMachineByNameOrIPAddress(command.params[0]);\n if (sourceHost == null || !sourceHost.equals(currentAttackerPathHost)) {//we add this machine to the possible machines if it is not the sender of the packets\n remediation.getPossibleMachines().add(currentAttackerPathHost);\n }\n }\n }\n\n blockAttackerOnAllPath.add(remediation);\n }\n //Add the block of the attacker on all path\n result.add(blockAttackerOnAllPath);\n\n\n //THEN LET'S DO THE OUTPUT RULES\n blockAttackerOnAllPath = new ArrayList<RemediationAction>();\n //For all possible path\n for (List<InformationSystemHost> anAttackerPath : attackerPath) {\n\n remediation = new RemediationAction(ActionType.DEPLOY_FIREWALL_RULE, costParametersFolder);\n remediation.setRelatedVertex(leaf);\n if (command.params[0].equals(\"internet\")) {\n FirewallRule fwRule = new FirewallRule(Action.DROP, Protocol.getProtocolFromString(command.params[2]), new IPAddress(\"0.0.0.0\"), new IPAddress(\"0.0.0.0\"), new PortRange(true), to.getFirstIPAddress(), new IPAddress(\"255.255.255.255\"), PortRange.fromString(command.params[3]), Table.OUTPUT);\n remediation.getRemediationParameters().add(fwRule);\n } else if (command.params[1].equals(\"internet\")) {\n FirewallRule fwRule = new FirewallRule(Action.DROP, Protocol.getProtocolFromString(command.params[2]), from.getFirstIPAddress(), new IPAddress(\"255.255.255.255\"), new PortRange(true), new IPAddress(\"0.0.0.0\"), new IPAddress(\"0.0.0.0\"), PortRange.fromString(command.params[3]), Table.OUTPUT);\n remediation.getRemediationParameters().add(fwRule);\n } else {\n FirewallRule fwRule = new FirewallRule(Action.DROP, Protocol.getProtocolFromString(command.params[2]), from.getFirstIPAddress(), new IPAddress(\"255.255.255.255\"), new PortRange(true), to.getFirstIPAddress(), new IPAddress(\"255.255.255.255\"), PortRange.fromString(command.params[3]), Table.OUTPUT);\n remediation.getRemediationParameters().add(fwRule);\n }\n\n //The only thing that change between INPUT and OUTPUT is the machines on which this rule can be deployed\n for (InformationSystemHost currentAttackerPathHost : anAttackerPath) {\n if (command.params[1].equals(\"internet\")) {//Source packet is internet, input will block on all hosts\n remediation.getPossibleMachines().add(currentAttackerPathHost);\n } else {\n InformationSystemHost destinationHost = topology.existingMachineByNameOrIPAddress(command.params[1]);\n if (destinationHost == null || !destinationHost.equals(currentAttackerPathHost)) {//we add this machine to the possible machines if it is not the receiver of the packets\n remediation.getPossibleMachines().add(currentAttackerPathHost);\n }\n }\n }\n\n blockAttackerOnAllPath.add(remediation);\n }\n //Add the block of the attacker on all path\n result.add(blockAttackerOnAllPath);\n break;\n }\n }\n }\n return result;\n\n }\n\n /**\n * Get the attacker route to access a vulnerability according to the information in the attack path\n *\n * @param leaf the leaf of the vulnerability\n * @param topology the network topology\n * @return the attacker route\n * @throws Exception\n */\n public List<List<InformationSystemHost>> getAttackerRouteToAVulnerability(Vertex leaf, InformationSystem topology) throws Exception {\n Vertex child = leaf.children.get(0);\n if (child != null) {\n Vertex netAccessVertex = this.getParentOfVertexWithFactCommand(child, \"netAccess\");\n if (netAccessVertex == null) {\n netAccessVertex = this.getParentOfVertexWithFactCommand(child, \"accessMaliciousInput\");\n }\n if (netAccessVertex != null) {\n Vertex ruleAccessVertex = netAccessVertex.parents.get(0);\n if (ruleAccessVertex != null) {\n Vertex haclVertex = this.getParentOfVertexWithFactCommand(ruleAccessVertex, \"hacl\");\n if (haclVertex != null) {\n return haclVertex.fact.datalogCommand.getRoutesBetweenHostsOfHacl(topology);\n } else\n throw new Exception(\"No hacl.\");\n } else {\n throw new Exception(\"Problem while going up to the hacl for the leaf \" + leaf.id);\n }\n } else {\n throw new Exception(\"Problem while going up to the hacl for the leaf \" + leaf.id);\n }\n } else {\n throw new Exception(\"The leaf a no child\");\n }\n }\n\n /**\n * @param leaf an attack path leaf\n * @return true if the leaf is mandatory to reach the goal of the attack Path\n */\n public boolean leafMandatoryForGoal(Vertex leaf) {\n Vertex goal = this.getGoal();\n if (goal != null) {\n List<Vertex> leaf_list = new ArrayList<Vertex>();\n leaf_list.add(leaf);\n return leavesMandatoryForVertex(leaf_list, goal, new ArrayList<Vertex>());\n }\n return false;\n }\n\n /**\n * @param leaves a list of leaves\n * @return true if the leaves are mandatory to reach the goal\n */\n public boolean leavesMandatoryForGoal(List<Vertex> leaves) {\n Vertex goal = this.getGoal();\n return goal != null && leavesMandatoryForVertex(leaves, goal, new ArrayList<Vertex>());\n }\n\n /**\n * Recursive function that test whether or not leaves are mandatory to access a vertex\n *\n * @param leaves the leaves that will be tested\n * @param v the vertex\n * @return true if the leaves are mandatory / else false\n */\n private boolean leavesMandatoryForVertex(List<Vertex> leaves, Vertex v, List<Vertex> alreadySeen) {\n if (leaves.contains(v))\n return true;\n else if (v.type == VertexType.AND) {\n boolean result = false;\n v.computeParentsAndChildren(this);\n alreadySeen.add(v);\n for (int i = 0; i < v.parents.size(); i++) {\n Vertex parent = v.parents.get(i);\n if (!alreadySeen.contains(parent))\n result = result || leavesMandatoryForVertex(leaves, parent, alreadySeen);\n }\n alreadySeen.remove(v);\n return result;\n } else if (v.type == VertexType.OR) {\n boolean result = true;\n v.computeParentsAndChildren(this);\n alreadySeen.add(v);\n for (int i = 0; i < v.parents.size(); i++) {\n Vertex parent = v.parents.get(i);\n if (!alreadySeen.contains(parent))\n result = result && leavesMandatoryForVertex(leaves, parent, alreadySeen);\n }\n alreadySeen.remove(v);\n return result;\n } else {\n return false;\n }\n }\n\n /**\n * Load the attack path from a DOM element of a XML file (the XML file contains only the arcs, the vertices are in the attack graph)\n *\n * @param root the DOM element\n * @param attackGraph the corresponding attack graph\n */\n public void loadFromDomElementAndAttackGraph(Element root, AttackGraph attackGraph) {\n Element scoringElement = root.getChild(\"scoring\");\n if (scoringElement != null) {\n this.scoring = Double.parseDouble(scoringElement.getText());\n }\n\n\t\t/* Add all the arcs */\n Element arcs_element = root.getChild(\"arcs\");\n if (arcs_element != null) {\n List<Element> arcs = arcs_element.getChildren(\"arc\");\n for (Element arc_element : arcs) { //All arcs\n Element src_element = arc_element.getChild(\"dst\"); //MULVAL XML FILES INVERSE DESTINATION AND DESTINATION\n Element dst_element = arc_element.getChild(\"src\"); //MULVAL XML FILES INVERSE DESTINATION AND DESTINATION\n if (src_element != null && dst_element != null) {\n Vertex destination = getVertexFromAttackGraph((int) Double.parseDouble(dst_element.getText()), attackGraph);\n Vertex source = getVertexFromAttackGraph((int) Double.parseDouble(src_element.getText()), attackGraph);\n Arc arc = new Arc(source, destination);\n this.arcs.add(arc);\n }\n }\n }\n }\n\n /**\n * @param vertexID the vertex number\n * @param attackGraph an attack graph\n * @return the existing vertex if it is already in the attack path else add this vertex from the attack graph\n */\n public Vertex getVertexFromAttackGraph(int vertexID, AttackGraph attackGraph) {\n if (this.vertices.containsKey(vertexID))\n return this.vertices.get(vertexID);\n else {\n Vertex result = attackGraph.getExistingOrCreateVertex(vertexID);\n this.vertices.put(vertexID, result);\n return result;\n }\n }\n\n /**\n * @return the dom element corresponding to this attack path XML file\n */\n public Element toDomXMLElement() {\n Element root = new Element(\"attack_path\");\n\n Element scoringElement = new Element(\"scoring\");\n scoringElement.setText(this.scoring + \"\");\n root.addContent(scoringElement);\n //arcs\n Element arcsElement = new Element(\"arcs\");\n root.addContent(arcsElement);\n for (Arc arc : arcs) {\n Element arcElement = new Element(\"arc\");\n arcsElement.addContent(arcElement);\n Element srcElement = new Element(\"src\");\n srcElement.setText(arc.destination.id + \"\");\n arcElement.addContent(srcElement);\n Element dstElement = new Element(\"dst\");\n dstElement.setText(arc.source.id + \"\");\n arcElement.addContent(dstElement);\n }\n\n return root;\n }\n\n @Override\n public String toString() {\n String result = \"AttackPath : \";\n for (int i : this.vertices.keySet()) {\n result += this.vertices.get(i).id + \" - \";\n }\n return result;\n }\n\n /**\n * @param informationSystem the information system\n * @return The topology Graph associated to this attack path\n * @throws Exception\n */\n public InformationSystemGraph getRelatedTopologyGraph(InformationSystem informationSystem) throws Exception {\n InformationSystemGraph result = super.getRelatedTopologyGraph(informationSystem);\n\n result.addTarget(this.getGoal().getRelatedMachine(informationSystem));\n\n return result;\n }\n\n @Override\n public AttackPath clone() throws CloneNotSupportedException {\n AttackPath copie = (AttackPath) super.clone();\n\n if (this.goal != null)\n copie.goal = copie.vertices.get(this.goal.id);\n\n return copie;\n }\n\n public static class AttackPathComparator implements Comparator<AttackPath> {\n public int compare(AttackPath a1, AttackPath a2) {\n //descending order\n if (a1.scoring == a2.scoring) {\n return 0;\n } else if (a1.scoring < a2.scoring) {\n return 1;\n } else {\n return -1;\n }\n }\n }\n\n /**\n * Comparator to compare deployable remediation according to their cost\n */\n private class DeployableRemediationComparator implements Comparator<DeployableRemediation> {\n public int compare(DeployableRemediation dr1, DeployableRemediation dr2) {\n if (dr1.getCost() == dr2.getCost()) {\n return 0;\n } else if (dr1.getCost() < dr2.getCost()) {\n return -1;\n } else {\n return 1;\n }\n }\n }\n\n}", "public class SerializableAttackPath implements Serializable {\n\n /**\n * A list of vertices\n */\n public Map<Integer, SerializableVertex> vertices = new HashMap<Integer, SerializableVertex>();\n\n /**\n * A list of arcs between the vertices\n */\n public ArrayList<SerializableArc> arcs = new ArrayList<SerializableArc>();\n\n /**\n * Create a serializable attack path from an attack path\n *\n * @param attackPath the attack path to serialize\n * @param informationSystem the information system\n * @throws Exception\n */\n public SerializableAttackPath(AttackPath attackPath, InformationSystem informationSystem) throws Exception {\n InformationSystemGraph informationSystemGraph = attackPath.getRelatedTopologyGraph(informationSystem);\n\n Map<InformationSystemGraphVertex, Integer> vertexToNumber = new HashMap<InformationSystemGraphVertex, Integer>();\n int id = 0;\n for (InformationSystemGraphVertex vertex : informationSystemGraph.getVertices()) {\n SerializableVertex serializableVertex = new SerializableVertex(vertex);\n vertices.put(id, serializableVertex);\n vertexToNumber.put(vertex, id);\n id++;\n }\n\n for (InformationSystemGraphArc arc : informationSystemGraph.getArcs()) {\n int sourceID = vertexToNumber.get(arc.getSource());\n int destination = vertexToNumber.get(arc.getDestination());\n arcs.add(new SerializableArc(sourceID, destination, \"vulnerability:\" + arc.getRelatedVulnerability()));\n }\n\n }\n\n /**\n * Test if an attack path is similar to another attack path\n *\n * @param attackPath the attack path to test\n * @return true if the attack paths are similar.\n */\n public boolean isSimilarTo(SerializableAttackPath attackPath) {\n boolean result = true;\n for (SerializableVertex serializableVertex : attackPath.vertices.values()) {\n boolean resultVertex = false;\n for (SerializableVertex vertexToTest : this.vertices.values()) {\n resultVertex |= vertexToTest.equals(serializableVertex);\n }\n result &= resultVertex;\n }\n return result;\n }\n}", "public class InformationSystem implements Cloneable {\n\n\n /**\n * The network topology of the information system\n */\n private Topology topology = new Topology();\n\n /**\n * Is the attacker located on the internet in addition to {@link #machinesOfAttacker} ?\n */\n private boolean attackerLocatedOnInternet = false;\n\n /**\n * The flow matrix of the Information System\n */\n private FlowMatrix flowMatrix;\n\n /**\n * The list of machines that are mastered by the attacker\n */\n private List<InformationSystemHost> machinesOfAttacker = new ArrayList<InformationSystemHost>();\n\n\n /**\n * Create an empty information system\n */\n public InformationSystem() {\n\n }\n\n @Override\n public InformationSystem clone() throws CloneNotSupportedException {\n InformationSystem copie = (InformationSystem) super.clone();\n copie.topology = copie.topology.clone();\n return copie;\n }\n\n /**\n * Create a file with Datalog rules for the input of Mulval\n *\n * @param mulvalFilePath the filePath to store MulVAL input Datalog file\n * @throws Exception\n */\n public void exportToMulvalDatalogFile(String mulvalFilePath) throws Exception {\n PrintWriter fichier = new PrintWriter(new BufferedWriter(new FileWriter(mulvalFilePath)));\n\n //Add internet\n fichier.println(\"/**********************************/\");\n fichier.println(\"/* Add Internet */\");\n fichier.println(\"/**********************************/\");\n\n fichier.println(\"attackerLocated(internet_host).\");\n fichier.println(\"hasIP(internet_host,'1.1.1.1').\");\n fichier.println(\"defaultLocalFilteringBehavior('internet_host',allow).\");\n fichier.println(\"isInVlan('1.1.1.1','internet').\");\n fichier.println();\n\n for (Host host : topology.getHosts()) {\n fichier.println(\"/**********************************/\");\n fichier.println(\"/* Add Host \" + host.getName() + \" */\");\n fichier.println(\"/**********************************/\");\n InformationSystemHost informationSystemHost = (InformationSystemHost) host;\n fichier.println(\"attackerLocated('\" + host.getName() + \"').\");\n fichier.println(\"attackGoal(execCode('\" + host.getName() + \"', _)).\");\n for (Interface networkInterface : host.getInterfaces().values()) {\n fichier.println(\"hasIP('\" + host.getName() + \"','\" + networkInterface.getAddress().toString() + \"').\");\n if (networkInterface.getVlan() != null && !networkInterface.getVlan().getName().isEmpty()) {\n fichier.println(\"isInVlan('\" + networkInterface.getAddress().toString() + \"','\" + networkInterface.getVlan().getName() + \"').\");\n }\n }\n fichier.println(\"hostAllowAccessToAllIP('\" + host.getName() + \"').\");\n for (Service service : informationSystemHost.getServices().values()) {\n fichier.println(\"installed('\" + host.getName() + \"','\" + service.getName() + \"').\");\n if (service.getPortNumber() != 0) {\n fichier.println(\"networkServiceInfo('\" + service.getIpAddress() + \"', '\" + service.getName() + \"', '\" + service.getProtocol().toString() + \"', \" + service.getPortNumber() + \", 'user').\");\n }\n\n for (String cve : service.getVulnerabilities().keySet()) {\n Vulnerability vulnerability = service.getVulnerabilities().get(cve);\n fichier.println(\"vulProperty('\" + vulnerability.cve + \"', \" + vulnerability.exploitType + \", \" + vulnerability.exploitGoal + \").\");\n fichier.println(\"vulExists('\" + host.getName() + \"', '\" + vulnerability.cve + \"', '\" + service.getName() + \"', \" + vulnerability.exploitType + \", \" + vulnerability.exploitGoal + \").\");\n if (vulnerability.cvss != null && vulnerability.cvss.getScore() >= 6.6) {\n fichier.println(\"cvss('\" + vulnerability.cve + \"',h).\");\n } else if (vulnerability.cvss != null && vulnerability.cvss.getScore() >= 3.3) {\n fichier.println(\"cvss('\" + vulnerability.cve + \"',m).\");\n } else if (vulnerability.cvss != null && vulnerability.cvss.getScore() > 0) {\n fichier.println(\"cvss('\" + vulnerability.cve + \"',l).\");\n } else {\n fichier.println(\"cvss('\" + vulnerability.cve + \"',m).\");\n }\n }\n }\n fichier.println();\n\n }\n\n //Add flow matrix elements\n if (this.flowMatrix != null && this.flowMatrix.getFlowMatrixLines().size() > 0) {\n for (FlowMatrixLine flowMatrixLine : this.flowMatrix.getFlowMatrixLines()) {\n String mulvalDestinationPort;\n if (flowMatrixLine.getDestination_port().isAny()) {\n mulvalDestinationPort = \"_\";\n } else if (flowMatrixLine.getDestination_port().getMax() == flowMatrixLine.getDestination_port().getMin()) {\n mulvalDestinationPort = \"\" + flowMatrixLine.getDestination_port().getMax();\n } else {\n throw new IllegalStateException(\"Minimum and Maximum port range are not yet managed.\");\n }\n\n String mulvalProtocol;\n if (flowMatrixLine.getProtocol().equals(FirewallRule.Protocol.ANY)) {\n mulvalProtocol = \"_\";\n } else {\n mulvalProtocol = \"'\" + flowMatrixLine.getProtocol().toString() + \"'\";\n }\n\n if (!mulvalDestinationPort.isEmpty() && !mulvalProtocol.isEmpty()) {\n FlowMatrixElement sourceElement = flowMatrixLine.getSource();\n FlowMatrixElement destinationElement = flowMatrixLine.getDestination();\n\n if (sourceElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.IP) &&\n destinationElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.IP)) {\n if (sourceElement.getResource() instanceof Interface && destinationElement.getResource() instanceof Interface) {\n Interface sourceInterface = (Interface) sourceElement.getResource();\n Interface destinationInterface = (Interface) destinationElement.getResource();\n fichier.println(\"haclprimit('\" + sourceInterface.getAddress() + \"','\" + destinationInterface.getAddress() + \"', \" + mulvalDestinationPort + \",\" + mulvalProtocol + \").\");\n } else {\n throw new IllegalStateException(\"Illegal resource type\");\n }\n } else if (sourceElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.INTERNET) &&\n destinationElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.IP)) {\n if (destinationElement.getResource() instanceof Interface) {\n Interface destinationInterface = (Interface) destinationElement.getResource();\n fichier.println(\"vlanToIP('internet','\" + destinationInterface.getAddress() + \"', \" + mulvalDestinationPort + \",\" + mulvalProtocol + \").\");\n } else {\n throw new IllegalStateException(\"Illegal resource type\");\n }\n } else if (sourceElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.VLAN) &&\n destinationElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.IP)) {\n if (sourceElement.getResource() instanceof VLAN && destinationElement.getResource() instanceof Interface) {\n VLAN sourceVlan = (VLAN) sourceElement.getResource();\n Interface destinationInterface = (Interface) destinationElement.getResource();\n fichier.println(\"vlanToIP('\" + sourceVlan.getName() + \"','\" + destinationInterface.getAddress() + \"', \" + mulvalDestinationPort + \",\" + mulvalProtocol + \").\");\n } else {\n throw new IllegalStateException(\"Illegal resource type\");\n }\n } else if (sourceElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.IP) &&\n destinationElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.VLAN)) {\n if (sourceElement.getResource() instanceof Interface && destinationElement.getResource() instanceof VLAN) {\n Interface sourceInterface = (Interface) sourceElement.getResource();\n VLAN destinationVlan = (VLAN) destinationElement.getResource();\n fichier.println(\"ipToVlan('\" + sourceInterface.getAddress() + \"','\" + destinationVlan.getName() + \"', \" + mulvalDestinationPort + \",\" + mulvalProtocol + \").\");\n } else {\n throw new IllegalStateException(\"Illegal resource type\");\n }\n } else if (sourceElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.INTERNET) &&\n destinationElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.VLAN)) {\n if (destinationElement.getResource() instanceof VLAN) {\n VLAN destinationVLAN = (VLAN) destinationElement.getResource();\n fichier.println(\"vlanToVlan('internet','\" + destinationVLAN.getName() + \"', \" + mulvalDestinationPort + \",\" + mulvalProtocol + \").\");\n } else {\n throw new IllegalStateException(\"Illegal resource type\");\n }\n } else if (sourceElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.VLAN) &&\n destinationElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.VLAN)) {\n if (sourceElement.getResource() instanceof VLAN && destinationElement.getResource() instanceof VLAN) {\n VLAN sourceVLAN = (VLAN) sourceElement.getResource();\n VLAN destinationVLAN = (VLAN) destinationElement.getResource();\n fichier.println(\"vlanToVlan('\" + sourceVLAN.getName() + \"','\" + destinationVLAN.getName() + \"', \" + mulvalDestinationPort + \",\" + mulvalProtocol + \").\");\n } else {\n throw new IllegalStateException(\"Illegal resource type\");\n }\n } else if (sourceElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.IP) &&\n destinationElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.INTERNET)) {\n if (sourceElement.getResource() instanceof Interface) {\n Interface sourceInterface = (Interface) sourceElement.getResource();\n fichier.println(\"ipToVlan('\" + sourceInterface.getAddress() + \"','internet', \" + mulvalDestinationPort + \",\" + mulvalProtocol + \").\");\n } else {\n throw new IllegalStateException(\"Illegal resource type\");\n }\n } else if (sourceElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.VLAN) &&\n destinationElement.getType().equals(FlowMatrixElement.FlowMatrixElementType.INTERNET)) {\n if (sourceElement.getResource() instanceof VLAN) {\n VLAN sourceVLAN = (VLAN) sourceElement.getResource();\n fichier.println(\"vlanToVlan('\" + sourceVLAN.getName() + \"','internet', \" + mulvalDestinationPort + \",\" + mulvalProtocol + \").\");\n } else {\n throw new IllegalStateException(\"Illegal resource type\");\n }\n } else {\n throw new IllegalStateException(\"Unknown values of flow matrix\");\n }\n\n\n } else {\n throw new IllegalStateException(\"Empty port or protocol\");\n }\n }\n } else { //Empty flow matrix, add access betwen each couples of VLANs\n for (VLAN vlanFrom : this.topology.getVlans().values()) {\n for (VLAN vlanTo : this.topology.getVlans().values()) {\n if (!vlanFrom.equals(vlanTo)) {\n fichier.println(\"vlanToVlan('\" + vlanFrom.getName() + \"','\" + vlanTo.getName() + \"',_,_).\");\n }\n\n }\n }\n }\n\n fichier.println(\"/**********************************/\");\n fichier.println(\"/****** General Rules ******/\");\n fichier.println(\"/**********************************/\");\n fichier.println(\"defaultLocalFilteringBehavior(_,allow).\"); //Attacker is on the internet\n\n fichier.close();\n }\n\n /**\n * Get a machine by its name or IP address. If the machine doesn't exist, add it to the topology\n *\n * @param str the name or IP address of the machine\n * @return the created or existing machine.\n * @throws Exception\n */\n public InformationSystemHost getHostByNameOrIPAddress(String str) throws Exception {\n if (IPAddress.isAnIPAddress(str)) {\n return getMachineByIPAddress(new IPAddress(str));\n } else {\n InformationSystemHost existingMachine = existingMachineByName(str);\n if (existingMachine != null)\n return existingMachine;\n InformationSystemHost newMachine = new InformationSystemHost(str, this.topology);\n this.topology.getHosts().add(newMachine);\n return newMachine;\n }\n }\n\n /**\n * get the routes from the internet to a host\n *\n * @param to the destination host\n * @return The list of routes\n * @throws Exception\n */\n public List<List<InformationSystemHost>> routesFromInternetTo(Host to) throws Exception {\n List<List<InformationSystemHost>> result = new ArrayList<List<InformationSystemHost>>();\n List<List<Host>> routes = to.getRoutesFromInternet();\n\n for (List<Host> route : routes) {\n List<InformationSystemHost> tmpResult = new ArrayList<InformationSystemHost>();\n for (Host aRoute : route) {\n tmpResult.add((InformationSystemHost) aRoute);\n }\n result.add(tmpResult);\n }\n\n return result;\n }\n\n /**\n * Get an existing machine of the information system with its name\n *\n * @param name the name of the machine\n * @return the machine if it exists else null\n */\n public InformationSystemHost existingMachineByName(String name) {\n for (int i = 0; i < this.topology.getHosts().size(); i++) {\n if (this.topology.getHosts().get(i).getName().equals(name))\n return (InformationSystemHost) this.topology.getHosts().get(i);\n }\n if (name.equals(\"internet\"))\n return new InformationSystemHost(\"internet\", topology);\n\n return null;\n }\n\n /**\n * Get an existing machine of the information system with its name or ip address\n *\n * @param str the name or ip address of the machine\n * @return the machine if it exists else null\n * @throws Exception\n */\n public InformationSystemHost existingMachineByNameOrIPAddress(String str) throws Exception {\n if (IPAddress.isAnIPAddress(str))\n return (InformationSystemHost) topology.existingHostByIPAddress(new IPAddress(str));\n else\n return existingMachineByName(str);\n }\n\n\n /**\n * Get an existing machine of the information system with a specific user\n *\n * @param username the name of the user\n * @return an existing machine that have the user that can use it.\n */\n public InformationSystemHost existingMachineByUserName(String username) {\n for (int i = 0; i < this.topology.getHosts().size(); i++) {\n InformationSystemHost machine = (InformationSystemHost) this.topology.getHosts().get(i);\n for (String j : machine.getUsers().keySet()) {\n if (machine.getUsers().get(j).getName().equals(username))\n return machine;\n }\n }\n return null;\n }\n\n /**\n * Get a machine by its IP address, or create a new one if it does not exist\n *\n * @param ipAddress an IP Address\n * @return The machine in the topology that has this IP Address. If this machine doesn't exists, just add a new one.\n * @throws Exception\n */\n public InformationSystemHost getMachineByIPAddress(IPAddress ipAddress) throws Exception {\n InformationSystemHost existingMachine = (InformationSystemHost) topology.existingHostByIPAddress(ipAddress);\n if (existingMachine != null)\n return existingMachine;\n InformationSystemHost newMachine = new InformationSystemHost(ipAddress.getAddress(), topology);\n newMachine.addInterface(\"int1\", ipAddress.getAddress());\n this.topology.getHosts().add(newMachine);\n return newMachine;\n }\n\n /**\n * Get the route from a host to the internet\n *\n * @param from the start of the route.\n * @return the route from a host to the internet\n * @throws Exception\n */\n public List<InformationSystemHost> routeToInternetFrom(Host from) throws Exception {\n List<InformationSystemHost> result = new ArrayList<InformationSystemHost>();\n List<Host> hosts = from.getRouteToInternet();\n for (Host host : hosts) {\n result.add((InformationSystemHost) host);\n }\n return result;\n }\n\n /**\n * Get the route between two hosts\n *\n * @param from the start of the route\n * @param to the destination host\n * @return the route between two hosts\n * @throws Exception\n */\n public List<InformationSystemHost> routeBetweenHosts(InformationSystemHost from, InformationSystemHost to) throws Exception {\n List<InformationSystemHost> result = new ArrayList<InformationSystemHost>();\n List<Host> route = topology.routeBetweenHosts(from, to);\n for (Host aRoute : route) {\n result.add((InformationSystemHost) aRoute);\n }\n return result;\n }\n\n\n /**\n * Save the attack graph in an xml file\n *\n * @param filePath the file path where the attack graph will be save\n * @throws Exception\n */\n public void saveToXmlFile(String filePath) throws Exception {\n XMLOutputter output = new XMLOutputter(Format.getPrettyFormat());\n output.output(toDomXMLElement(), new FileOutputStream(filePath));\n }\n\n /**\n * Get the XML DOM element of this information system\n *\n * @return the dom element corresponding to this topology with the format of the tva report file\n */\n public Element toDomXMLElement() {\n Element root = new Element(\"topology\");\n\n //machines\n for (int i = 0; i < this.topology.getHosts().size(); i++) {\n InformationSystemHost machine = (InformationSystemHost) this.topology.getHosts().get(i);\n root.addContent(machine.toDomXMLElement());\n }\n\n return root;\n }\n\n /**\n * Load a network topology from a dom element\n *\n * @param domElement the dom element of an xml file\n * @throws Exception\n */\n public void loadFromDomElement(Element domElement, Database db) throws Exception {\n if (domElement == null)\n return;\n List<Element> hostsElement = domElement.getChildren(\"machine\");\n for (Element hostElement : hostsElement) {\n InformationSystemHost host = new InformationSystemHost(this.topology);\n host.loadFromDomElement(hostElement, this.topology, db);\n this.topology.getHosts().add(host);\n }\n this.flowMatrix = new FlowMatrix(domElement.getChild(\"flow-matrix\"), this.topology);\n }\n\n\n /**\n * Load the topology from an xml file\n *\n * @param XMLFilePath the path to the xml file\n * @throws Exception\n */\n public void loadFromXMLFile(String XMLFilePath, Database db) throws Exception {\n FileInputStream file = new FileInputStream(XMLFilePath);\n SAXBuilder sxb = new SAXBuilder();\n Document document = sxb.build(file);\n Element root = document.getRootElement();\n\n this.loadFromDomElement(root, db);\n }\n\n /**\n * Generates the Json object relative to the hosts list\n * @return the Json Object containing the hosts list\n */\n public JSONObject getHostsListJson() {\n //Build the json list of hosts\n JSONObject json = new JSONObject();\n JSONArray hosts_array = new JSONArray();\n for (Host host : this.getTopology().getHosts()) {\n InformationSystemHost informationSystemHost = (InformationSystemHost) host;\n JSONObject host_object = new JSONObject();\n host_object.put(\"name\", informationSystemHost.getName());\n JSONArray security_requirements_array = new JSONArray();\n for (SecurityRequirement securityRequirement : informationSystemHost.getSecurityRequirements()) {\n JSONObject security_requirement = new JSONObject();\n security_requirement.put(\"name\", securityRequirement.getName());\n security_requirement.put(\"metric\", securityRequirement.getMetricPlainText());\n security_requirements_array.put(security_requirement);\n }\n host_object.put(\"security_requirements\", security_requirements_array);\n hosts_array.put(host_object);\n }\n json.put(\"hosts\", hosts_array);\n return json;\n }\n\n /**\n * Get the network topology\n *\n * @return the topology\n */\n public Topology getTopology() {\n return topology;\n }\n\n /**\n * Is the attacker located on the internet in addition to {@link #machinesOfAttacker} ?\n */\n public boolean isAttackerLocatedOnInternet() {\n return attackerLocatedOnInternet;\n }\n\n /**\n * Set the attacker on the internet status\n *\n * @param attackerLocatedOnInternet the new value of attackerLocatedOnInternet\n */\n public void setAttackerLocatedOnInternet(boolean attackerLocatedOnInternet) {\n this.attackerLocatedOnInternet = attackerLocatedOnInternet;\n }\n\n /**\n * Get the list of machines where the attacker is located (in addition to the internet)\n */\n public List<InformationSystemHost> getMachinesOfAttacker() {\n return machinesOfAttacker;\n }\n\n /**\n * Set the list of machines of the internet\n *\n * @param machinesOfAttacker new machines of the attacker\n */\n public void setMachinesOfAttacker(List<InformationSystemHost> machinesOfAttacker) {\n this.machinesOfAttacker = machinesOfAttacker;\n }\n}", "public class ProjectProperties {\n public static final String PROPERTY_FILE_NAME = System.getProperty(\"user.home\") + \"/.remediation/config.properties\";\n\n /**\n * Load the property file from the file define in the constant {@link #PROPERTY_FILE_NAME}\n *\n * @return the {@link java.util.Properties} object\n */\n private static Properties loadPropertyFile() {\n File file = new File(PROPERTY_FILE_NAME);\n if (!file.exists()) {\n new File(file.getParent()).mkdirs();//If folder doesn't exist, create it\n System.err.println(\"Property file does not exists, I will create a new one in \" + PROPERTY_FILE_NAME);\n Properties prop = new Properties();\n try {\n prop.store(new FileOutputStream(PROPERTY_FILE_NAME), null);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return prop;\n } else {\n Properties prop = new Properties();\n try {\n\n prop.load(new FileInputStream(file));\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return prop;\n }\n }\n\n /**\n * Get a property from the property file\n *\n * @param propertyName the property name\n * @return the corresponding property\n */\n public static String getProperty(String propertyName) {\n Properties prop = loadPropertyFile();\n return prop.getProperty(propertyName);\n\n }\n\n /**\n * Change a property value\n *\n * @param propertyName name of the property\n * @param value new value\n */\n public static void setProperty(String propertyName, String value) {\n Properties prop = loadPropertyFile();\n prop.setProperty(propertyName, value);\n try {\n prop.store(new FileOutputStream(PROPERTY_FILE_NAME), null);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}", "public class SerializableDeployableRemediation implements Serializable {\n /**\n * The actions of the deployable remediation\n */\n private List<SerializableDeployableRemediationAction> actions = new ArrayList<SerializableDeployableRemediationAction>();\n\n public SerializableDeployableRemediation(DeployableRemediation deployableRemediation) {\n for (DeployableRemediationAction action : deployableRemediation.getActions()) {\n this.actions.add(new SerializableDeployableRemediationAction(action));\n }\n }\n\n /**\n * Get the actions\n *\n * @return the actions\n */\n public List<SerializableDeployableRemediationAction> getActions() {\n return actions;\n }\n\n /**\n * Test if a deployable remediation is similar to a serializable one\n * @param deployableRemediation the remediation to test\n * @return true if they are similar\n */\n public boolean isSimilarTo(DeployableRemediation deployableRemediation) {\n boolean result = true;\n for(DeployableRemediationAction deployableRemediationAction : deployableRemediation.getActions()) {\n boolean resultForAction = false;\n for(SerializableDeployableRemediationAction serializableDeployableRemediation : this.getActions()) {\n resultForAction |= serializableDeployableRemediation.equals(deployableRemediationAction);\n }\n result &= resultForAction;\n }\n\n return result;\n }\n}" ]
import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.fiware.cybercaptor.server.attackgraph.AttackPath; import org.fiware.cybercaptor.server.attackgraph.serializable.SerializableAttackPath; import org.fiware.cybercaptor.server.informationsystem.InformationSystem; import org.fiware.cybercaptor.server.properties.ProjectProperties; import org.fiware.cybercaptor.server.remediation.serializable.SerializableDeployableRemediation; import org.jdom2.Element; import java.io.*; import java.util.AbstractMap; import java.util.ArrayList;
/**************************************************************************************** * This file is part of FIWARE CyberCAPTOR, * * instance of FIWARE Cyber Security Generic Enabler * * Copyright (C) 2012-2015 Thales Services S.A.S., * * 20-22 rue Grande Dame Rose 78140 VELIZY-VILACOUBLAY FRANCE * * * * FIWARE CyberCAPTOR 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. * * * * FIWARE CyberCAPTOR 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 FIWARE CyberCAPTOR. * * If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package org.fiware.cybercaptor.server.remediation; /** * Class representing a deployable remediation = a list of {@link DeployableRemediationAction} * (remediations that can be deployed on a host) with a cost. * * @author Francois -Xavier Aguessy */ public class DeployableRemediation { /** * The actions of the deployable remediation */ private List<DeployableRemediationAction> actions = new ArrayList<DeployableRemediationAction>(); /** * The cost of the deployable remediation */ private double cost = 0; /** * The corrected attack path */
private AttackPath correctedPath;
0
DiatomStudio/SketchChair
src/ShapePacking/spShapePack.java
[ "public class GLOBAL {\n\n\tpublic static boolean useMaskedUpdating = false;\n\n\tstatic SketchProperties sketchProperties = new SketchProperties();\n\t\n\tpublic static double CAM_OFFSET_X = 300;\n\tpublic static double CAM_OFFSET_Y = -900;\n\tpublic static int windowWidth;\n\tpublic static int windowHeight;\n\tpublic static PFont font;\n\tpublic PImage clickToStart;\n\tpublic String version = \"0.9.0.1\";\n\tpublic static boolean forceReset = false;\n\tpublic static boolean cropExportToScreen = false;\n\tpublic static SketchGlobals SketchGlobals;\n\tpublic static boolean dxfCapture = false;\n\tpublic static String dxfLocation = \"./designOutput.dxf\";\n\t//public static MovieMaker mm;\n\tpublic static boolean captureScreen = false;\n\tstatic int designDisplayList;\n\n\n\t//contains the title img\n\tstatic PImage tittleImg;\n\n\tstatic Object myMovie = null;\n\tstatic int tittleImageNum = 0;\n\n\tstatic public SketchChairs sketchChairs;\n\n\t//static public VerletPhysics physics;\n\tstatic public jBullet jBullet;\n\tstatic public UITools uiTools;\n\t//static public RagDoll ragDoll = null;\n\tpublic static ModalGUI gui;\n\tstatic public Environments environments;\n\n\t/*\n\t * What mode are we in? 0 - sketch seat 1 - view in 3d\n\t */\n\tstatic public int mode = 0;\n\tstatic public float rotateModelsX;\n\n\tstatic public float rotateModelsY;\n\tstatic public PGraphics g;\n\n\tpublic static PApplet applet;\n\tpublic static boolean savePDF = false;\n\tpublic static int sketch_id;\n\tstatic double ZOOM = 1.5f;\n\tpublic static Ray3D debugRay = null;\n\n\tpublic static Vec3D debugRayIntersection = null;\n\tpublic static ergoDoll person = null;\n\n\tpublic static spShapePack shapePack;\n\tstatic public Undo undo = new Undo();\n\n\tstatic public Long tick = 0l;\n\tstatic public WidgetPlanes planesWidget;\n\n\tstatic public WidgetSlices slicesWidget;\n\tstatic public WidgetLoad loadWidget;\n\tstatic public WidgetMaterials widgetMaterials;\n\tstatic public WidgetToolSettings widgetToolSettings;\n\tpublic static boolean performanceMode = true;\n\n\tstatic JFileChooser fc;\n\n\tpublic static String pdfSaveLocation = null;\n\tpublic static MeasureTool measuretTool;\n\tpublic static String LAST_SAVED_LOCATION = null;\n\tpublic static int timeoutCounter = 1200000 * 1000; //seconds of inactivity untill timeout. \n\n\tpublic static int inativeCounter = 0; //seconds of inactivity untill timeout. \n\tpublic static boolean personTranslate = true;\n\tpublic static boolean autoRotate = false;\n\tpublic static boolean modeChanged = false;\n\tpublic static float rememberLasty;\n\tpublic static boolean resetting = false;\n\tstatic CloudHook cloudHook = new CloudHook(\n\t\t\t\"http://sketchchair.cc/framework/CloudHook.php\");\n\tpublic static boolean autoOpenPDF = true;\n\tpublic static String lastLoadLocation = null;\n\tpublic static boolean screenshot = false;\n\tpublic static int renderChairColour = 255;\n\tpublic static WidgetLoad widgetLoad;\n\tpublic static String dxfSaveLocation;\n\tpublic static boolean saveDXF;\n\tpublic static SketchChair copyOfChair;\n\tpublic static GUIComponentSet toggleSetSlices;\n\tpublic static String pngPreviewSaveLocation;\n\tpublic static boolean exportPreviewPNG = false;\n\tstatic SkchAutamata skchAutomatic = new SkchAutamata();\n\tpublic static boolean floorOn = true;\n\tpublic static boolean saveChairToFile =false;\n\tpublic static boolean saveChairToFileAuto = false;\n\tpublic static boolean displayIntroPanel = true;\n\tpublic static boolean forceResize = false;\n\tpublic static boolean deleteAllChairsFlag =false;\n\n\t\n\tpublic static String username = null;\n\tpublic static String password = null;\n\tpublic static boolean authenticated = false;\n\tpublic static String sessionID = null;\n\n\tpublic static float prevRotateModelsX = 0;\n\tpublic static float prevRotateModelsY = -(float)Math.PI/4;\n\n\tpublic static GUIPanelTabbed designToolbarAdvanced = null;\n\tpublic static GUIPanelTabbed designToolbarBasic = null;\n\n\tpublic static GUIPanel slicePanel;\n\n\tpublic static WidgetPreviewPanel previewWidget;\n\n\tpublic static Frame frame;\n\n\tpublic static int planeID = 0;\n\n\tprotected static String loadChairLocation = null;\n\tpublic static String saveChairLocation = null;\n\tpublic static String savePatternLocation = null;\n\n\tprotected static String saveDXFLocation = null;\n\n\tprotected static String importSVGLocation = null;\n\n\n\n\t// create and load default properties\n\tProperties properties = new Properties();\n\n\tpublic static boolean debugPickBuffer =false;\n\n\tpublic static GUIPanelTabbed designToolbarPattern = null;\n\n\tpublic static GUIPanel cameraPanel;\n\n\tpublic static GUIPanel patternCameraPanel;\n\n\n\t\n\tpublic final static int color(int x, int y, int z) {\n\n\t\tif (x > 255)\n\t\t\tx = 255;\n\t\telse if (x < 0)\n\t\t\tx = 0;\n\t\tif (y > 255)\n\t\t\ty = 255;\n\t\telse if (y < 0)\n\t\t\ty = 0;\n\t\tif (z > 255)\n\t\t\tz = 255;\n\t\telse if (z < 0)\n\t\t\tz = 0;\n\n\t\treturn 0xff000000 | (x << 16) | (y << 8) | z;\n\n\t}\n\n\tpublic final static int color(int x, int y, int z, int a) {\n\n\t\tif (a > 255)\n\t\t\ta = 255;\n\t\telse if (a < 0)\n\t\t\ta = 0;\n\t\tif (x > 255)\n\t\t\tx = 255;\n\t\telse if (x < 0)\n\t\t\tx = 0;\n\t\tif (y > 255)\n\t\t\ty = 255;\n\t\telse if (y < 0)\n\t\t\ty = 0;\n\t\tif (z > 255)\n\t\t\tz = 255;\n\t\telse if (z < 0)\n\t\t\tz = 0;\n\n\t\treturn (a << 24) | (x << 16) | (y << 8) | z;\n\n\t}\n\n\t/**\n\t * @return the zOOM\n\t */\n\tpublic static double getZOOM() {\n\t\treturn ZOOM;\n\t}\n\n\tpublic static boolean isMacOSX() {\n\t\tString osName = System.getProperty(\"os.name\");\n\t\treturn osName.startsWith(\"Mac OS X\");\n\t}\n\n\t/**\n\t* @param zOOM the zOOM to set\n\t*/\n\tpublic static void setZOOM(float zOOM) {\n\t\tZOOM = zOOM;\n\t}\n\n\tGLOBAL(PApplet applet) {\n\t\t\n\t\tLOGGER.info(\"Making GLOBAL\");\n\t\t\t\n\n\t\tGLOBAL.applet = applet;\n\t\tgui = new ModalGUI();\n\t\tgui.applet = applet;\n\t\tgui.appletStatic = applet;\n\t\t\n\t\t\n\t\tZOOM = 1f;\n\t\tCAM_OFFSET_X = -600;\n\t\tCAM_OFFSET_Y = -900;\n\t\t\n\n\t\tthis.font = applet.loadFont(\"SegoeUI-12.vlw\");\n\t\t//this.font = applet.createFont(\"Helvetica\", 12);\n\n\t\tgui.myFontMedium = this.font;\n\t\t/*\n\t\tURL url = findResource(\"TrebuchetMS-12.vlw\");\n\t\ttry {\n\t\t InputStream input = createInput(filename);\n\t\t this.font = new PFont(input);\n\n\t\t } catch (Exception e) {\n\t\t die(\"Could not load font \" + filename + \". \" +\n\t\t \"Make sure that the font has been copied \" +\n\t\t \"to the data folder of your sketch.\", e);\n\t\t }\n\t\t */\n\n\t\tsketchChairs = new SketchChairs();\n\t\t//physics = new VerletPhysics(\n\t\t//new Vec3D(0, 2f, 0), 300, 90f, .090f);\n\t\tjBullet = new jBullet();\n\t\tuiTools = new UITools(applet);\n\t\t//ragDoll = null;\n\n\t\tenvironments = new Environments();\n\t\t/*\n\t\t * What mode are we in? 0 - sketch seat 1 - view in 3d\n\t\t */\n\t\tmode = 0;\n\n\t\trotateModelsX = 0;\n\t\trotateModelsY = 0;\n\n\t\tsavePDF = false;\n\t\t//\tpsketch_id;\n\t\tsetZOOM(1f);\n\n\t\tdebugRay = null;\n\t\tdebugRayIntersection = null;\n\n\t\tperson = null;\n\t\tshapePack = new spShapePack();\n\t\tundo = new Undo();\n\t\ttick = 0l;\n\n\t\tplanesWidget = new WidgetPlanes(0, 0, 0, 0, gui);\n\n\t\tloadWidget = new WidgetLoad();\n\t\twidgetMaterials = new WidgetMaterials(0, 0, 0, 0, gui);\n\n\t\tperformanceMode = false;\n\n\t\tfc = null;\n\t\tpdfSaveLocation = null;\n\t\tmeasuretTool = new MeasureTool();\n\t\tLAST_SAVED_LOCATION = null;\n\n\t\tSketchGlobals = new SketchGlobals();\n\t\tSketchGlobals.undo = this.undo;\n\n\t}\n\n\tpublic final int color(float x, float y, float z) {\n\n\t\tif (x > 255)\n\t\t\tx = 255;\n\t\telse if (x < 0)\n\t\t\tx = 0;\n\t\tif (y > 255)\n\t\t\ty = 255;\n\t\telse if (y < 0)\n\t\t\ty = 0;\n\t\tif (z > 255)\n\t\t\tz = 255;\n\t\telse if (z < 0)\n\t\t\tz = 0;\n\n\t\treturn 0xff000000 | ((int) x << 16) | ((int) y << 8) | (int) z;\n\n\t}\n\n}", "public class LOGGER {\n\n\tpublic static void debug(String message) {\n\t//System.out.println(message);\n\t}\n\n\tpublic static void debug(String message, Object obj) {\t\n\t//System.out.println(obj.getClass().getName()+\": \"+message);\n\t}\n\n\tpublic static void error(String message) {\n\t\tSystem.out.println(message);\n\t}\n\n\tpublic static void error(String message, Object obj) {\n\t\tSystem.out.println(obj.getClass().getName() + \": \" + message);\n\t}\n\n\t//log levels ERROR > WARNING > INFO > DEBUG\n\tpublic static void info(String message) {\n\t\tSystem.out.println(message);\n\t}\n\n\tpublic static void info(String message, Object obj) {System.out.println(obj.getClass().getName()+\": \"+message);\n\t}\n\n\tpublic static void warn(String message) {\n\t\tSystem.out.println(message);\n\t}\n\n\tpublic static void warn(String message, Object obj) {\n\t\tSystem.out.println(obj.getClass().getName() + \": \" + message);\n\t}\n\n\tpublic static void warning(String message) {\n\t\tSystem.out.println(message);\n\t}\n\n\tpublic static void warning(String message, Object obj) {\n\t\tSystem.out.println(obj.getClass().getName() + \": \" + message);\n\t}\n\n}", "public class SETTINGS {\n\n\tpublic static boolean DEVELOPER_MODE = false; //if on print to console etc\n\n\t\n\tpublic static final int UNDO_LEVELS = 20;\n\tpublic static final boolean build_collision_mesh_detailed = true;\n\tpublic static final float MIN_SPACING = 20f;\n\tpublic static final int THUMBNAIL_HEIGHT = 300;\n\tpublic static final int THUMBNAIL_WIDTH = 300;\n\n\tpublic static boolean REC = false;\n\tpublic static boolean draw_collision_mesh = false;\n\t\n\t//public static float slat_width = 50;// drawing tool width\n\t//public static float leg_width = 25;\n\tpublic static float person_friction = 1f;\n\tpublic static float chair_damping_linear = .0001f;\n\tpublic static float chair_damping_ang = .001f;\n\n\tpublic static int sphere_res = 6;\n\tpublic static double optimize_outline_min_angle = 3;\n\n\t//Quality settings\n\tpublic static int cylinder_res = 15;\n\n\tpublic static float scale = .1f;\n\t//public static float pixels_per_mm_base = 5.6689342403628117913832199546485f;\n\tpublic static float pixels_per_mm_base = 0.35289342403628117913832199546485f;\n\n\tpublic static float pixels_per_mm_screen = 5.6689342403628117913832199546485f;\n\tpublic static float pixels_per_mm = pixels_per_mm_base * scale;\n\n\tpublic static float chair_width = 300;\n\tpublic static float slat_num = 5;\n\n\tpublic static float slot_tollerance = .03f * pixels_per_mm;\n\tpublic static float materialThickness = 0.25f;\n\n\tpublic static float spline_point_every = 30;\n\n\t//Colours\n\n\tpublic static int GRID_MAJOR_LINE = GLOBAL.applet.color(0, 0, 0, 255);\n\tpublic static float GRID_MAJOR_LINE_WEIGHT = 1f;\n\n\tpublic static int GRID_MINOR_LINE = GLOBAL.applet.color(0, 0, 0, 55);\n\tpublic static float GRID_MINOR_LINE_WEIGHT = 1f;\n\n\t//public static int SKETCHSHAPE_FILL_UNSELECTED_COLOUR = GLOBAL.applet.color(240, 240, 240);\n\tpublic static final float DEFAULT_MATERIAL_WIDTH = .37f;\n\tpublic static final float DEFAULT_SLAT_SPACING = 85;\n\n\tpublic static int person_fill_colour = GLOBAL.applet.color(250, 250, 250);\n\n\tpublic static final boolean WEB_MODE = false;\n\tpublic static final boolean APPLET_MODE = false;\n\tpublic static final float DEFAULT_SLATSLICE_HEIGHT = 100;\n\tpublic static final float MIN_RENDER_WIDTH = .3f;\n\tpublic static final float MIN_LEG_LEN = 2.0f;\n\tpublic static final int MOUSE_CLICKED_MIN_TIME = 1000;\n\tpublic static final int MOUSE_PRESSED_MIN_TIME = 1300;\n\n\tpublic static final boolean ENABLE_SELECT_MODEL_PLANES = true;\n\t\n\t\n\tpublic static final float MIN_ZOOM = 0.2f;\n\tpublic static final float MAX_ZOOM = 5;\n\t\n\tpublic static final float MIN_CAM_X_OFFSET = -4000f;\n\tpublic static final float MAX_CAM_X_OFFSET = 4000;\n\t\n\tpublic static final float MIN_CAM_Y_OFFSET = -2000f;\n\tpublic static final float MAX_CAM_Y_OFFSET = 2000;\n\tpublic static final float panelWidth = 900;\n\tpublic static final float panelHeight = 110;\n\n\t\n\t\n\tpublic static boolean DEBUG = false;\n\tpublic static String LANGUAGE = \"ENG\";\n\tpublic static boolean EXHIBITION_MODE = true; // deptreciated \n\tpublic static boolean EXPERT_MODE = true;\n\tpublic static boolean TOUCH_SCREEN_MODE = false; \n\n\t\n\t\n\t//PERSON COLOURS\n\tpublic static int ERGODOLL_FILL_COLOUR = GLOBAL.applet.color(225, 225, 225);\n\tpublic static int ERGODOLL_FILL_COLOUR_PERFORMANCE = GLOBAL.applet.color(\n\t\t\t245, 245, 245);\n\tpublic static int person_height_text_fill_colour = GLOBAL.applet.color(10,\n\t\t\t10, 10);\n\n\t//ENVIRONMENT COLOURS\n\tpublic int world_ground_colour = GLOBAL.applet.color(190, 190, 190);\n\tpublic int world_ground_side_colour = GLOBAL.applet.color(50, 50, 50);\n\tpublic int world_ground_under_colour = GLOBAL.applet.color(50, 50, 50);\n\t\n\tpublic int background_colour = GLOBAL.applet.color(250, 250, 250);\n\n\tpublic static float gravity = 60f;\n\n\tpublic static boolean show_framerate = false;\n\n\tpublic int autoSaveInterval = 600;\n\tpublic float bezierDetail = 1;\n\tpublic static int renderWidth = 1500;\n\tpublic static int renderHeight = 1500;\n\t\n\tpublic static boolean autoSave = false;\n\tpublic static int chairSaveNum = 0;\n\tpublic static float chair_friction = 1;\n\tpublic static boolean seperate_slots = false;\n\n\tpublic static boolean auto_seat = true;\n\tpublic static boolean hybernate = true;\n\tpublic static boolean render_chairs = true;\n\tpublic static boolean auto_build = true;\n\tpublic static float version = .90f;\n\tpublic static float chair_slat_end_size = 45;\n\tpublic static float chair_slatslot_end_size = 25;\n\tpublic static boolean RENDER_CENTRE_MASS = false;\n\t\n\t//guide windows\n\tpublic static int GUIDE_WINDOW_WIDTH = 800;\n\tpublic static int GUIDE_WINDOW_HEIGHT = 500;\n\tpublic static boolean displayIntroPanel = false;\n\tpublic static boolean useSliceCollisionDetection = false;\n\tpublic static float simplifyAmount = 1f;\n\tpublic static boolean autoSaveMakePattern = false;\n\tpublic static String autoSaveMakeLocation = \"/\";\n\tpublic static boolean addLegSlices = true;\n\tpublic static boolean autoRefreshTextures = false;\n\tpublic static float mouseMoveClamp = 10;\n\tpublic static boolean autoReset = false;\n\tpublic static int autoResetSeconds = 60;\n\n\n\t\n\t\n\n}", "public class functions {\n\tpublic static int DONT_INTERSECT = 0;\n\tpublic static int COLLINEAR = 1;\n\tpublic static int DO_INTERSECT = 2;\n\n\tpublic static float x = 0;\n\tpublic static float y = 0;\n\n\tpublic static float angleOf(Vec2D v1) {\n\t\tv1.normalize();\n\t\tfloat an = (float) Math.atan2(v1.y, v1.x);\n\n\t\tif (an > 0.0) {\n\t\t\tan = (float) (Math.PI + (Math.PI - an));\n\t\t} else {\n\t\t\t// no negative nums\n\t\t\tan = (float) (Math.PI - (Math.PI - Math.abs(an)));\n\t\t}\n\n\t\treturn an;\n\t}\n\n\tpublic static float angleOfDot(Vec2D v1) {\n\t\tv1.normalize();\n\n\t\tfloat an = (float) Math.acos(v1.dot(new Vec2D(0, 0)));\n\n\t\treturn (float) Math.atan2(v1.y, v1.x);\n\n\t}\n\n\tpublic static float bezierPoint(float a, float b, float c, float d, float t) {\n\t\tfloat t1 = 1.0f - t;\n\t\treturn a * t1 * t1 * t1 + 3 * b * t * t1 * t1 + 3 * c * t * t * t1 + d\n\t\t\t\t* t * t * t;\n\t}\n\n\t/*\n\tpublic static void drawAllSprings(VerletPhysics physics, PGraphics g){\n\t g.stroke(255,0,0);\n\tg.strokeWeight(1f);\n\t\n\t for ( int i = 0; i < physics.springs.size(); ++i )\n\t {\n\t\n\tVerletSpring s = (VerletSpring) physics.springs.get( i );\n\t g.line(s.a.x, s.a.y,s.a.z,s.b.x, s.b.y,s.b.z);\n\t\n\t }\n\n\n\t}\n\n\n\tvoid drawAllParticles(VerletPhysics physics, PGraphics g){\n\t g.stroke(0,0,0,100);\n\t\n\t for ( int i = 0; i < physics.particles.size(); ++i )\n\t {\n\t\n\tVerletParticle p = (VerletParticle) physics.particles.get( i );\n\tg.sphereDetail(2);\n\tg.pushMatrix();\n\tg.translate(p.x,p.y,p.z);\n\tg.sphere(p.weight*2);\n\tg.popMatrix();\n\t\n\t\n\t }\n\t\n\t}\n\t/*\n\n\tpublic static void boundAllParticles(VerletPhysics physics){\n\n\tfor ( int i = 0; i < physics.particles.size(); ++i )\n\t{\n\tVerletParticle p = (VerletParticle) physics.particles.get( i );\n\n\tif(p.y > 550)\n\tp.y -= p.y-550;\n\n\t}\n\n\t}\n\t*/\n\n\tpublic final static int color(int x, int y, int z) {\n\n\t\tif (x > 255)\n\t\t\tx = 255;\n\t\telse if (x < 0)\n\t\t\tx = 0;\n\t\tif (y > 255)\n\t\t\ty = 255;\n\t\telse if (y < 0)\n\t\t\ty = 0;\n\t\tif (z > 255)\n\t\t\tz = 255;\n\t\telse if (z < 0)\n\t\t\tz = 0;\n\n\t\treturn 0xff000000 | (x << 16) | (y << 8) | z;\n\n\t}\n\n\tpublic static float curvePoint(float x2, float x3, float x4, float x5,\n\t\t\tfloat t) {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n\tpublic static void cylinder(float w1, float w2, float h, int sides,\n\t\t\tPGraphics g) {\n\t\t/*\n\t\tfloat angle;\n\t\t\n\t\tfloat[] x1 = new float[sides + 1];\n\t\tfloat[] z1 = new float[sides + 1];\n\n\t\tfloat[] x2 = new float[sides + 1];\n\t\tfloat[] z2 = new float[sides + 1];\n\n\t\t//get the x and z position on a circle for all the sides\n\t\tfor (int i = 0; i < x1.length; i++) {\n\t\t\tangle = (float) ((Math.PI * 2) / (sides) * i + 1);\n\t\t\tx1[i] = (float) (Math.sin(angle) * w1);\n\t\t\tz1[i] = (float) (Math.cos(angle) * w1);\n\t\t}\n\n\t\t//get the x and z position on a circle for all the sides\n\t\tfor (int i = 0; i < x2.length; i++) {\n\t\t\tangle = (float) ((Math.PI * 2) / (sides) * i + 1);\n\t\t\tx2[i] = (float) (Math.sin(angle) * w2);\n\t\t\tz2[i] = (float) (Math.cos(angle) * w2);\n\t\t}\n\n\t\t//draw the top of the cylinder\n\t\tg.beginShape(PConstants.TRIANGLE_FAN);\n\n\t\tg.vertex(0, -h / 2, 0);\n\n\t\tfor (int i = 0; i < x1.length; i++) {\n\t\t\tg.vertex(x1[i], -h / 2, z1[i]);\n\t\t}\n\n\t\tg.endShape();\n\n\t\t//draw the center of the cylinder\n\t\tg.beginShape(PConstants.QUAD_STRIP);\n\n\t\tfor (int i = 0; i < x1.length; i++) {\n\t\t\tg.vertex(x1[i], -h / 2, z1[i]);\n\t\t\tg.vertex(x2[i], h / 2, z2[i]);\n\t\t}\n\n\t\tg.endShape();\n\n\t\t//draw the bottom of the cylinder\n\t\tg.beginShape(PConstants.TRIANGLE_FAN);\n\n\t\tg.vertex(0, h / 2, 0);\n\n\t\tfor (int i = 0; i < x2.length; i++) {\n\t\t\tg.vertex(x2[i], h / 2, z2[i]);\n\t\t}\n\n\t\tg.endShape();\n\t\t*/\n\t}\n\n\tpublic static void cylinder(float w, float h, int sides, PGraphics g) {\n\t\tfloat angle;\n\t\tfloat[] x = new float[sides + 1];\n\t\tfloat[] z = new float[sides + 1];\n\n\t\t//get the x and z position on a circle for all the sides\n\t\tfor (int i = 0; i < x.length; i++) {\n\t\t\tangle = (float) ((Math.PI * 2) / (sides) * i);\n\t\t\tx[i] = (float) (Math.sin(angle) * w);\n\t\t\tz[i] = (float) (Math.cos(angle) * w);\n\t\t}\n\n\t\t//draw the top of the cylinder\n\t\tg.beginShape(PConstants.TRIANGLE_FAN);\n\n\t\tg.vertex(0, -h / 2, 0);\n\n\t\tfor (int i = 0; i < x.length; i++) {\n\t\t\tg.vertex(x[i], -h / 2, z[i]);\n\t\t}\n\n\t\tg.endShape();\n\n\t\t//draw the center of the cylinder\n\t\tg.beginShape(PConstants.QUAD_STRIP);\n\n\t\tfor (int i = 0; i < x.length; i++) {\n\t\t\tg.vertex(x[i], -h / 2, z[i]);\n\t\t\tg.vertex(x[i], h / 2, z[i]);\n\t\t}\n\n\t\tg.endShape();\n\n\t\t//draw the bottom of the cylinder\n\t\tg.beginShape(PConstants.TRIANGLE_FAN);\n\n\t\tg.vertex(0, h / 2, 0);\n\n\t\tfor (int i = 0; i < x.length; i++) {\n\t\t\tg.vertex(x[i], h / 2, z[i]);\n\t\t}\n\n\t\tg.endShape();\n\t}\n\n\t\n\tpublic static void flatCylinder(float r1, float r2, float len, Transform myTransform, PGraphics g) {\n\t\tPMatrix3D worldMatrix = new PMatrix3D();\n\t\tfloat matrixWorldScale = (float) (GLOBAL.getZOOM()*70.0f);//Where does this come from? \n\t\tList points = new ArrayList();\n\t\t//g.beginShape();\n\n\t\t\n\t\tg.pushMatrix();\n\t\tg.translate(0, -len/2.0f, 0);\n\t\tfloat screenX1 = g.screenX(0,0,0);\n\t\tfloat screenY1 = g.screenY(0,0,0);\n\t\tfloat screenZ1 = g.screenZ(0,0,0);\n\t\t\n\n\n\t\t\n\t\tg.popMatrix();\n\t\t\n\t\tg.pushMatrix();\n\t\tg.translate(0, len/2.0f, 0);\n\t\tfloat screenX2 = g.screenX(0,0,0);\n\t\tfloat screenY2 = g.screenY(0,0,0);\n\t\tfloat screenZ2 = g.screenZ(0,0,0);\n\n\t\tg.popMatrix();\n\t\t\n\t\t\n\t\tfloat atan = (float)Math.atan((screenY1-screenY2)/(screenX1-screenX2));\n\n\t\t\t\n\t\t\n\t\tg.pushMatrix();\n\t\tg.translate(0, -len/2.0f-0.1f, 0);\n\n\t\t worldMatrix = new PMatrix3D();\n\t\tg.getMatrix(worldMatrix);\n\t\tworldMatrix.m00 = matrixWorldScale;worldMatrix.m01 = 0;worldMatrix.m02 = 0;\n\t\tworldMatrix.m10 = 0;worldMatrix.m11 = matrixWorldScale;worldMatrix.m12 = 0;\n\t\tg.setMatrix(worldMatrix);\n\t\tg.rotate(atan);\n\t\tfloat worldX1 = g.screenX(0,0,0);\n\t\tfloat worldY1 = g.screenY(0,0,0);\n\t\tfloat worldZ1 = g.screenZ(0,0,0);\n\t\t\n\t\tg.popMatrix();\n\t\t\n\t\t\n\t\tg.pushMatrix();\n\t\tg.translate(0, len/2.0f+0.1f, 0);\n\n\t\t worldMatrix = new PMatrix3D();\n\t\tg.getMatrix(worldMatrix);\n\t\tworldMatrix.m00 = matrixWorldScale;worldMatrix.m01 = 0;worldMatrix.m02 = 0;\n\t\tworldMatrix.m10 = 0;worldMatrix.m11 = matrixWorldScale;worldMatrix.m12 = 0;\n\t\tg.setMatrix(worldMatrix);\n\t\tg.rotate(atan);\n\t\tfloat worldX2 = g.screenX(0,0,0);\n\t\tfloat worldY2 = g.screenY(0,0,0);\n\t\tfloat worldZ2 = g.screenZ(0,0,0);\n\t\t\n\t\tg.popMatrix();\n\t\t\n\n\t\tfloat worldDist =(float) Math.sqrt(Math.pow(worldX2-worldX1,2) + Math.pow(worldY2-worldY1,2)+ Math.pow(worldZ2-worldZ1,2) )/matrixWorldScale;\n\t\nif(screenX1 < screenX2)\n\tatan -= (float)(Math.PI/2);\nelse\n\tatan += (float)(Math.PI/2);\n\n\n\t\t//side curve\n\t\tg.pushMatrix();\n\t\tg.translate(0, -len/2.0f-0.1f, 0);\n\n\t\t worldMatrix = new PMatrix3D();\n\t\tg.getMatrix(worldMatrix);\n\t\t//billboard matrix\n\t\tworldMatrix.m00 = matrixWorldScale;worldMatrix.m01 = 0;worldMatrix.m02 = 0;\n\t\tworldMatrix.m10 = 0;worldMatrix.m11 = matrixWorldScale;worldMatrix.m12 = 0;\n\t\tg.setMatrix(worldMatrix);\n\t\tg.rotate(atan);\n\n\t\t\n\t\t\n\t\tg.noStroke();\n\t\tg.fill(228);\n\t\tg.beginShape();\n\t\tg.vertex(-r1/2, 0,-0.1f);\n\t\tg.vertex( -r2/2, worldDist,-0.1f);\n\t\tg.vertex(r2/2, worldDist,-0.1f);\n\t\tg.vertex(r1/2, 0,-0.1f);\n\t\tg.endShape(PApplet.CLOSE);\n\t\t\n\t\tg.noFill();\n\t\tg.stroke(0);\n\t\tg.strokeWeight(2);\n\t\t\n\t\tg.line(-r1/2, 0, -r2/2, worldDist);\n\t\tg.line(r1/2,0, r2/2, worldDist);\n\t\t\n\t\t\n\t\t\n\n\t\t\n\t\tg.popMatrix();\n\n\t\t\n\t\t\n\t\t\n\t\t//Top curve\n\t\tg.pushMatrix();\n\t\tg.translate(0, -len/2.0f, 0);\n\t\tworldMatrix = new PMatrix3D();\n\t\tg.getMatrix(worldMatrix);\n\t\t//billboard matrix\n\t\tworldMatrix.m00 = matrixWorldScale;worldMatrix.m01 = 0;worldMatrix.m02 = 0;\n\t\tworldMatrix.m10 = 0;worldMatrix.m11 = matrixWorldScale;worldMatrix.m12 = 0;\n\t\t//worldMatrix.m20 = 0;worldMatrix.m21 = 0;worldMatrix.m22 = worldMatrix.m22;\n\t\tg.setMatrix(worldMatrix);\n\t\tg.rotate(atan);\n\t\t\n\t\t\n\t\tg.noStroke();\n\t\tg.fill(228);\n\t\tg.beginShape();\n\t\t for(float a=(float)(float) (Math.PI+(Math.PI/2)) ; a >= (float) (Math.PI/2); a -=0.1f) {\n\t\t\t g.vertex((float)(Math.sin(a)*(r1/2))+0,(float)(Math.cos(a)*(r1/2))+0,-0.1f);\n\t\t} \n\t\tg.endShape();\n\t\t\n\t\t\n\t\tg.noFill();\n\t\tg.stroke(0);\n\t\tg.strokeWeight(2);//top curve weight\n\t\tg.beginShape();\n\t\t for(float a=(float)(float) (Math.PI+(Math.PI/2)) ; a >= (float) (Math.PI/2); a -=0.1f) {\n\t\t\t g.vertex((float)(Math.sin(a)*(r1/2))+0,(float)(Math.cos(a)*(r1/2))+0);\n\t\t\t points.add(new PVector(g.modelX((float)(Math.sin(a)*(r1/2))+0,(float)(Math.cos(a)*(r1/2))+0,0),\n\t\t\t \t\tg.modelY((float)(Math.sin(a)*(r1/2))+0,(float)(Math.cos(a)*(r1/2))+0,0),\n\t\t\t \t\tg.modelZ((float)(Math.sin(a)*(r1/2))+0,(float)(Math.cos(a)*(r1/2))+0,0)));\n\t\t} \n\t\tg.endShape();\n\t\t\n\t\t\n\t\tg.strokeWeight(1);\n\t\tg.stroke(255,0,0);\n\t\t//g.ellipse(0, 0, r1,r1);\n\t\tg.popMatrix();\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t//bottom curve\n\t\tg.pushMatrix();\n\t\tg.translate(0, len/2.0f, 0);\n\n\t\t worldMatrix = new PMatrix3D();\n\t\tg.getMatrix(worldMatrix);\n\t\t//billboard matrix\n\t\tworldMatrix.m00 = matrixWorldScale;worldMatrix.m01 = 0;worldMatrix.m02 = 0;\n\t\tworldMatrix.m10 = 0;worldMatrix.m11 = matrixWorldScale;worldMatrix.m12 = 0;\n\t\t//worldMatrix.m20 = 0;worldMatrix.m21 = 0;worldMatrix.m22 = worldMatrix.m22;\n\n\t\t//g.printMatrix();\n\t\tg.setMatrix(worldMatrix);\n\t\tg.rotate(atan);\n\n\t\t\n\t\tg.noStroke();\n\t\tg.fill(228);\n\t\tg.beginShape();\n\t\t for(float a= (float)(Math.PI/2); a >= (float) -(Math.PI/2) ; a -=0.1f) {\n\t\t\t g.vertex((float)(Math.sin(a)*(r2/2))+0,(float)(Math.cos(a)*(r2/2))+0,-0.1f);\n\t\t\t points.add(new PVector(g.modelX((float)(Math.sin(a)*(r2/2))+0,(float)(Math.cos(a)*(r2/2))+0,0),\n\t\t\t \t\tg.modelY((float)(Math.sin(a)*(r2/2))+0,(float)(Math.cos(a)*(r2/2))+0,0),\n\t\t\t \t\tg.modelZ((float)(Math.sin(a)*(r2/2))+0,(float)(Math.cos(a)*(r2/2))+0,0)));\n\t\t} \n\t\t g.endShape();\n\t\t\n\t\tg.noFill();\n\t\tg.stroke(0);\n\t\tg.strokeWeight(2);\n\t\t\n\t\tg.beginShape();\n\t\t for(float a= (float)(Math.PI/2); a >= (float) -(Math.PI/2) ; a -=0.1f) {\n\t\t\t g.vertex((float)(Math.sin(a)*(r2/2))+0,(float)(Math.cos(a)*(r2/2))+0);\n\t\t} \n\t\t g.endShape();\n\n\t\tg.strokeWeight(1);\n\t\tg.stroke(255,0,0);\n\t\t//g.ellipse(0, 0, r2,r2);\n\t\t\n\t\tg.popMatrix();\t\n\t\t//g.endShape();\n\t\t\n\t\tg.pushMatrix();\n\t\tg.resetMatrix();\n\t\t//g.translate(-GLOBAL.windowWidth/2, -GLOBAL.windowHeight/2);\n\t\tg.translate(-GLOBAL.windowWidth/2, -GLOBAL.windowHeight/2);\n\t\tg.stroke(0);\n\t\tg.strokeWeight(3);\n\t\tg.fill(255);\n\n\t\tg.beginShape();\n\t\tfor(int i = 0 ; i < points.size() ; i++){\n\t\t\tPVector p = (PVector)points.get(i);\n\t\t\t//g.vertex(p.x,p.y,p.z/matrixWorldScale);\n\t\t}\n\t\tg.endShape(PApplet.CLOSE);\n\t\tg.popMatrix();\n\t\tg.noStroke();\n\t\tg.fill(228);\n\t\t\n\t}\n\n\t\n\tpublic static boolean fileExists(String filename) {\n\n\t\tFile file = new File(filename);\n\n\t\tif (!file.exists())\n\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\tpublic static String getComputerName() {\n\n\t\treturn \"name\";\n\t\t/*\n\t\ttry{\n\t\t String computername=InetAddress.getLocalHost().getHostName();\n\t\treturn computername;\n\t\t}catch (Exception e){\n\t\t\treturn null;\n\t\t}\\*/\n\t}\n\n\tpublic static String getFileName() {\n\n\t\tCalendar now = Calendar.getInstance();\n\t\tLong time = now.getTimeInMillis();\n\t\treturn time.toString();\n\t}\n\n\n\t\n\tpublic static ByteBuffer getIndexBuffer(int[] indices) {\n\t\tByteBuffer buf = ByteBuffer.allocateDirect(indices.length * 4).order(\n\t\t\t\tByteOrder.nativeOrder());\n\t\tfor (int i = 0; i < indices.length; i++) {\n\t\t\tbuf.putInt(indices[i]);\n\t\t}\n\t\tbuf.flip();\n\t\treturn buf;\n\t}\n\n\tpublic static ByteBuffer getVertexBuffer(float[] vertices) {\n\t\tByteBuffer buf = ByteBuffer.allocateDirect(vertices.length * 4).order(\n\t\t\t\tByteOrder.nativeOrder());\n\t\tfor (int i = 0; i < vertices.length; i++) {\n\t\t\tbuf.putFloat(vertices[i]);\n\t\t}\n\t\tbuf.flip();\n\t\treturn buf;\n\t}\n\n\tpublic static int intersect(float x1, float y1, float x2, float y2,\n\t\t\tfloat x3, float y3, float x4, float y4) {\n\n\t\tfloat a1, a2, b1, b2, c1, c2;\n\t\tfloat r1, r2, r3, r4;\n\t\tfloat denom, offset, num;\n\n\t\t// Compute a1, b1, c1, where line joining points 1 and 2\n\t\t// is \"a1 x + b1 y + c1 = 0\".\n\t\ta1 = y2 - y1;\n\t\tb1 = x1 - x2;\n\t\tc1 = (x2 * y1) - (x1 * y2);\n\n\t\t// Compute r3 and r4.\n\t\tr3 = ((a1 * x3) + (b1 * y3) + c1);\n\t\tr4 = ((a1 * x4) + (b1 * y4) + c1);\n\n\t\t// Check signs of r3 and r4. If both point 3 and point 4 lie on\n\t\t// same side of line 1, the line segments do not intersect.\n\t\tif ((r3 != 0) && (r4 != 0) && same_sign(r3, r4)) {\n\t\t\treturn DONT_INTERSECT;\n\t\t}\n\n\t\t// Compute a2, b2, c2\n\t\ta2 = y4 - y3;\n\t\tb2 = x3 - x4;\n\t\tc2 = (x4 * y3) - (x3 * y4);\n\n\t\t// Compute r1 and r2\n\t\tr1 = (a2 * x1) + (b2 * y1) + c2;\n\t\tr2 = (a2 * x2) + (b2 * y2) + c2;\n\n\t\t// Check signs of r1 and r2. If both point 1 and point 2 lie\n\t\t// on same side of second line segment, the line segments do\n\t\t// not intersect.\n\t\tif ((r1 != 0) && (r2 != 0) && (same_sign(r1, r2))) {\n\t\t\treturn DONT_INTERSECT;\n\t\t}\n\n\t\t//Line segments intersect: compute intersection point.\n\t\tdenom = (a1 * b2) - (a2 * b1);\n\n\t\tif (denom == 0) {\n\t\t\treturn COLLINEAR;\n\t\t}\n\n\t\tif (denom < 0) {\n\t\t\toffset = -denom / 2;\n\t\t} else {\n\t\t\toffset = denom / 2;\n\t\t}\n\n\t\t// The denom/2 is to get rounding instead of truncating. It\n\t\t// is added or subtracted to the numerator, depending upon the\n\t\t// sign of the numerator.\n\t\tnum = (b1 * c2) - (b2 * c1);\n\t\tif (num < 0) {\n\t\t\tx = (num - offset) / denom;\n\t\t} else {\n\t\t\tx = (num + offset) / denom;\n\t\t}\n\n\t\tnum = (a2 * c1) - (a1 * c2);\n\t\tif (num < 0) {\n\t\t\ty = (num - offset) / denom;\n\t\t} else {\n\t\t\ty = (num + offset) / denom;\n\t\t}\n\n\t\t// lines_intersect\n\t\treturn DO_INTERSECT;\n\t}\n\n\tpublic static int intersect(Vec2D a1, Vec2D a2, Vec2D b1, Vec2D b2,\n\t\t\tVec2D b3, Vec2D b4) {\n\n\t\tif (functions.intersect(a1.x, a1.y, a2.x, a2.y, b1.x, b1.y, b2.x, b2.y) == functions.DO_INTERSECT)\n\t\t\treturn functions.DO_INTERSECT;\n\n\t\tif (functions.intersect(a1.x, a1.y, a2.x, a2.y, b2.x, b2.y, b3.x, b3.y) == functions.DO_INTERSECT)\n\t\t\treturn functions.DO_INTERSECT;\n\n\t\tif (functions.intersect(a1.x, a1.y, a2.x, a2.y, b3.x, b3.y, b4.x, b4.y) == functions.DO_INTERSECT)\n\t\t\treturn functions.DO_INTERSECT;\n\n\t\tif (functions.intersect(a1.x, a1.y, a2.x, a2.y, b4.x, b4.y, b1.x, b1.y) == functions.DO_INTERSECT)\n\t\t\treturn functions.DO_INTERSECT;\n\n\t\treturn functions.DONT_INTERSECT;\n\t}\n\n\tpublic static int intersect(Vec2D a1, Vec2D a2, Vec2D a3, Vec2D a4,\n\t\t\tVec2D b1, Vec2D b2, Vec2D b3, Vec2D b4) {\n\n\t\tif (functions.intersect(a1, a2, b1, b2, b3, b4) == functions.DO_INTERSECT)\n\t\t\treturn functions.DO_INTERSECT;\n\n\t\tif (functions.intersect(a2, a3, b1, b2, b3, b4) == functions.DO_INTERSECT)\n\t\t\treturn functions.DO_INTERSECT;\n\n\t\tif (functions.intersect(a3, a4, b1, b2, b3, b4) == functions.DO_INTERSECT)\n\t\t\treturn functions.DO_INTERSECT;\n\n\t\tif (functions.intersect(a4, a1, b1, b2, b3, b4) == functions.DO_INTERSECT)\n\t\t\treturn functions.DO_INTERSECT;\n\n\t\treturn functions.DONT_INTERSECT;\n\t}\n\n\tstatic boolean same_sign(float a, float b) {\n\n\t\treturn ((a * b) >= 0);\n\t}\n\n\tpublic final int color(float x, float y, float z) {\n\n\t\tif (x > 255)\n\t\t\tx = 255;\n\t\telse if (x < 0)\n\t\t\tx = 0;\n\t\tif (y > 255)\n\t\t\ty = 255;\n\t\telse if (y < 0)\n\t\t\ty = 0;\n\t\tif (z > 255)\n\t\t\tz = 255;\n\t\telse if (z < 0)\n\t\t\tz = 0;\n\n\t\treturn 0xff000000 | ((int) x << 16) | ((int) y << 8) | (int) z;\n\n\t}\n\n\t/**\n\t * Creates colors for storing in variables of the <b>color</b> datatype. The parameters are interpreted as RGB or HSB values depending on the current <b>colorMode()</b>. The default mode is RGB values from 0 to 255 and therefore, the function call <b>color(255, 204, 0)</b> will return a bright yellow color. More about how colors are stored can be found in the reference for the <a href=\"color_datatype.html\">color</a> datatype.\n\t *\n\t * @webref color:creating_reading\n\t * @param x red or hue values relative to the current color range\n\t * @param y green or saturation values relative to the current color range\n\t * @param z blue or brightness values relative to the current color range\n\t * @param a alpha relative to current color range\n\t *\n\t * @see processing.core.PApplet#colorMode(int)\n\t * @ref color_datatype\n\t */\n\tpublic final int color(float x, float y, float z, float a) {\n\t\tif (a > 255)\n\t\t\ta = 255;\n\t\telse if (a < 0)\n\t\t\ta = 0;\n\t\tif (x > 255)\n\t\t\tx = 255;\n\t\telse if (x < 0)\n\t\t\tx = 0;\n\t\tif (y > 255)\n\t\t\ty = 255;\n\t\telse if (y < 0)\n\t\t\ty = 0;\n\t\tif (z > 255)\n\t\t\tz = 255;\n\t\telse if (z < 0)\n\t\t\tz = 0;\n\n\t\treturn ((int) a << 24) | ((int) x << 16) | ((int) y << 8) | (int) z;\n\n\t}\n\n\tpublic final static int color(int x, int y, int z, int a) {\n\n\t\tif (a > 255)\n\t\t\ta = 255;\n\t\telse if (a < 0)\n\t\t\ta = 0;\n\t\tif (x > 255)\n\t\t\tx = 255;\n\t\telse if (x < 0)\n\t\t\tx = 0;\n\t\tif (y > 255)\n\t\t\ty = 255;\n\t\telse if (y < 0)\n\t\t\ty = 0;\n\t\tif (z > 255)\n\t\t\tz = 255;\n\t\telse if (z < 0)\n\t\t\tz = 0;\n\n\t\treturn (a << 24) | (x << 16) | (y << 8) | z;\n\n\t}\n\n\tpublic static Vec2D rotate(Vec2D curVec, Vec2D center, float r) {\n\t\tVec2D returnVec = curVec.copy();\n\t\treturnVec.subSelf(center);\n\t\treturnVec.rotate(r);\n\t\treturnVec.addSelf(center);\n\t\treturn returnVec;\n\t\t\n\t\t\n\t}\n\n\tpublic static List getRange(List l, int start,\n\t\t\tint end) {\n\t\tList returnList = new ArrayList();\n\t\tfor(int i = start; i <= end; i++)\n\t\t\treturnList.add(l.get(i));\n\t\t\n\t\treturn returnList;\n\t\t\t}\n\n\n\n\n}", "public class Sketch {\n\tpublic static final int RENDER_3D_EDITING_PLANES = 1; // a plane is selected and being edited\n\tpublic static final int RENDER_3D_PREVIW = 2; // top right hand preview and layer selector\n\tpublic static final int RENDER_3D_DIAGRAM = 3; // exporting a picture as a diagram // add extra edges\n\tpublic static final int RENDER_EDIT_SELECT = 4; //\n\tpublic static final int RENDER_3D_NORMAL = 5; // Nothing is selected or being edited\n\t\n\tSketchShapes sketchShapes;\n\tboolean selected = true;\n\tpublic SketchTools sketchTools;\n\n\tpublic SketchGlobals sketchGlobals;\n\tprivate SlicePlane onSlicePlane;\n\tpublic boolean screenshot = false;\n\n\tpublic int sketch_id;\n\tprivate ArrayList<Object> selectedNodes = new ArrayList();\n\tprivate boolean layerSelected = true;\n\n\tprivate int renderMode;\n\tprivate boolean render3D;\n\n\tpublic Sketch(PApplet app) {\n\t\tsketchShapes = new SketchShapes(this);\n\t\tsetSketchTools(new SketchTools(app));\n\t\tsetSketchGlobals(new SketchGlobals());\n\t}\n\n\tpublic Sketch(SketchTools sTools, SketchGlobals sGlobals) {\n\t\tsketchShapes = new SketchShapes(this);\n\t\tsetSketchTools(sTools);\n\t\tsetSketchGlobals(sGlobals);\n\t}\n\n\tpublic Sketch(SketchTools sTools, SketchGlobals sGlobals, Element element) {\n\t\tsetSketchTools(sTools);\n\t\tsetSketchGlobals(sGlobals);\n\t\tsketchShapes = new SketchShapes(this, element);\n\t}\n\n\tpublic Sketch(SketchTools sTools, SketchGlobals sGlobals, SlicePlane slice) {\n\t\tsketchShapes = new SketchShapes(this);\n\t\tsketchShapes.onSlicePlane = slice;\n\t\tsetSketchTools(sTools);\n\t\tsetSketchGlobals(sGlobals);\n\t}\n\n\tpublic void add(SketchShape sketchShape) {\n\t\tsketchShapes.add(sketchShape);\n\t}\n\n\tpublic boolean addPointAlongPath(float x, float y) {\n\t\treturn sketchShapes.addPointAlongPath(x, y);\n\n\t}\n\n\tpublic void build() {\n\t\tfor (int i = 0; i < this.getSketchShapes().l.size(); i++) {\n\t\t\tSketchShape s = this.getSketchShapes().l.get(i);\n\t\t\ts.build();\n\t\t}\n\t\tthis.buildOutline();\n\t}\n\n\tpublic void buildOutline() {\n\t\tsketchShapes.buildOutline(false, false);\n\t}\n\n\tpublic void buildOutline(boolean addSlots, boolean booleanSlots) {\n\t\tsketchShapes.buildOutline(addSlots, booleanSlots);\n\n\t}\n\t\n\n\tpublic Sketch clone() {\n\t\tSketch s = new Sketch(getSketchTools(), getSketchGlobals());\n\t\ts.sketchShapes = this.sketchShapes.clone();\n\t\ts.sketchShapes.setParentSketch(s);\n\n\t\treturn s;\n\t\t//return clone();\n\t}\n\n\tpublic boolean contains(SketchShape path) {\n\t\treturn sketchShapes.contains(path);\n\t}\n\n\tpublic Sketch copy() {\n\t\tSketch newSketch = new Sketch(this.getSketchTools(),\n\t\t\t\tthis.getSketchGlobals());\n\t\tnewSketch.sketchShapes = this.sketchShapes.copy(newSketch);\n\t\treturn newSketch;\n\t}\n\n\tpublic int countSelectedNodes() {\n\t\treturn sketchShapes.countSelectedNodes();\n\n\t}\n\n\tpublic void deleteAll() {\n\t\tthis.getSketchShapes().deleteAll();\n\t}\n\n\tpublic void deleteSelectedNodes() {\n\t\tfor (int i = 0; i < this.getSelectedNodes().size(); i++) {\n\t\t\tSketchPoint sketchP = (SketchPoint) this.getSelectedNodes().get(i);\n\t\t\tthis.removeVertex(sketchP);\n\t\t}\n\t\tthis.buildOutline();\n\t}\n\n\tpublic void deleteSelectedShapes() {\n\t\tsketchShapes.deleteSelectedShapes();\n\t\tthis.buildOutline();\n\t\tthis.deleteSelectedNodes();\n\t}\n\n\tpublic void flipHorizontal(toxi.geom.Vec3D centre) {\n\t\tsketchShapes.flipHorizontal(centre);\n\t}\n\n\tpublic PApplet getApplet() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n\tpublic float getArea() {\n\t\treturn sketchShapes.getArea();\n\n\t}\n\n\tpublic Vec2D getCentreOfMass() {\n\t\treturn sketchShapes.getCentreOfMass();\n\t}\n\n\tpublic SketchPoint getClosestPathVertex(Vec2D pointOnPlan) {\n\t\treturn sketchShapes.getClosestPathVertex(pointOnPlan);\n\t}\n\n\tpublic SketchShape getCurrentShape() {\n\t\treturn getSketchShapes().currentShape;\n\t}\n\n\tpublic SketchShape getFirst() {\n\t\treturn sketchShapes.getFirst();\n\t}\n\n\tpublic float getHeight() {\n\t\treturn sketchShapes.getHeight();\n\t}\n\n\tpublic SketchShape getLast() {\n\t\treturn sketchShapes.getLast();\n\t}\n\n\tpublic Vec2D getLastVec() {\n\t\treturn sketchShapes.getLastVec();\n\t}\n\n\tpublic boolean getLayerSelected() {\n\t\treturn this.layerSelected;\n\t}\n\n\tpublic float getMaxX() {\n\t\treturn sketchShapes.getMaxX();\n\t}\n\n\tpublic float getMaxXWorldSpace(Transform currentWorldTransform) {\n\t\treturn sketchShapes.sketchOutlines\n\t\t\t\t.getMaxXWorldSpace(currentWorldTransform);\n\t}\n\n\tpublic float getMaxY() {\n\t\treturn sketchShapes.getMaxY();\n\t}\n\n\tpublic float getMaxYWorldSpace(Transform currentWorldTransform) {\n\t\treturn sketchShapes.sketchOutlines\n\t\t\t\t.getMaxYWorldSpace(currentWorldTransform);\n\t}\n\n\tpublic float getMinX() {\n\t\treturn sketchShapes.sketchOutlines.getMinX();\n\t}\n\n\tpublic float getMinXWorldSpace(Transform currentWorldTransform) {\n\t\treturn sketchShapes.sketchOutlines\n\t\t\t\t.getMinXWorldSpace(currentWorldTransform);\n\t}\n\n\tpublic float getMinY() {\n\t\treturn sketchShapes.sketchOutlines.getMinY();\n\t}\n\n\tpublic float getMinYWorldSpace(Transform currentWorldTransform) {\n\t\treturn sketchShapes.sketchOutlines\n\t\t\t\t.getMinYWorldSpace(currentWorldTransform);\n\t}\n\n\tpublic SlicePlane getOnSketchPlane() {\n\t\treturn getOnSlicePlane();\n\t}\n\n\t/**\n\t * @return the onSlicePlane\n\t */\n\tpublic SlicePlane getOnSlicePlane() {\n\t\treturn onSlicePlane;\n\t}\n\n\tpublic SketchPoint getOverSelectPoint(float x, float y) {\n\t\treturn sketchShapes.getOverSelectPoint(x, y);\n\t}\n\n\tpublic List<SketchShape> getOverShape(float x, float y) {\n\t\treturn sketchShapes.getOverShape(x,y);\n\t}\n\n\tpublic int getRenderMode() {\n\t\treturn this.renderMode;\n\t}\n\n\tprotected ArrayList<Object> getSelectedNodes() {\n\t\treturn this.selectedNodes;\n\t}\n\n\tpublic SketchShape getSelectedShape() {\n\t\t// TODO Auto-generated method stub\n\t\treturn getSketchShapes().selectedShape;\n\t}\n\n\tpublic SketchShape getShapePickBuffer(int col) {\n\t\treturn sketchShapes.getShapePickBuffer(col);\n\t}\n\n\tpublic SketchGlobals getSketchGlobals() {\n\t\treturn sketchGlobals;\n\t}\n\n\tpublic SketchShape getSketchShapeById(int linkedSketchId) {\n\t\treturn sketchShapes.getSketchShapeById(linkedSketchId);\n\t}\n\n\tpublic SketchShapes getSketchShapes() {\n\t\t// TODO Auto-generated method stub\n\t\treturn sketchShapes;\n\t}\n\n\tpublic SketchTools getSketchTools() {\n\t\treturn sketchTools;\n\t}\n\n\t/**\n\t * @return the slots\n\t */\n\tpublic SliceSlots getSlots() {\n\t\treturn sketchShapes.getSlots();\n\t}\n\n\tpublic spShape getspShape() {\n\t\treturn sketchShapes.getspShape();\n\t}\n\n\tpublic Vec2D getVec2DpickBuffer(int col) {\n\t\treturn sketchShapes.getVec2DpickBuffer(col);\n\n\t}\n\n\tpublic int getZOOM() {\n\t\t// TODO Auto-generated method stub\n\t\treturn 1;\n\t}\n\n\tprivate boolean isEditing() {\n\t\treturn sketchShapes.isEditing();\n\t}\n\n\tboolean isSelected() {\n\t\t//return false;\n\t\treturn sketchShapes.selected;\n\t}\n\n\tpublic boolean lastSketchOverlaps() {\n\t\treturn sketchShapes.lastSketchOverlaps();\n\t}\n\n\tpublic void mouseDragged(float mouseX, float mouseY) {\n\n\t\t//#IF JAVA\n\t\tif(GLOBAL.gui != null && GLOBAL.gui.overComponent())\n\t\t\treturn;\n\t\t//#ENDIF JAVA\n\t\t\n\t\tsketchShapes.mouseDragged(mouseX, mouseY);\n\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.DRAW_TOOL) {\n\n\t\t\tif (getCurrentShape() != null) {\n\t\t\t\tgetCurrentShape().add(new SketchPoint(mouseX, mouseY));\n\t\t\t}\n\n\t\t}\n\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.LEG_TOOL) {\n\t\t\tVec2D pointOnPlan = new Vec2D(mouseX, mouseY);\n\t\t\tif (getLastVec() != null) {\n\t\t\t\tgetLastVec().set(pointOnPlan.x, pointOnPlan.y);\n\t\t\t\tgetCurrentShape().offset();\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void mousePressed(float mouseX, float mouseY) {\n\t\t\n\t\tLOGGER.debug(\"mousePressed\" +getSketchTools().getMouseButton());\n\n\t\t\n\t\t//#IF JAVA\n\t\tif(GLOBAL.gui != null && GLOBAL.gui.overComponent())\n\t\t\treturn;\n\t\t//#ENDIF JAVA\n\t\t\n\n\t\t//DRAW TOOL OPERATIONS\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.DRAW_TOOL\n\t\t\t\t&& getSketchTools().getMouseButton() == SketchTools.MOUSE_LEFT) {\n\t\t\tVec2D pointOnPlan = new Vec2D(mouseX, mouseY);\n\t\t\t//alert(pointOnPlan.distanceTo(pointOnPlan.add(new Vec2D(10,10))));\n\t\t\tSketchPoint sp = new SketchPoint(mouseX, mouseY);\n\t\t\t//alert(sp.distanceTo(pointOnPlan.add(new Vec2D(10,10))));\n\n\t\t\tSketchSpline newSketch = new SketchSpline(this,\n\t\t\t\t\tSketchSpline.OFFSET_BOTH);\n\t\t\tnewSketch.setOffsetSize(getSketchTools().brush_dia);\n\t\t\tnewSketch.setCap(getSketchTools().getCurrentCapType());\n\t\t\tnewSketch.add(new SketchPoint(mouseX, mouseY));\n\t\t\tnewSketch.setType(SketchShape.TYPE_SPLINE);\n\t\t\tadd(newSketch);\n\t\t\tsetCurrentShape(newSketch);\n\n\t\t\t//if(getSketchGlobals().undo != null)\n\t\t\t//getSketchGlobals().undo.addOperation(new UndoAction(newSketch,UndoAction.ADD_SHAPE));\t\n\t\t}\n\n\t\t//LEG TOOL OPERATIONS\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.LEG_TOOL\n\t\t\t\t&& getSketchTools().getMouseButton() == SketchTools.MOUSE_LEFT) {\n\n\t\t\tVec2D pointOnPlan = new Vec2D(mouseX, mouseY);\n\n\t\t\tSketchSpline newSketch = new SketchSpline(this,\n\t\t\t\t\tSketchSpline.OFFSET_BOTH);\n\t\t\tnewSketch.setType(SketchSpline.TYPE_LEG);\n\t\t\tnewSketch.setOffsetSize(getSketchTools().brush_dia\n\t\t\t\t\t* SETTINGS_SKETCH.LEG_BRUSH_RATIO_TOP);\n\t\t\t//newSketch.offsetSizeEnd = getSketchTools().brush_dia*SETTINGS_SKETCH.LEG_BRUSH_RATIO_BOTTOM;\n\t\t\tnewSketch.getCentreOffset().put(\n\t\t\t\t\t1,\n\t\t\t\t\tgetSketchTools().brush_dia\n\t\t\t\t\t\t\t* SETTINGS_SKETCH.LEG_BRUSH_RATIO_BOTTOM);\n\t\t\tnewSketch.capType = SketchSpline.CAP_LEG;\n\n\t\t\tnewSketch.add(new SketchPoint(pointOnPlan.x, pointOnPlan.y));\n\t\t\tnewSketch.add(new SketchPoint(pointOnPlan.x, pointOnPlan.y));\n\t\t\tnewSketch.path.editable = true;\n\t\t\tadd(newSketch);\n\t\t\tsetCurrentShape(newSketch);\n\t\t\t//getSketchGlobals().undo.addOperation(new UndoAction(newSketch,UndoAction.ADD_SHAPE));\n\t\t}\n\n\t\tif ((getSketchTools().getCurrentTool() == SketchTools.SELECT_TOOL || getSketchTools()\n\t\t\t\t.getCurrentTool() == SketchTools.SELECT_BEZIER_TOOL)\n\t\t\t\t&& getSketchTools().getMouseButton() == SketchTools.MOUSE_LEFT) {\n\t\t\tselectNodes(mouseX, mouseY);\n\t\t}\n\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.SELECT_BEZIER_TOOL\n\t\t\t\t&& getSelectedShape() != null && getSelectedNodes().size() > 0\n\t\t\t\t&& getSelectedNodes().get(0) != null) {\n\n\t\t\tif (getSelectedNodes().size() > 0) {\n\t\t\t\tObject obj = (Object) getSelectedNodes().get(0);\n\t\t\t\tif (obj instanceof SketchPoint) {\n\t\t\t\t\tSketchPoint selectedVec = (SketchPoint) obj;\n\t\t\t\t\tif (!selectedVec.containsBezier()) {\n\t\t\t\t\t\n//\t\t\t\t\t\tgetSelectedShape().getPath().addBezier(\n//\t\t\t\t\t\t\t\t(SketchPoint) selectedVec, new Vec2D(selectedVec.x - 10,\n//\t\t\t\t\t\t\t\t\t\tselectedVec.y + 10), new Vec2D(\n//\t\t\t\t\t\t\t\t\t\tselectedVec.x + 10, selectedVec.y + 10));\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\n\t\tthis.unSelectAll();\n\n\t}\n\n\tpublic void mouseReleased(float mouseX, float mouseY) {\n\t\t\n\t\t\n\t\tLOGGER.debug(\"mouseReleased\" +getSketchTools().getMouseButton());\n\t\t\n\t\t//#IF JAVA\n\t\tif(GLOBAL.gui != null && GLOBAL.gui.overComponent())\n\t\t\treturn;\n\t\t//#ENDIF JAVA\n\t\t\n\t\t\n\t\t//LOGGER.info(\" mouseReeased\" + this.onSlicePlane.getId());\n\t\tsketchShapes.mouseReleased(mouseX, mouseY);\n\n\t\t//OFFSETPATH TOOL\n\t\t//___________________________________________________________________________________________________\n\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.DRAW_OFFSETPATH_TOOL) {\n\t\t\tboolean skip = false;\n\t\t\tVec2D pointOnPlan = new Vec2D(mouseX, mouseY);\n\n\t\t\tif (getCurrentShape() != null\n\t\t\t\t\t&& getCurrentShape().getType() == SketchShape.OFFSET_SPLINE\n\t\t\t\t\t&& getSketchTools().getMouseButton() == PConstants.RIGHT\n\t\t\t\t\t&& !getCurrentShape().getClosed() && !skip) {\n\t\t\t\tSketchSpline spline = (SketchSpline) getCurrentShape();\n\t\t\t\tspline.getCentrePath().remove(spline.getCentrePath().getLast());\n\t\t\t\tgetCurrentShape().setClosed(true);\n\t\t\t\tspline.offset();\n\t\t\t\tskip = true;\n\t\t\t}\n\n\t\t\tif (getCurrentShape() != null\n\t\t\t\t\t&& (getCurrentShape().getType() != SketchShape.OFFSET_SPLINE || getCurrentShape()\n\t\t\t\t\t\t\t.getClosed())\n\t\t\t\t\t&& getSketchTools().getMouseButton() == PConstants.LEFT\n\t\t\t\t\t&& !skip) {\n\n\t\t\t\tSketchSpline sketch = new SketchSpline(this);\n\t\t\t\tsketch.setType(SketchShape.OFFSET_SPLINE);\n\t\t\t\tsketch.autoSmooth = false;\n\t\t\t\tsketch.setOffsetSize(this.getSketchTools().brush_dia);\n\t\t\t\tsketch.setJoinType(SketchSpline.JOIN_ROUND);\n\t\t\t\tsketch.setCap(getSketchTools().getCurrentCapType());\n\t\t\t\tadd(sketch);\n\n\t\t\t}\n\n\t\t\tif (getCurrentShape() == null\n\t\t\t\t\t&& getSketchTools().getMouseButton() == PConstants.LEFT\n\t\t\t\t\t&& !skip) {\n\n\t\t\t\tSketchSpline sketch = new SketchSpline(this);\n\t\t\t\tsketch.setType(SketchShape.OFFSET_SPLINE);\n\t\t\t\tsketch.autoSmooth = false;\n\t\t\t\tsketch.setJoinType(SketchSpline.JOIN_ROUND);\n\t\t\t\tsketch.setOffsetSize(this.getSketchTools().brush_dia);\n\t\t\t\tsketch.setCap(getSketchTools().getCurrentCapType());\n\t\t\t\tadd(sketch);\n\t\t\t}\n\n\t\t\t//add a point\n\t\t\tif (getCurrentShape() != null\n\t\t\t\t\t&& getCurrentShape().getType() == SketchShape.OFFSET_SPLINE\n\t\t\t\t\t&& getSketchTools().getMouseButton() == PConstants.LEFT\n\t\t\t\t\t&& !skip) {\n\n\t\t\t\tgetCurrentShape().add(\n\t\t\t\t\t\tnew SketchPoint(pointOnPlan.x, pointOnPlan.y));\n\t\t\t\tgetCurrentShape().add(\n\t\t\t\t\t\tnew SketchPoint(pointOnPlan.x + 10, pointOnPlan.y + 1));\n\t\t\t}\n\n\t\t}\n\n\t\t\n\n\t\t\n\t\t\n\t\t//PATH TOOL\n\t\t//___________________________________________________________________________________________________\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.DRAW_PATH_TOOL) {\n\n\t\t\tboolean skip = false;\n\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t//Remove vertex!\n\t\t\tif (!skip && (getSketchTools().getMouseButton() == PConstants.LEFT|| getSketchTools().getMouseButton() == PConstants.RIGHT)\n\t\t\t\t\t&& getSketchTools().keyPressed\n\t\t\t\t\t&& getSketchTools().keyCode == PConstants.CONTROL) {\n\n\t\t\t\tVec2D pointOnPlane = new Vec2D(mouseX, mouseY);\n\n\t\t\t\tSketchPoint pathVert = getClosestPathVertex(pointOnPlane);\n\t\t\n\t\t\t\tif (pathVert != null && pointOnPlane.distanceTo(pathVert) < SETTINGS_SKETCH.select_dia) {\n\t\t\t\t\tremoveVertex(pathVert);\n\t\t\t\t\tskip = true;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t//check to see if we are adding a new point to an existing path\n\t\t\tif (!skip && (getSketchTools().getMouseButton() == PConstants.LEFT || getSketchTools().getMouseButton() == PConstants.RIGHT)\n\t\t\t\t\t&& getSketchTools().keyPressed\n\t\t\t\t\t&& getSketchTools().keyCode == PConstants.CONTROL) {\n\n\t\t\t\tVec2D pointOnPlane = new Vec2D(mouseX, mouseY);\n\n\t\t\t\tif (addPointAlongPath(pointOnPlane.x, pointOnPlane.y))\n\t\t\t\t\tskip = true;\n\n\t\t\t}\n\n\n\t\t\t\tVec2D pointOnPlan = new Vec2D(mouseX, mouseY);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t/*\n\t\t\t\tif (getSketchTools().getMouseButton() == PConstants.RIGHT && !skip) {\n\n\t\t\t\t\tSketchPoint pathVert = getClosestPathVertex(pointOnPlan);\n\n\t\t\t\t\t\n\t\t\t\t\tif (pathVert != null\n\t\t\t\t\t\t\t&& pointOnPlan.distanceTo(pathVert) < SETTINGS_SKETCH.select_dia) {\n\t\t\t\t\t\tremoveVertex(pathVert);\n\t\t\t\t\t\tskip = true;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t*/\n\n\t\t\t\tif (getCurrentShape() != null\n\t\t\t\t\t\t&& getCurrentShape().getType() == SketchShape.TYPE_PATH\n\t\t\t\t\t\t&& getSketchTools().getMouseButton() == PConstants.LEFT\n\t\t\t\t\t\t&& !skip) {\n\n\t\t\t\t\tSketchPath sketchP = (SketchPath) getCurrentShape();\n\t\t\t\t\tif (sketchP.getClosed()) {\n\n\t\t\t\t\t\tSketchPath sketch = new SketchPath(this);\n\t\t\t\t\t\tsketch.setType(SketchShape.TYPE_PATH);\n\t\t\t\t\t\tadd(sketch);\n\t\t\t\t\t\tgetCurrentShape().add(\n\t\t\t\t\t\t\t\tnew SketchPoint(pointOnPlan.x, pointOnPlan.y));\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (getCurrentShape() == null\n\t\t\t\t\t\t|| getCurrentShape().getType() != SketchShape.TYPE_PATH\n\t\t\t\t\t\t&& getSketchTools().getMouseButton() == PConstants.LEFT\n\t\t\t\t\t\t&& !skip) {\n\n\t\t\t\t\tSketchPath sketch = new SketchPath(this);\n\t\t\t\t\tsketch.setType(SketchShape.TYPE_PATH);\n\t\t\t\t\tsketch.setClosed(false);\n\t\t\t\t\tadd(sketch);\n\t\t\t\t\tgetCurrentShape().add(\n\t\t\t\t\t\t\tnew SketchPoint(pointOnPlan.x, pointOnPlan.y));\n\n\t\t\t\t}\n\n\t\t\t\tif (getCurrentShape().getType() == SketchShape.TYPE_PATH\n\t\t\t\t\t\t&& getSketchTools().getMouseButton() == PConstants.LEFT\n\t\t\t\t\t\t&& !skip) {\n\n\t\t\t\t\tif (getCurrentShape().getLength() > 2) {\n\n\t\t\t\t\t\tVec2D firstPoint = (Vec2D) ((SketchPath) getCurrentShape())\n\t\t\t\t\t\t\t\t.get(0);\n\t\t\t\t\t\tVec2D mousePos = new Vec2D(mouseX, mouseY);\n\t\t\t\t\t\t\n\t\t\t\t\t\t//mousePos = GLOBAL.uiTools.getPointOnPlane(mousePos, getCurrentShape().getParentSketch().getOnSketchPlane().getPlane());\n\t\t\t\t\t\tif (firstPoint.distanceTo(mousePos) < SETTINGS_SKETCH.MIN_CLOSE_SHAPE_DIST) {\n\t\t\t\t\t\t\tSketchPath path = (SketchPath) getCurrentShape();\n\t\t\t\t\t\t\tpath.remove(path.getLast());\n\t\t\t\t\t\t\t((SketchPath) getCurrentShape()).setClosed(true);\n\n\t\t\t\t\t\t\tskip = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//add a point\n\t\t\t\tif ((getCurrentShape().getType() == SketchShape.TYPE_PATH || getCurrentShape()\n\t\t\t\t\t\t.getType() == SketchShape.TYPE_SPLINE)\n\t\t\t\t\t\t&& getSketchTools().getMouseButton() == PConstants.LEFT\n\t\t\t\t\t\t&& !skip) {\n\n\t\t\t\t\tgetCurrentShape().add(\n\t\t\t\t\t\t\tnew SketchPoint(pointOnPlan.x, pointOnPlan.y));\n\t\t\t\t\t//getCurrentShape().add(new SketchPoint(0, 0));\n\n\t\t\t\t}\n\n\t\t\t\tif (getCurrentShape().getType() == SketchShape.TYPE_PATH\n\t\t\t\t\t\t&& getSketchTools().getMouseButton() == PConstants.RIGHT\n\t\t\t\t\t\t&& !getCurrentShape().getClosed() && !skip) {\n\n\t\t\t\t\tSketchPath path = (SketchPath) getCurrentShape();\n\t\t\t\t\tpath.remove(path.getLast());\n\t\t\t\t\tpath.setClosed(true);\n\t\t\t\t}\n\n\t\t\t\n\t\t}\n\n\t\t//#IF JAVA\n\t\tbuildOutline();\n\t\t//#ENDIF JAVA\n\n\t}\n\t\n\t\n\tpublic void mouseDoubleClick(float x, float y) {\n\t\t\n\t\tLOGGER.debug(\"double Click\");\n\t\t\n\t\t\n\t\tif(this.sketchTools.getCurrentTool() == SketchTools.SELECT_TOOL)\n\t\tthis.selectShape(x, y)\t;\n\t\t\n\t\t\n\t\t\n\t\t//OFFSETPATH TOOL\n\t\t//___________________________________________________________________________________________________\n\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.DRAW_OFFSETPATH_TOOL) {\n\t\t\tboolean skip = false;\n\n\t\t\t\n\t\t\tif (getCurrentShape() != null\n\t\t\t\t\t&& getCurrentShape().getType() == SketchShape.OFFSET_SPLINE\n\t\t\t\t\t&& !getCurrentShape().getClosed() && !skip) {\n\t\t\t\tSketchSpline spline = (SketchSpline) getCurrentShape();\n\t\t\t\tspline.getCentrePath().remove(spline.getCentrePath().getLast());\n\t\t\t\tgetCurrentShape().setClosed(true);\n\t\t\t\tspline.offset();\n\t\t\t\tskip = true;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.DRAW_PATH_TOOL) {\n\t\tif (getCurrentShape().getType() == SketchShape.TYPE_PATH\n\t\t\t\t&& getSketchTools().getMouseButton() == PConstants.LEFT\n\t\t\t\t&& !getCurrentShape().getClosed()) {\n\t\t\tSketchPath path = (SketchPath) getCurrentShape();\n\t\t\tpath.remove(path.getLast());\n\t\t\tpath.remove(path.getLast());\n\t\t\tpath.setClosed(true);\n\t\t}}}\n\n\tpublic int numerOfShapes() {\n\t\t// TODO Auto-generated method stub\n\t\treturn getSketchShapes().l.size();\n\t}\n\n\tpublic void optimize() {\n\t\tsketchShapes.optimize();\n\t}\n\n\tpublic boolean overSelectPoint(float mouseX, float mouseY) {\n\t\treturn sketchShapes.overSelectPoint(mouseX, mouseY);\n\t}\n\n\tpublic void removeLast() {\n\t\tsketchShapes.removeLast();\n\t}\n\n\tpublic void removeVertex(SketchPoint v) {\n\t\tsketchShapes.removeVertex(v);\n\t}\n\n\tpublic void render(PGraphics g) {\n\t\t\n\t\n\t\t\n\t\tswitch(getRenderMode()){\n\t\tcase Sketch.RENDER_3D_PREVIW:\n\t\t\tsketchShapes.sketchOutlines.render(g);\n\t\t\tsketchShapes.render(g);\n\n\t\tbreak;\n\t\t\t\n\t\tcase Sketch.RENDER_3D_EDITING_PLANES:\n\t\t\tif (getLayerSelected() == true){\n\t\t\t\tif(!sketchGlobals.mousePressed)\n\t\t\t\tsketchShapes.sketchOutlines.render(g);\n\t\t\t\t\n\t\t\t\tgetSlots().render(g);\n\t\t\t\tsketchShapes.render(g);\n\n\t\t\t}else{\n\t\t\t\tsketchShapes.sketchOutlines.render(g);\n\t\t\t\tsketchShapes.render(g);\n\n\t\t\t}\n\t\tbreak;\n\t\t\t\n\t\tcase Sketch.RENDER_3D_DIAGRAM:\n\t\t\tsketchShapes.sketchOutlines.render(g);\n\t\t\tsketchShapes.render(g);\n\t\t\t\n\t\t\t\n\t\t\tfloat extrudeDepth = getOnSketchPlane().thickness / 2;\n\t\t\textrudeDepth /= SETTINGS_SKETCH.scale;\n\t\t\t\n\t\t\tg.stroke(SETTINGS_SKETCH.SKETCHSHAPE_PATH_COLOUR_UNSELECTED);\n\t\t\tg.strokeWeight(SETTINGS_SKETCH.SKETCHSLOTEDGE_PATH_WEIGHT_DIAGRAM);\n\t\t\t\n\t\t\tg.pushMatrix();\n\t\t\tg.translate(0, 0, extrudeDepth+SETTINGS_SKETCH.OUTLINE_RENDER_OFFSET );\n\t\t\tgetSlots().renderEdge(g);\n\t\t\tg.popMatrix();\n\n\t\t\tg.pushMatrix();\n\t\t\tg.translate(0, 0, -(extrudeDepth+SETTINGS_SKETCH.OUTLINE_RENDER_OFFSET ));\n\t\t\tgetSlots().renderEdge(g);\n\t\t\tg.popMatrix();\n\t\t\t\n\t\t\tgetSlots().renderEdge(g);\n\n\t\tbreak;\n\t\t\n\t\t\n\t\tcase Sketch.RENDER_3D_NORMAL:\n\t\t\tsketchShapes.sketchOutlines.render(g);\n\t\t\tsketchShapes.render(g);\n\n\t\tbreak;\n\t\t\n\t\t\n\t\t}\n\t\t\n\n\t}\n\n\tpublic void renderOutline(PGraphics g) {\n\t\tsketchShapes.renderOutline(g);\n\n\t}\n\n\tpublic void renderPickBuffer(PGraphics g) {\n\t\tsketchShapes.renderPickBuffer(g);\n\t}\n\n\tpublic void renderSide(PGraphics g) {\n\t\tsketchShapes.renderSide(g);\n\n\t}\n\n\tpublic void renderSilhouette(PGraphics g) {\n\t\tsketchShapes.renderSilhouette(g);\n\t}\n\n\tpublic void scale(float scale, toxi.geom.Vec3D centre) {\n\t\tsketchShapes.scale(scale, centre);\n\t}\n\n\tpublic void select() {\n\t\tthis.selected = true;\n\t}\n\n\tpublic void selectNodes(float x, float y) {\n\t\tsketchShapes.selectNodes(x, y);\n\t}\n\n\tpublic void selectShape(float x, float y) {\n\t\tsketchShapes.selectShape(x, y);\n\t}\n\n\tpublic void setBrushCap(int cap) {\n\t\tSketchShape sketch = getSketchShapes().selectedShape;\n\n\t\tif (sketch instanceof SketchSpline) {\n\t\t\tSketchSpline spline = (SketchSpline) sketch;\n\t\t\tspline.setCap(cap);\n\t\t\tspline.offset();\n\t\t}\n\n\t}\n\n\tpublic void setBrushDia(float val) {\n\t\tSketchShape sketch = getSketchShapes().selectedShape;\n\n\t\tif (sketch instanceof SketchSpline) {\n\t\t\tSketchSpline spline = (SketchSpline) sketch;\n\t\t\tspline.setOffsetSize(val);\n\t\t}\n\n\t\tfor (int i = 0; i < this.getSketchShapes().l.size(); i++) {\n\t\t\tSketchShape s = this.getSketchShapes().l.get(i);\n\t\t\tif (s instanceof SketchSpline) {\n\t\t\t\tSketchSpline spline = (SketchSpline) s;\n\t\t\t\tspline.setOffsetSizeCentre(val);\n\t\t\t\tspline.offset();\n\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void setCurrentShape(SketchShape newSketch) {\n\t\tgetSketchShapes().currentShape = newSketch;\n\n\t}\n\n\tpublic void setEditing(boolean e) {\n\t\tsketchShapes.editing = e;\n\t}\n\n\tpublic void setLayerSelected(boolean selected) {\n\t\tthis.layerSelected = selected;\n\t}\n\n\tpublic void setOnSketchPlane(SlicePlane slicePlane) {\n\t\tsetOnSlicePlane(slicePlane);\n\t}\n\n\t/**\n\t * @param onSlicePlane the onSlicePlane to set\n\t */\n\tpublic void setOnSlicePlane(SlicePlane sp) {\n\t\tonSlicePlane = sp;\n\t}\n\n\tpublic void setRenderMode(int mode) {\n\t\tthis.renderMode = mode;\n\t}\n\n\tpublic void setSketchGlobals(SketchGlobals sGlobals) {\n\t\tsketchGlobals = sGlobals;\n\t}\n\n\tpublic void setSketchTools(SketchTools sTools) {\n\t\tsketchTools = sTools;\n\t}\n\n\n\tpublic void setSlots(SliceSlots slots) {\n\t\tsketchShapes.setSlots(slots);\n\t}\n\n\tpublic Vec2D setVec2DpickBuffer(int col, SketchPoint selectedVec,\n\t\t\tSketchShape selectedShape, SlicePlane selectedVecPlane,\n\t\t\tboolean isSelectedVecOnOutline) {\n\t\treturn sketchShapes.setVec2DpickBuffer(col, selectedVec, selectedShape,\n\t\t\t\tselectedVecPlane, isSelectedVecOnOutline);\n\n\t}\n\n\tpublic void toggleUnion() {\n\t\tSketchShape sketch = getSketchShapes().selectedShape;\n\n\t\tif (sketch.union == SketchShape.UNION_ADD)\n\t\t\tsketch.union = SketchShape.UNION_SUBTRACT;\n\t\telse\n\t\t\tsketch.union = SketchShape.UNION_ADD;\n\n\t}\n\n\tpublic Element toXML() {\n\t\treturn sketchShapes.toXML();\n\t}\n\n\tpublic void unselect() {\n\t\tthis.selected = false;\n//\t\tsketchShapes.unSelectAll();\n\n\t}\n\n\tpublic void unSelectAll() {\n\t\tsketchShapes.unSelectAll();\n\t}\n\n\tpublic void update() {\n\t\t//buildOutline();\n\t\t//sketchShapes.update();\n\n\t\tVec2D pointOnPlan = new Vec2D(getSketchTools().mouseX,\n\t\t\t\tgetSketchTools().mouseY);\n\n\t\t//#IF JAVA\n\t\tif (getOnSketchPlane() != null)\n\t\t\tpointOnPlan = GLOBAL.uiTools.getPointOnPlane(pointOnPlan,\n\t\t\t\t\tgetOnSketchPlane().getPlane());\n\t\t//#ENDIF JAVA\n\t\t\n\t\t//OFFSETPATH TOOL\n\t\t// Update paths position to show under mouse\n\t\t//___________________________________________________________________________________________________\n\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.DRAW_OFFSETPATH_TOOL) {\n\t\t\tboolean skip = false;\n\n\t\t\tif (getCurrentShape() != null\n\t\t\t\t\t&& getCurrentShape().getType() == SketchShape.OFFSET_SPLINE\n\t\t\t\t\t&& !getCurrentShape().getClosed() && !skip) {\n\t\t\t\tSketchSpline spline = (SketchSpline) getCurrentShape();\n\t\t\t\tspline.getCentrePath().getLast().set(pointOnPlan);\n\t\t\t\tspline.offset();\n\t\t\t}\n\t\t}\n\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.DRAW_PATH_TOOL) {\n\n\t\t\t\n\t\t\tthis.getSketchTools().drawPathToolState = SketchTools.DRAW_PATH_TOOL_STATE_NORMAL;\n\n\t\t\t\n\t\t\tif(getSketchTools().keyPressed\n\t\t\t&& getSketchTools().keyCode == PConstants.CONTROL) {\n\t\t\t\t\n\t\t\t\tthis.getSketchTools().drawPathToolState = SketchTools.DRAW_PATH_TOOL_STATE_ADD;\n\t\t\t\t \n\t\t\t\t\n\t\t\t\tif(pointOnPlan.distanceTo(sketchShapes.getClosestPathVertex(pointOnPlan)) < SETTINGS_SKETCH.select_dia){\n\t\t\t\t\tthis.getSketchTools().drawPathToolState = SketchTools.DRAW_PATH_TOOL_STATE_REMOVE;\n\n\t\t\t\t}\n\t\t\t\t\n\n\t\t//if (addPointAlongPath(pointOnPlane.x, pointOnPlane.y))\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tif (getCurrentShape() != null\n\t\t\t\t\t&& getCurrentShape().getType() == SketchShape.TYPE_PATH\n\t\t\t\t\t&& !getCurrentShape().getClosed()) {\n\t\t\t\tSketchPath path = (SketchPath) getCurrentShape();\n\t\t\t\tpath.getLast().set(pointOnPlan);\n\t\t\t\t\n\t\t\t\t\n\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t//SHOULD WE SHOW THE CONNECT CURSOR?\n\t\t\t\t\n\t\t\t\tif(path.size() > 2 && path.getLast().distanceTo(path.getFirst()) < 10)\n\t\t\t\t\tthis.getSketchTools().drawPathToolState = SketchTools.DRAW_PATH_TOOL_STATE_CONNECT;\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t\t//close paths if another tool is selected\n\t\t//close shape if tool is not selected! \n\t\tif (getSketchTools().getCurrentTool() != SketchTools.DRAW_OFFSETPATH_TOOL\n\t\t\t\t&& getCurrentShape() != null\n\t\t\t\t&& getCurrentShape().getType() == SketchShape.OFFSET_SPLINE\n\t\t\t\t&& !getCurrentShape().getClosed()) {\n\t\t\tSketchSpline spline = (SketchSpline) getCurrentShape();\n\t\t\tspline.getCentrePath().remove(spline.getCentrePath().getLast());\n\t\t\tgetCurrentShape().setClosed(true);\n\t\t\tspline.offset();\n\t\t}\n\n\t\tif (getSketchTools().getCurrentTool() != SketchTools.DRAW_PATH_TOOL\n\t\t\t\t&& getCurrentShape() != null\n\t\t\t\t&& getCurrentShape().getType() == SketchShape.TYPE_PATH\n\t\t\t\t&& !getCurrentShape().getClosed()) {\n\t\t\tSketchPath path = (SketchPath) getCurrentShape();\n\t\t\tpath.remove(path.getLast());\n\t\t\tgetCurrentShape().setClosed(true);\n\t\t\t//spline.offset();\n\t\t}\n\t\t\n\t\t//highlight over point\n\t\tif (getSketchTools().getCurrentTool() == SketchTools.SELECT_TOOL){\n\t\tSketchPoint p = this.getOverSelectPoint(pointOnPlan.x, pointOnPlan.y);\n\t\tif (p != null) {\n\t\t\tp.isOver = true;\n\t\t}\n\t\t}\n\n\t}\n\n\tpublic void removeLegs() {\n\t\tthis.sketchShapes.removeLegs();\n\t}\n\n\tpublic void importSVG(String path) {\n\t\tURI fileUri = null;\n\t\ttry {\n\t\t\tfileUri = new URI(\"file://\"+path);\n\t\t} catch (URISyntaxException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t SVGDiagram diagram = SVGCache.getSVGUniverse().getDiagram(fileUri);\n\t \n\t \n\t \n\t //diagram.getRoot().getChild(1);\n\t for(int i = 0; i < diagram.getRoot().getNumChildren();i++){\n\t \t\n\t \tSVGElement element = diagram.getRoot().getChild(i);\n\t //SVGElement element = diagram.getElement(\"shape_01\");\n\t if(element != null){\n\t List vector = element.getPath(null);\n\t com.kitfox.svg.Path pathSVG = (com.kitfox.svg.Path) vector.get(1); \n\t Shape shape = pathSVG.getShape();\n\t this.sketchShapes.buildPathsFromAWTShape(shape);\n\t }\n\t }\n\t // element.\n\t \n\t // }\n\t //LOGGER.info(diagram.get)\n\t /*\n\t SVGElement element = diagram.getElement(pathName); \n\t List vector = element.getPath(null); \n\t // get the AWT Shape \n\t // iterate over the shape using a path iterator discretizing with distance 0.001 units \n\t PathIterator pathIterator = shape.getPathIterator(null, 0.001d); \n\t float[] coords = new float[2]; \n\t while (!pathIterator.isDone()) { \n\t pathIterator.currentSegment(coords); \n\t points.add(new Vector2f(coords[0], coords[1])); \n\t pathIterator.next(); \n\t \n\t } \n\t */ \t\t\n\t}\n\n\tpublic void setEditable(boolean editable) {\n\t\tsketchShapes.setEditable(editable);\t\n\t}\n\n\tpublic void setRender3D(boolean b) {\n\t\tthis.render3D = b;\t\t\n\t}\n\tpublic boolean getRender3D() {\n\t\treturn this.render3D;\t\t\n\t}\n\n\tpublic void unselectShapes() {\n\t\tsketchShapes.unSelectAll();\t\n\t}\n\n\t\n\n\t\n\n}", "public class CraftRoboWriter extends HPGLWriter {\n\n\tpublic CraftRoboWriter(String location) {\n\t\tsuper(location);\n\t}\n\n\t@Override\n\tpublic void bezier(float x1, float y1, float cx1, float cy1, float cx2,\n\t\t\tfloat cy2, float x2, float y2) {\n\n\t\tx1 = getTranslatedX(x1);\n\t\ty1 = getTranslatedY(y1);\n\n\t\tcx1 = getTranslatedX(cx1);\n\t\tcy1 = getTranslatedY(cy1);\n\n\t\tcx2 = getTranslatedX(cx2);\n\t\tcy2 = getTranslatedY(cy2);\n\n\t\tx2 = getTranslatedX(x2);\n\t\ty2 = getTranslatedY(y2);\n\n\t\ttry {\n\t\t\tout.write(\"BZ1,\" + Float.toString(y1) + \",\" + Float.toString(x1)\n\t\t\t\t\t+ \",\" + Float.toString(cy1) + \",\" + Float.toString(cx1)\n\t\t\t\t\t+ \",\" + Float.toString(cy2) + \",\" + \",\"\n\t\t\t\t\t+ Float.toString(cx2) + \",\" + Float.toString(y2) + \",\"\n\t\t\t\t\t+ \",\" + Float.toString(x2) + \",\");\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\t//BZ1,1577,522,1675,522,1755,442,1755,344,\n\n\t}\n\n\t@Override\n\tpublic void lineTo(float x, float y) {\n\t\tx = getTranslatedX(x);\n\t\ty = getTranslatedY(y);\n\n\t\ttry {\n\t\t\tout.write(\"D\" + Float.toString(y) + \",\" + Float.toString(x) + \",\");\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void move(float x, float y) {\n\n\t\tx = getTranslatedX(x);\n\t\ty = getTranslatedY(y);\n\n\t\ttry {\n\t\t\tout.write(\"M\" + Float.toString(y) + \",\" + Float.toString(x) + \",\");\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n\tpublic void nextPage() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t//Set pen force from 0 - 30\n\t@Override\n\tpublic void setPenForce(int strength) {\n\n\t\ttry {\n\t\t\tout.write(\"FX\" + strength + \",\");\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setupDefault() {\n\t\t// setup default settings for the craft robo\n\t\ttry {\n\t\t\tthis.out.write(\"FN0,&100,100,100,^0,0,\\\\0,0,L0,!110,\");\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n}", "public class DXFWriter extends HPGLWriter {\n\t/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */\n\n\t/*\n\t * RawDXF - Code to write DXF files with beginRaw/endRaw\n\t * An extension for the Processing project - http://processing.org\n\t * <p/>\n\t * This library is free software; you can redistribute it and/or\n\t * modify it under the terms of the GNU Lesser General Public\n\t * License as published by the Free Software Foundation; either\n\t * version 2.1 of the License, or (at your option) any later version.\n\t * <p/>\n\t * This library is distributed in the hope that it will be useful,\n\t * but WITHOUT ANY WARRANTY; without even the implied warranty of\n\t * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\t * Lesser General Public License for more details.\n\t * <p/>\n\t * You should have received a copy of the GNU Lesser General\n\t * Public License along with the Processing project; if not,\n\t * write to the Free Software Foundation, Inc., 59 Temple Place,\n\t * Suite 330, Boston, MA 02111-1307 USA\n\t */\n\n\t/**\n\t * A simple library to write DXF files with Processing.\n\t * Because this is used with beginRaw() and endRaw(), only individual\n\t * triangles and (discontinuous) line segments will be written to the file.\n\t * <P/>\n\t * Use something like a keyPressed() in PApplet to trigger it,\n\t * to avoid writing a bazillion .dxf files.\n\t * <P/>\n\t * Usually, the file will be saved to the sketch's folder.\n\t * Use Sketch &rarr; Show Sketch Folder to see it from the PDE.\n\t * <p/>\n\t * A simple example of how to use:\n\t * <PRE>\n\t * import processing.dxf.*;\n\t *\n\t * boolean record;\n\t *\n\t * void setup() {\n\t * size(500, 500, P3D);\n\t * }\n\t *\n\t * void keyPressed() {\n\t * // use a key press so that it doesn't make a million files\n\t * if (key == 'r') record = true;\n\t * }\n\t *\n\t * void draw() {\n\t * if (record) {\n\t * beginRaw(DXF, \"output.dxf\");\n\t * }\n\t *\n\t * // do all your drawing here\n\t *\n\t * if (record) {\n\t * endRaw();\n\t * record = false;\n\t * }\n\t * }\n\t * </PRE>\n\t * or to use it and be able to control the current layer:\n\t * <PRE>\n\t * import processing.dxf.*;\n\t *\n\t * boolean record;\n\t * RawDXF dxf;\n\t *\n\t * void setup() {\n\t * size(500, 500, P3D);\n\t * }\n\t *\n\t * void keyPressed() {\n\t * // use a key press so that it doesn't make a million files\n\t * if (key == 'r') record = true;\n\t * }\n\t *\n\t * void draw() {\n\t * if (record) {\n\t * dxf = (RawDXF) createGraphics(width, height, DXF, \"output.dxf\");\n\t * beginRaw(dxf);\n\t * }\n\t *\n\t * // do all your drawing here, and to set the layer, call:\n\t * // if (record) {\n\t * // dxf.setLayer(num);\n\t * // }\n\t * // where 'num' is an integer.\n\t * // the default is zero, or you can set it to whatever.\n\t *\n\t * if (record) {\n\t * endRaw();\n\t * record = false;\n\t * dxf = null;\n\t * }\n\t * }\n\t * </PRE>\n\t * Note that even though this class is a subclass of PGraphics, it only\n\t * implements the parts of the API that are necessary for beginRaw/endRaw.\n\t * <P/>\n\t * Based on the original DXF writer from Simon Greenwold, February 2004.\n\t * Updated for Processing 0070 by Ben Fry in September 2004,\n\t * and again for Processing beta in April 2005.\n\t * Rewritten to support beginRaw/endRaw by Ben Fry in February 2006.\n\t * Updated again for inclusion as a core library in March 2006.\n\t * Constructor modifications in September 2008 as we approach 1.0.\n\t */\n\n\tFile file;\n\tPrintWriter writer;\n\tint currentLayer;\n\tprivate int vertexCount;\n\tprivate float prevX;\n\tprivate float prevY;\n\tprivate float prevZ;\n\tprivate float scale = 1;\n\n\tpublic DXFWriter(String path) {\n\t\tsuper(path);\n\n\t\tif (path != null) {\n\t\t\tfile = new File(path);\n\t\t\tif (!file.isAbsolute())\n\t\t\t\tfile = null;\n\t\t}\n\t\tif (file == null) {\n\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\"PGraphicsPDF requires an absolute path \"\n\t\t\t\t\t\t\t+ \"for the location of the output file.\");\n\t\t}\n\n\t\tif (writer == null) {\n\t\t\ttry {\n\t\t\t\twriter = new PrintWriter(new FileWriter(file));\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new RuntimeException(e); // java 1.4+\n\t\t\t}\n\t\t}\n\n\t\tallocate();\n\t\twriteHeader();\n\n\t}\n\n\t// ..............................................................\n\n\tprotected void allocate() {\n\t\t/*\n\t\tfor (int i = 0; i < MAX_TRI_LAYERS; i++) {\n\t\t layerList[i] = NO_LAYER;\n\t\t}\n\t\t*/\n\t\tsetLayer(0);\n\t}\n\n\t@Override\n\tpublic void bezier(float x1, float y1, float cx1, float cy1, float cx2,\n\t\t\tfloat cy2, float x2, float y2) {\n\n\t\tfor (float t = 0; t <= 1; t += 0.1f) {\n\t\t\tfloat x = functions.bezierPoint(x1, cx1, cx2, x2, t);\n\t\t\tfloat y = functions.bezierPoint(y1, cy1, cy2, y2, t);\n\t\t\tlineTo(x, y);\n\t\t}\n\n\t}\n\n\t// ..............................................................\n\n\tpublic void close() {\n\t\twriteFooter();\n\t\tdispose();\n\t}\n\n\t// ..............................................................\n\n\tpublic void dispose() {\n\t\twriteFooter();\n\n\t\twriter.flush();\n\t\twriter.close();\n\t\twriter = null;\n\t}\n\n\t@Override\n\tpublic void lineTo(float x, float y) {\n\t\tlineTo(x, y, 0);\n\t}\n\n\tpublic void lineTo(float x, float y, float z) {\n\n\t\twriteLine(prevX, prevY, prevZ, getTranslatedX(x), getTranslatedY(y), z\n\t\t\t\t* scale);\n\t\tprevX = getTranslatedX(x);\n\t\tprevY = getTranslatedY(y);\n\t\tprevZ = z * scale;\n\t}\n\n\t@Override\n\tpublic void move(float x, float y) {\n\t\tmove(x, y, 0);\n\t}\n\n\tpublic void move(float x, float y, float z) {\n\t\tprevX = getTranslatedX(x);\n\t\tprevY = getTranslatedY(y);\n\t\tprevZ = z * scale;\n\t}\n\n\t// ..............................................................\n\n\tpublic void nextPage() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t/**\n\t * Write a line to the dxf file. Available for anyone who wants to\n\t * insert additional commands into the DXF stream.\n\t */\n\tpublic void println(String what) {\n\t\twriter.println(what);\n\t}\n\n\t/**\n\t * Set the current layer being used in the DXF file.\n\t * The default is zero.\n\t */\n\tpublic void setLayer(int layer) {\n\t\tcurrentLayer = layer;\n\t}\n\n\t/**\n\t * Write a command on one line (as a String), then start a new line\n\t * and write out a formatted float. Available for anyone who wants to\n\t * insert additional commands into the DXF stream.\n\t */\n\tpublic void write(String cmd, float val) {\n\t\twriter.println(cmd);\n\t\t// don't format, will cause trouble on systems that aren't en-us\n\t\t// http://dev.processing.org/bugs/show_bug.cgi?id=495\n\t\twriter.println(val);\n\t}\n\n\tprivate void writeFooter() {\n\t\twriter.println(\"0\");\n\t\twriter.println(\"ENDSEC\");\n\t\twriter.println(\"0\");\n\t\twriter.println(\"EOF\");\n\t}\n\n\tprivate void writeHeader() {\n\t\twriter.println(\"0\");\n\t\twriter.println(\"SECTION\");\n\t\twriter.println(\"2\");\n\t\twriter.println(\"ENTITIES\");\n\t}\n\n\tprotected void writeLine(float x1, float y1, float z1, float x2, float y2,\n\t\t\tfloat z2) {\n\t\twriter.println(\"0\");\n\t\twriter.println(\"LINE\");\n\n\t\t// write out the layer\n\t\twriter.println(\"8\");\n\t\twriter.println(String.valueOf(currentLayer));\n\n\t\twrite(\"10\", x1);\n\t\twrite(\"20\", y1 * -1);\n\t\twrite(\"30\", z1);\n\n\t\twrite(\"11\", x2);\n\t\twrite(\"21\", y2 * -1);\n\t\twrite(\"31\", z2);\n\t}\n\n}" ]
import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import nu.xom.Attribute; import nu.xom.Document; import nu.xom.Element; import nu.xom.Serializer; import cc.sketchchair.core.GLOBAL; import cc.sketchchair.core.LOGGER; import cc.sketchchair.core.SETTINGS; import cc.sketchchair.functions.functions; import cc.sketchchair.sketch.Sketch; import ToolPathWriter.CraftRoboWriter; import ToolPathWriter.DXFWriter; import processing.core.PApplet; import processing.core.PConstants; import processing.core.PFont; import processing.core.PGraphics; import processing.pdf.PGraphicsPDF;
String[] cmd = {"/usr/bin/open", "-a" , "Cutting Master 2 for CraftROBO.app", "/Applications/Cutting Master 2 CraftROBO 1.86/Release/"}; p = rt.exec(cmd); }else{ craftRoboPath = "C:/Program Files/Cutting Master 2 for CraftROBO 1.60/Program/App2.exe"; p = rt.exec(craftRoboPath); } LOGGER.info("Running: " + craftRoboPath); // in = p.getInputStream(); if (in.available() > 0) System.out.println(in.toString()); out = p.getOutputStream(); InputStream err = p.getErrorStream(); //p.destroy() ; } catch (Exception exc) {/*handle exception*/ } } public void setupFirstRender(PGraphics g){ ZOOM = ( (float)g.height/this.materialHeight); this.CAM_OFFSET_X = (int) -(this.materialWidth/2.0f); this.CAM_OFFSET_Y = (int) -(this.materialHeight/2.0f); } public void render(PGraphics g) { if(firstRender) setupFirstRender(g);//if this is the first time we have rendered then setup the correct postion on the screen if(ZOOM < minZoom) ZOOM = minZoom; if(ZOOM > maxZoom) ZOOM = maxZoom; if(CAM_OFFSET_X > maxCamX) CAM_OFFSET_X = maxCamX; if(CAM_OFFSET_X < minCamX) CAM_OFFSET_X = minCamX; if(CAM_OFFSET_Y > maxCamY) CAM_OFFSET_Y = maxCamY; if(CAM_OFFSET_Y < minCamY) CAM_OFFSET_Y = minCamY; firstRender = false; g.textSize(this.textSize); g.fill(0); g.noStroke(); g.pushMatrix(); g.translate(g.width/2, g.height/2); g.scale(this.ZOOM); g.translate(this.CAM_OFFSET_X, this.CAM_OFFSET_Y); this.pages.render(g); g.popMatrix(); } public void renderPickBuffer(PGraphics pickBuffer) { firstRender = false; pickBuffer.noFill(); pickBuffer.stroke(0); pickBuffer.pushMatrix(); pickBuffer.scale(this.ZOOM); pickBuffer.translate(this.CAM_OFFSET_X, this.CAM_OFFSET_Y); this.pages.renderPickBuffer(pickBuffer); pickBuffer.popMatrix(); } public void renderList(PGraphics g) { g.textSize(this.textSize); g.noFill(); g.stroke(0); g.pushMatrix(); this.pages.renderList(g); g.popMatrix(); } public void scaleAll(float scale) { this.shapes.scale(scale); } public void renderPickBufferList(PGraphics pickBuffer) { this.pages.renderPickBufferList(pickBuffer); } public void zoomView(float _zoomDelta, float _mouseX, float _mouseY){ float deltaMouseXBefore = (float) (((GLOBAL.applet.width/2)-_mouseX)/this.ZOOM); float deltaMouseYBefore = (float) (((GLOBAL.applet.height/2)-_mouseY)/this.ZOOM); this.ZOOM -= _zoomDelta;
if( (_zoomDelta > 0 && this.ZOOM < SETTINGS.MIN_ZOOM)){
2
setial/intellij-javadocs
src/main/java/com/github/setial/intellijjavadocs/action/JavaDocGenerateAction.java
[ "public class SetupTemplateException extends RuntimeException {\n\n /**\n * Instantiates a new Setup template exception.\n *\n * @param cause the cause\n */\n public SetupTemplateException(Throwable cause) {\n super(cause);\n }\n}", "public class TemplateNotFoundException extends RuntimeException {\n\n /**\n * Instantiates a new Template not found exception.\n *\n * @param message the message\n */\n public TemplateNotFoundException(String message) {\n super(message);\n }\n}", "public interface JavaDocGenerator<T extends PsiElement> {\n\n /**\n * Generate java docs.\n *\n * @param element the Element\n * @return the Psi doc comment\n */\n @Nullable\n PsiDocComment generate(@NotNull T element);\n\n}", "public class ClassJavaDocGenerator extends AbstractJavaDocGenerator<PsiClass> {\n\n /**\n * Instantiates a new Class java doc generator.\n *\n * @param project the Project\n */\n public ClassJavaDocGenerator(@NotNull Project project) {\n super(project);\n }\n\n @Nullable\n @Override\n protected JavaDoc generateJavaDoc(@NotNull PsiClass element) {\n JavaDocSettings configuration = getSettings().getConfiguration();\n if ((configuration != null && !configuration.getGeneralSettings().getLevels().contains(Level.TYPE)) ||\n !shouldGenerate(element.getModifierList())) {\n return null;\n }\n Template template = getDocTemplateManager().getClassTemplate(element);\n Map<String, Object> params = getDefaultParameters(element);\n if (!configuration.getGeneralSettings().isSplittedClassName()) {\n params.put(\"name\", element.getName());\n }\n String javaDocText = getDocTemplateProcessor().merge(template, params);\n return JavaDocUtils.toJavaDoc(javaDocText, getPsiElementFactory());\n }\n\n}", "public class FieldJavaDocGenerator extends AbstractJavaDocGenerator<PsiField> {\n\n /**\n * Instantiates a new Field java doc generator.\n *\n * @param project the Project\n */\n public FieldJavaDocGenerator(@NotNull Project project) {\n super(project);\n }\n\n @Nullable\n @Override\n protected JavaDoc generateJavaDoc(@NotNull PsiField element) {\n JavaDocSettings configuration = getSettings().getConfiguration();\n if (configuration != null && !configuration.getGeneralSettings().getLevels().contains(Level.FIELD) ||\n !shouldGenerate(element.getModifierList())) {\n return null;\n }\n Template template = getDocTemplateManager().getFieldTemplate(element);\n Map<String, Object> params = getDefaultParameters(element);\n PsiClass parent = findClassElement(element);\n if (parent != null) {\n params.put(\"typeName\", getDocTemplateProcessor().buildDescription(parent.getName(), false));\n }\n String javaDocText = getDocTemplateProcessor().merge(template, params);\n return JavaDocUtils.toJavaDoc(javaDocText, getPsiElementFactory());\n }\n\n private PsiClass findClassElement(PsiElement element) {\n PsiClass parentClass = null;\n if (element != null) {\n PsiElement parent = element.getParent();\n if (parent instanceof PsiClass) {\n parentClass = (PsiClass) parent;\n } else {\n parentClass = findClassElement(parent);\n }\n }\n return parentClass;\n }\n\n}", "public class MethodJavaDocGenerator extends AbstractJavaDocGenerator<PsiMethod> {\n\n /**\n * Instantiates a new Method java doc generator.\n *\n * @param project the Project\n */\n public MethodJavaDocGenerator(@NotNull Project project) {\n super(project);\n }\n\n @Nullable\n @Override\n protected JavaDoc generateJavaDoc(@NotNull PsiMethod element) {\n if (!shouldGenerate(element) || !shouldGenerate(element.getModifierList())) {\n return null;\n }\n Template template = getDocTemplateManager().getMethodTemplate(element);\n Map<String, String> paramNames = new HashMap<>();\n for (PsiParameter parameter : element.getParameterList().getParameters()) {\n paramNames.put(parameter.getName(), getDocTemplateProcessor().buildDescription(parameter.getName(), false));\n }\n Map<String, String> exceptionNames = new HashMap<>();\n for (PsiJavaCodeReferenceElement exception : element.getThrowsList().getReferenceElements()) {\n exceptionNames.put(exception.getReferenceName(),\n getDocTemplateProcessor().buildDescription(exception.getReferenceName(), false));\n }\n String returnDescription = StringUtils.EMPTY;\n PsiTypeElement returnElement = element.getReturnTypeElement();\n if (returnElement != null) {\n returnDescription = returnElement.getText();\n }\n Map<String, Object> params = getDefaultParameters(element);\n if (returnElement != null) {\n params.put(\"isNotVoid\", !returnElement.getType().isAssignableFrom(PsiType.VOID));\n params.put(\"return\", getDocTemplateProcessor().buildDescription(returnDescription, false));\n }\n params.put(\"paramNames\", paramNames);\n params.put(\"exceptionNames\", exceptionNames);\n params.put(\"fieldName\", getDocTemplateProcessor().buildFieldDescription(element.getName()));\n\n String javaDocText = getDocTemplateProcessor().merge(template, params);\n return JavaDocUtils.toJavaDoc(javaDocText, getPsiElementFactory());\n }\n\n private boolean shouldGenerate(@NotNull PsiMethod element) {\n PsiMethod[] superMethods = element.findSuperMethods();\n JavaDocSettings configuration = getSettings().getConfiguration();\n boolean result = configuration != null && configuration.getGeneralSettings().getLevels().contains(Level.METHOD);\n if (superMethods.length > 0) {\n boolean overriddenMethods = superMethods.length > 0 && configuration != null &&\n configuration.getGeneralSettings().isOverriddenMethods();\n result = result && overriddenMethods;\n }\n return result;\n }\n\n}", "public interface JavaDocWriter {\n\n /**\n * Write java doc.\n *\n * @param javaDoc the Java doc\n * @param beforeElement the element to place javadoc before it\n */\n void write(@NotNull PsiDocComment javaDoc, @NotNull PsiElement beforeElement);\n\n /**\n * Remove void.\n *\n * @param beforeElement the before element\n */\n void remove(@NotNull PsiElement beforeElement);\n\n}", "public static final String JAVADOCS_PLUGIN_TITLE_MSG = \"Javadocs plugin\";" ]
import com.github.setial.intellijjavadocs.exception.SetupTemplateException; import com.github.setial.intellijjavadocs.exception.TemplateNotFoundException; import com.github.setial.intellijjavadocs.generator.JavaDocGenerator; import com.github.setial.intellijjavadocs.generator.impl.ClassJavaDocGenerator; import com.github.setial.intellijjavadocs.generator.impl.FieldJavaDocGenerator; import com.github.setial.intellijjavadocs.generator.impl.MethodJavaDocGenerator; import com.github.setial.intellijjavadocs.operation.JavaDocWriter; import com.intellij.codeInsight.CodeInsightActionHandler; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiField; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiMethod; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilCore; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.text.MessageFormat; import java.util.LinkedList; import java.util.List; import static com.github.setial.intellijjavadocs.configuration.impl.JavaDocConfigurationImpl.JAVADOCS_PLUGIN_TITLE_MSG;
package com.github.setial.intellijjavadocs.action; /** * The type Java doc generate action. * * @author Sergey Timofiychuk */ public class JavaDocGenerateAction extends BaseAction { private static final Logger LOGGER = Logger.getInstance(JavaDocGenerateAction.class); private JavaDocWriter writer; /** * Instantiates a new Java doc generate action. */ public JavaDocGenerateAction() { this(new JavaDocHandler()); } /** * Instantiates a new Java doc generate action. * * @param handler the handler */ public JavaDocGenerateAction(CodeInsightActionHandler handler) { super(handler); writer = ServiceManager.getService(JavaDocWriter.class); } /** * Action performed. * * @param e the Event */ @Override public void actionPerformed(AnActionEvent e) { DumbService dumbService = DumbService.getInstance(e.getProject()); if (dumbService.isDumb()) { dumbService.showDumbModeNotification("Javadocs plugin is not available during indexing"); return; } Editor editor = CommonDataKeys.EDITOR.getData(e.getDataContext()); if (editor == null) { LOGGER.error("Cannot get com.intellij.openapi.editor.Editor");
Messages.showErrorDialog("Javadocs plugin is not available", JAVADOCS_PLUGIN_TITLE_MSG);
7
calibre2opds/calibre2opds
OpdsOutput/src/main/java/com/gmail/dpierron/calibre/opds/TagListSubCatalog.java
[ "public class Book extends GenericDataObject {\r\n private final static Logger logger = LogManager.getLogger(Book.class);\r\n\r\n private File bookFolder;\r\n private final String id;\r\n private final String uuid;\r\n private String title;\r\n private String titleSort;\r\n private final String path;\r\n private String comment;\r\n private String summary;\r\n private Integer summaryMaxLength;\r\n private final Float serieIndex;\r\n private final Date timestamp;\r\n private final Date modified;\r\n private final Date publicationDate;\r\n private final String isbn;\r\n private List<Author> authors;\r\n private String listOfAuthors;\r\n private String authorSort;\r\n private Publisher publisher;\r\n private Series series;\r\n private List<Tag> tags;\r\n private List<EBookFile> files;\r\n private EBookFile preferredFile;\r\n private EBookFile epubFile;\r\n private String epubFileName;\r\n private long latestFileModifiedDate = -1;\r\n private final BookRating rating;\r\n private List<Language> bookLanguages = new LinkedList<Language>();\r\n private List<CustomColumnValue> customColumnValues;\r\n private static Date ZERO;\r\n private static final Pattern tag_br = Pattern.compile(\"\\\\<br\\\\>\", Pattern.CASE_INSENSITIVE);\r\n protected Book copyOfBook; // If a book is copied then this points to the original\r\n\r\n // Flags\r\n // NOTE: Using byte plus bit settings is more memory efficient than using boolean types\r\n private final static byte FLAG_ALL_CLEAR = 0;\r\n private final static byte FLAG_DONE = 0x01; // Set when the Book full details have been generated\r\n private final static byte FLAG_REFERENCED = 0x02; // Set if book full details must be generated as referenced\r\n private final static byte FLAG_FILES_SORTED = 0x04;\r\n private final static byte FLAG_EPUBFILE_COMPUTED = 0x08;\r\n private final static byte FLAG_PREFERREDFILECOMPUTED = 0x10;\r\n private final static byte FLAG_CHANGED = 0x20;\r\n private final static byte FLAG_FLAGGED = 0x40;\r\n private byte flags = FLAG_ALL_CLEAR;\r\n\r\n static {\r\n Calendar c = Calendar.getInstance();\r\n c.setTimeInMillis(0);\r\n ZERO = c.getTime();\r\n }\r\n\r\n // CONSTRUCTORS\r\n\r\n public Book(String id,\r\n String uuid,\r\n String title,\r\n String title_sort,\r\n String path,\r\n Float serieIndex,\r\n Date timestamp,\r\n Date modified,\r\n Date publicationDate,\r\n String isbn,\r\n String authorSort,\r\n BookRating rating) {\r\n super();\r\n copyOfBook = null;\r\n this.id = id;\r\n this.uuid = uuid;\r\n\r\n if (title != null) {\r\n // Do some (possibly unnecessary) tidyong of title\r\n title = title.trim();\r\n this.title = title.substring(0, 1).toUpperCase() + title.substring(1);\r\n // title_sort is normally set by Calibre autoamtically, but it can be cleared\r\n // by users and may not be set by older versions of Calibre. In these\r\n // cases we fall back to using the (mandatory) title field and issue a warning\r\n if (Helper.isNullOrEmpty(title_sort)) {\r\n logger.warn(\"Title_Sort not set - using Title for book '\" + this.title + \"'\"); Helper.statsWarnings++;\r\n this.titleSort = DataModel.getNoiseword(getFirstBookLanguage()).removeLeadingNoiseWords(this.title);\r\n } else {\r\n this.titleSort = title_sort;\r\n }\r\n // Small memory optimisation to re-use title object if possible\r\n // TODO check if unecessary if Java does this automatically?\r\n if (this.title.equalsIgnoreCase(this.titleSort)) {\r\n this.titleSort = this.title;\r\n }\r\n }\r\n\r\n this.path = path;\r\n this.serieIndex = serieIndex;\r\n this.timestamp = timestamp;\r\n this.modified = modified;\r\n this.publicationDate = publicationDate;\r\n this.tags = new LinkedList<Tag>();\r\n this.files = new LinkedList<EBookFile>();\r\n this.authors = new LinkedList<Author>();\r\n this.isbn = isbn;\r\n this.authorSort = authorSort;\r\n this.rating = rating;\r\n\r\n }\r\n\r\n // METHODS and PROPERTIES implementing Abstract ones from Base class)\r\n\r\n /**\r\n * Method that gets the name for this 'data' type\r\n *\r\n * @return\r\n */\r\n public String getColumnName () {\r\n return \"book\";\r\n }\r\n\r\n public ColumType getColumnType() {\r\n return ColumType.COLUMN_BOOK;\r\n }\r\n\r\n public String getDisplayName() {\r\n return (copyOfBook == null) ? title : copyOfBook.getDisplayName();\r\n }\r\n\r\n public String getSortName() {\r\n return (copyOfBook == null) ? titleSort : copyOfBook.getSortName();\r\n }\r\n\r\n public String getTextToDisplay() {\r\n return DataModel.displayTitleSort ? getSortName() : getDisplayName() ;\r\n }\r\n\r\n public String getTextToSort() {\r\n return DataModel.librarySortTitle ? getDisplayName() : getSortName();\r\n }\r\n\r\n // METHODS and PROPERTIES\r\n\r\n /**\r\n * Helper routine to set flags bits state\r\n */\r\n private void setFlags (boolean b, int f) {\r\n if (b == true)\r\n flags |= f; // Set flag bits\r\n else\r\n flags &= ~f; // Clear flag bits;\r\n }\r\n\r\n /**\r\n * Helper routine to check if specified kags set\r\n * @param f\r\n * @return\r\n */\r\n private boolean isFlags( int f) {\r\n return ((flags & f) == f);\r\n }\r\n\r\n\r\n public String getId() {\r\n return (copyOfBook == null) ? id : copyOfBook.getId();\r\n }\r\n\r\n public String getUuid() {\r\n return (copyOfBook == null) ? uuid : copyOfBook.getUuid();\r\n }\r\n\r\n /**\r\n * Return the first listed language for a book\r\n * (this is on the assumption it is the most important one)\r\n * @return\r\n */\r\n public Language getFirstBookLanguage() {\r\n if (copyOfBook != null) return copyOfBook.getFirstBookLanguage();\r\n List<Language> languages = getBookLanguages();\r\n if ((languages == null) || (languages.size() == 0))\r\n return null;\r\n else\r\n return languages.get(0);\r\n }\r\n\r\n /**\r\n * Get all the languages for a book.\r\n * Most of the time there will only be one, but Ca;ibre\r\n * allows for multpiple languages on the same book.\r\n * @return\r\n */\r\n public List<Language> getBookLanguages() {\r\n return (copyOfBook == null) ? bookLanguages : copyOfBook.getBookLanguages();\r\n }\r\n\r\n /**\r\n * Add a language to the book.\r\n *\r\n * @param bookLanguage\r\n */\r\n public void addBookLanguage(Language bookLanguage) {\r\n assert copyOfBook == null; // Never expect this to be used on a copy of the book!\r\n if (getBookLanguages() == null) {\r\n bookLanguages = new LinkedList<Language>();\r\n }\r\n if (!bookLanguages.contains(bookLanguage)) {\r\n bookLanguages.add(bookLanguage);\r\n }\r\n }\r\n\r\n public String getIsbn() {\r\n return (copyOfBook == null) ? (isbn == null ? \"\" : isbn) : copyOfBook.getIsbn();\r\n }\r\n\r\n public String getPath() {\r\n return (copyOfBook == null) ? path : copyOfBook.getPath();\r\n }\r\n\r\n public String getComment() {\r\n return (copyOfBook == null) ? comment : copyOfBook.getComment();\r\n }\r\n\r\n /**\r\n * Remove leading text from the given XHTNL string. This is\r\n * used to remove words such as SUMMARY that we add ourselves\r\n * in the catalog. It is also used to remove other common\r\n * expressions from the Summary to try and leave text that is more\r\n * useful as a summary.\r\n *\r\n * Special processing requirements:\r\n * - Any leading HTML tags or spaces are ignored\r\n * - Any trailing ':' or spaces are removed\r\n * - If after removing the desired text there are\r\n * HTML tags that were purely surrounding the text\r\n * that has been removed, they are also removed.\r\n * @param text Text that is being worked on\r\n * @param leadingText String to be checked for (case ignored)\r\n * @return Result of removing text, or null if input was null\r\n */\r\n private String removeLeadingText (String text, String leadingText) {\r\n // Check for fast exit conditions\r\n if (Helper.isNullOrEmpty(text) || Helper.isNullOrEmpty(leadingText) )\r\n return text;\r\n int textLength = text.length();\r\n int leadingLength = leadingText.length();\r\n\r\n int cutStart = 0; // Start scanning from beginning of string\r\n int cutStartMax = textLength - leadingLength - 1 ;\r\n\r\n // skip over leading tags and spaces\r\n boolean scanning = true;\r\n while (scanning) {\r\n // Give up no room left to match text\r\n if (cutStart > cutStartMax)\r\n return text;\r\n // Look for special characters\r\n switch (text.charAt(cutStart)) {\r\n case ' ':\r\n cutStart++;\r\n break;\r\n case '<':\r\n // Look for end of tag\r\n int tagEnd = text.indexOf('>',cutStart);\r\n // If not found then give up But should this really occur)\r\n if (tagEnd == -1)\r\n return text;\r\n else\r\n cutStart = tagEnd + 1;\r\n break;\r\n default:\r\n scanning = false;\r\n break;\r\n }\r\n }\r\n\r\n // Exit if text does not match\r\n if (! text.substring(cutStart).toUpperCase(Locale.ENGLISH).startsWith(leadingText.toUpperCase(Locale.ENGLISH)))\r\n return text;\r\n // Set end of text to remove\r\n int cutEnd = cutStart + leadingLength;\r\n\r\n // After removing leading text, now remove any tags that are now empty of content\r\n // TODO - complete the logic here. Currently does not remove such empty tags\r\n scanning=true;\r\n while (scanning) {\r\n if (cutEnd >= textLength) {\r\n scanning = false;\r\n }\r\n else {\r\n switch (text.charAt(cutEnd)) {\r\n case ' ':\r\n case ':':\r\n cutEnd++;\r\n break;\r\n case '<':\r\n if (text.charAt(cutEnd+1) != '/'){\r\n // Handle case of BR tag following removed text\r\n if (text.substring(cutEnd).toUpperCase().startsWith(\"<BR\")) {\r\n int tagEnd = text.indexOf('>', cutEnd+1);\r\n if (tagEnd != -1) {\r\n cutEnd = tagEnd + 1;\r\n break;\r\n }\r\n }\r\n scanning = false;\r\n break;\r\n }\r\n else {\r\n int tagEnd = text.indexOf('>');\r\n if (tagEnd == -1) {\r\n scanning = false;\r\n break;\r\n }\r\n else {\r\n cutEnd = tagEnd + 1;\r\n }\r\n }\r\n break;\r\n default:\r\n scanning = false;\r\n break;\r\n } // End of switch\r\n }\r\n } // End of while\r\n\r\n if (cutStart > 0)\r\n return (text.substring(0, cutStart) + text.substring(cutEnd)).trim();\r\n else\r\n return text.substring(cutEnd).trim();\r\n }\r\n\r\n /**\r\n * Sets the comment value\r\n * If it starts with 'SUMMARY' then this is removed as superfluous\r\n * NOTE. Comments are allowed to contain (X)HTML) tags\r\n * @param value the new comment\r\n */\r\n public void setComment(String value) {\r\n assert copyOfBook == null; // Never expect this to be used on a copy\r\n summary = null;\r\n summaryMaxLength = -1;\r\n if (Helper.isNotNullOrEmpty(value)) {\r\n if (value.startsWith(\"<\")) {\r\n if (value.contains(\"<\\\\br\") || value.contains(\"<\\\\BR\")) {\r\n int dummy = 1;\r\n }\r\n // Remove newlines from HTML as they are meangless in that context\r\n value = value.replaceAll(\"\\\\n\",\"\");\r\n // Remove any empty paragraphs.\r\n value= value.replaceAll(\"<p></p>\",\"\");\r\n }\r\n comment = removeLeadingText(value, \"SUMMARY\");\r\n comment = removeLeadingText(comment, \"PRODUCT DESCRIPTION\");\r\n // The following log entry can be useful if trying to debug character encoding issues\r\n // logger.info(\"Book \" + id + \", setComment (Hex): \" + Database.stringToHex(comment));\r\n \r\n if (comment != null && comment.matches(\"(?i)<br>\")) {\r\n logger.warn(\"<br> tag in comment changed to <br /> for Book: Id=\" + id + \" Title=\" + title); Helper.statsWarnings++;\r\n comment.replaceAll(\"(?i)<br>\", \"<br />\");\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Get the book summary\r\n * This starts with any series information, and then as much of the book comment as\r\n * will fit in the space allowed.\r\n *\r\n * Special processing Requirements\r\n * - The word 'SUMMARY' is removed as superfluous at the start of the comment text\r\n * - The words 'PRODUCT DESCRIPTION' are removed as superfluous at the start of the comment text\r\n * - The calculated value is stored for later re-use (which is very likely to happen).\r\n * NOTE. Summary must be pure text (no (X)HTML tags) for OPDS compatibility\r\n * @param maxLength Maximum length of text allowed in summary\r\n * @return The value of the calculated summary field\r\n */\r\n public String getSummary(int maxLength) {\r\n if (copyOfBook != null) return copyOfBook.getSummary(maxLength);\r\n if (summary == null || maxLength != summaryMaxLength) {\r\n summary = \"\";\r\n summaryMaxLength = maxLength;\r\n // Check for series info to include\r\n if (Helper.isNotNullOrEmpty(getSeries())) {\r\n float seriesIndexFloat = getSerieIndex();\r\n if (seriesIndexFloat == 0 ) {\r\n // We do not add the index when it is zero\r\n summary += getSeries().getDisplayName() + \": \";\r\n } else {\r\n int seriesIndexInt = (int) seriesIndexFloat;\r\n String seriesIndexText;\r\n // For the commonest case of integers we want to truncate off the fractional part\r\n if (seriesIndexFloat == (float) seriesIndexInt)\r\n seriesIndexText = String.format(\"%d\", seriesIndexInt);\r\n else {\r\n // For fractions we want only 2 decimal places to match calibre\r\n seriesIndexText = String.format(\"%.2f\", seriesIndexFloat);\r\n }\r\n summary += getSeries().getDisplayName() + \" [\" + seriesIndexText + \"]: \";\r\n }\r\n if (maxLength != -1) {\r\n summary = Helper.shorten(summary, maxLength);\r\n }\r\n }\r\n // See if still space for comment info\r\n // allow for special case of -1 which means no limit.\r\n if (maxLength == -1 || (maxLength > (summary.length() + 3))) {\r\n String noHtml = Helper.removeHtmlElements(getComment());\r\n if (noHtml != null) {\r\n noHtml = removeLeadingText(noHtml, \"SUMMARY\");\r\n noHtml = removeLeadingText(noHtml, \"PRODUCT DESCRIPTION\");\r\n if (maxLength == -1 ) {\r\n summary += noHtml;\r\n } else {\r\n summary += Helper.shorten(noHtml, maxLength - summary.length());\r\n }\r\n }\r\n }\r\n }\r\n return summary;\r\n }\r\n\r\n /**&\r\n * Get the series index.\r\n * It is thought that Calibre always sets this but it is better to play safe!\r\n * @return\r\n */\r\n public Float getSerieIndex() {\r\n if (copyOfBook != null) return copyOfBook.getSerieIndex();\r\n if (Helper.isNotNullOrEmpty(serieIndex)) {\r\n return serieIndex;\r\n }\r\n // We never expect to get here!\r\n logger.warn(\"Unexpected null/empty Series Index for book \" + getDisplayName() + \"(\" + getId() + \")\"); Helper.statsWarnings++;\r\n return (float)1.0;\r\n }\r\n\r\n public Date getTimestamp() {\r\n if (copyOfBook != null) return copyOfBook.getTimestamp();\r\n // ITIMPI: Return 'now' if timestamp not set - would 0 be better?\r\n if (timestamp == null) {\r\n logger.warn(\"Date/Time Added not set for book '\" + title + \"'\"); Helper.statsWarnings++;\r\n return new Date();\r\n }\r\n return timestamp;\r\n }\r\n\r\n public Date getModified() {\r\n if (copyOfBook != null) return copyOfBook.getModified();\r\n // ITIMPI: Return 'now' if modified not set - would 0 be better?\r\n if (modified == null) {\r\n logger.warn(\"Date/Time Modified not set for book '\" + title + \"'\"); Helper.statsWarnings++;\r\n return new Date();\r\n }\r\n return modified;\r\n }\r\n\r\n public Date getPublicationDate() {\r\n if (copyOfBook != null) return copyOfBook.getPublicationDate();\r\n if (publicationDate == null) {\r\n logger.warn(\"Publication Date not set for book '\" + title + \"'\"); Helper.statsWarnings++;\r\n return ZERO;\r\n }\r\n return (publicationDate);\r\n }\r\n\r\n public boolean hasAuthor() {\r\n return Helper.isNotNullOrEmpty(getAuthors());\r\n }\r\n\r\n public boolean hasSingleAuthor() {\r\n if (copyOfBook != null) return copyOfBook.hasSingleAuthor();\r\n return (Helper.isNotNullOrEmpty(authors) && authors.size() == 1);\r\n }\r\n\r\n public List<Author> getAuthors() {\r\n if (copyOfBook != null) return copyOfBook.getAuthors();\r\n assert authors != null && authors.size() > 0;\r\n return authors;\r\n }\r\n\r\n /**\r\n * Create a comma separated list of authors\r\n * @return\r\n */\r\n public String getListOfAuthors() {\r\n if (copyOfBook != null) return copyOfBook.getListOfAuthors();\r\n if (listOfAuthors == null)\r\n listOfAuthors = Helper.concatenateList(\" & \", getAuthors(), \"getDisplayName\");\r\n return listOfAuthors;\r\n }\r\n\r\n public Author getMainAuthor() {\r\n if (copyOfBook != null) return copyOfBook.getMainAuthor();\r\n if (getAuthors() == null || getAuthors().size() == 0)\r\n return null;\r\n return getAuthors().get(0);\r\n }\r\n\r\n public String getAuthorSort() {\r\n return (copyOfBook == null) ? authorSort : copyOfBook.getAuthorSort();\r\n }\r\n\r\n public Publisher getPublisher() {\r\n return (copyOfBook == null) ? publisher : copyOfBook.getPublisher();\r\n }\r\n\r\n public void setPublisher(Publisher publisher) {\r\n assert copyOfBook == null; // Do not expect this on a copy\r\n this.publisher = publisher;\r\n }\r\n\r\n public Series getSeries() {\r\n return (copyOfBook == null) ? series : copyOfBook.getSeries();\r\n }\r\n\r\n public void setSeries(Series value) {\r\n assert copyOfBook == null; // Do not expect this on a copy\r\n this.series = value;\r\n }\r\n\r\n /**\r\n * Note that the list of tags for a books can be different\r\n * in the master and in any copies of the book object\r\n *\r\n * @return\r\n */\r\n public List<Tag> getTags() {\r\n return tags;\r\n }\r\n\r\n /**\r\n * Get the list of eBook files associated with this book.\r\n * @return\r\n */\r\n public List<EBookFile> getFiles() {\r\n if (copyOfBook != null) return copyOfBook.getFiles();\r\n if (! isFlags(FLAG_FILES_SORTED)) {\r\n if (files != null && files.size() > 1) {\r\n Collections.sort(files, new Comparator<EBookFile>() {\r\n public int compare(EBookFile o1, EBookFile o2) {\r\n if (o1 == null) {\r\n if (o2 == null)\r\n return 0;\r\n else\r\n return 1;\r\n }\r\n if (o2 == null) {\r\n return -1;\r\n }\r\n // Now allow for empty format entries\r\n if (o1.getFormat() == null) {\r\n if (o2.getFormat() == null)\r\n return 0;\r\n else\r\n return 1;\r\n }\r\n if (o2.getFormat() == null) {\r\n return -1;\r\n }\r\n return Helper.checkedCompare(o1.getFormat().toString(), o2.getFormat().toString());\r\n }\r\n });\r\n }\r\n setFlags(true, FLAG_FILES_SORTED);;\r\n }\r\n return files;\r\n }\r\n\r\n public void removeFile(EBookFile file) {\r\n assert copyOfBook == null; // Do not expect this on a copy\r\n files.remove(file);\r\n epubFile = null;\r\n preferredFile = null;\r\n latestFileModifiedDate = -1;\r\n setFlags(false,FLAG_EPUBFILE_COMPUTED + FLAG_PREFERREDFILECOMPUTED + FLAG_FILES_SORTED);\r\n }\r\n\r\n /**\r\n *\r\n * @param file\r\n */\r\n public void addFile(EBookFile file) {\r\n assert copyOfBook == null; // Fo not expect this on a copy\r\n files.add(file);\r\n epubFile = null;\r\n preferredFile = null;\r\n latestFileModifiedDate = -1;\r\n setFlags(false,FLAG_EPUBFILE_COMPUTED + FLAG_PREFERREDFILECOMPUTED + FLAG_FILES_SORTED);\r\n }\r\n\r\n public EBookFile getPreferredFile() {\r\n if (copyOfBook != null) return copyOfBook.getPreferredFile();\r\n if (! isFlags(FLAG_PREFERREDFILECOMPUTED)) {\r\n for (EBookFile file : getFiles()) {\r\n if (preferredFile == null || file.getFormat().getPriority() > preferredFile.getFormat().getPriority())\r\n preferredFile = file;\r\n }\r\n setFlags(true, FLAG_PREFERREDFILECOMPUTED);\r\n }\r\n return preferredFile;\r\n }\r\n\r\n /**\r\n * @param author\r\n */\r\n public void addAuthor(Author author) {\r\n assert copyOfBook == null; // Do not expect this on a copy\r\n listOfAuthors = null; // Force display list to be recalculated\r\n if (authors == null)\r\n authors = new LinkedList<Author>();\r\n if (!authors.contains(author))\r\n authors.add(author);\r\n }\r\n\r\n public String toString() {\r\n return getId() + \" - \" + getDisplayName();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == null)\r\n return false;\r\n if (obj instanceof Book) {\r\n return (Helper.checkedCompare(((Book) obj).getId(), getId()) == 0);\r\n } else\r\n return super.equals(obj);\r\n }\r\n\r\n public String toDetailedString() {\r\n return getId() + \" - \" + getMainAuthor().getDisplayName() + \" - \" + getDisplayName() + \" - \" + Helper.concatenateList(getTags()) + \" - \" + getPath();\r\n }\r\n\r\n public File getBookFolder() {\r\n if (copyOfBook != null) return copyOfBook.getBookFolder();\r\n if (bookFolder == null) {\r\n File calibreLibraryFolder = Configuration.instance().getDatabaseFolder();\r\n bookFolder = new File(calibreLibraryFolder, getPath());\r\n }\r\n return bookFolder;\r\n }\r\n\r\n public String getEpubFilename() {\r\n if (copyOfBook != null) return copyOfBook.getEpubFilename();\r\n if (! isFlags(FLAG_EPUBFILE_COMPUTED)) {\r\n getEpubFile();\r\n }\r\n return epubFileName;\r\n }\r\n\r\n public EBookFile getEpubFile() {\r\n if (copyOfBook != null) return copyOfBook.getEpubFile();\r\n if (!isFlags(FLAG_EPUBFILE_COMPUTED)) {\r\n epubFile = null;\r\n epubFileName = null;\r\n for (EBookFile file : getFiles()) {\r\n if (file.getFormat() == EBookFormat.EPUB) {\r\n epubFile = file;\r\n epubFileName = epubFile.getName() + epubFile.getExtension();\r\n }\r\n }\r\n setFlags(true, FLAG_EPUBFILE_COMPUTED);\r\n }\r\n return epubFile;\r\n }\r\n\r\n public boolean doesEpubFileExist() {\r\n if (copyOfBook != null) return copyOfBook.doesEpubFileExist();\r\n EBookFile file = getEpubFile();\r\n if (file == null)\r\n return false;\r\n File f = file.getFile();\r\n return (f != null && f.exists());\r\n }\r\n\r\n public long getLatestFileModifiedDate() {\r\n if (copyOfBook != null) return copyOfBook.getLatestFileModifiedDate();\r\n if (latestFileModifiedDate == -1) {\r\n latestFileModifiedDate = 0;\r\n for (EBookFile file : getFiles()) {\r\n File f = file.getFile();\r\n if (f.exists()) {\r\n long m = f.lastModified();\r\n if (m > latestFileModifiedDate)\r\n latestFileModifiedDate = m;\r\n }\r\n }\r\n }\r\n return latestFileModifiedDate;\r\n }\r\n\r\n public BookRating getRating() {\r\n if (copyOfBook != null) return copyOfBook.getRating();\r\n return rating;\r\n }\r\n\r\n /**\r\n * Make a copy of the book object.\r\n *\r\n * The copy has some special behavior in that most properties a@e read\r\n * from the original, but the tags one is still private.\r\n *\r\n * NOTE: Can pass as null values that are always read from parent!\r\n * Not sure if this reduces RAM usage or not!\r\n *\r\n * @return Book object that is the copy\r\n */\r\n public Book copy() {\r\n Book result = new Book(\r\n null,\r\n null,\r\n null,\r\n null,\r\n null,\r\n null,timestamp,modified,publicationDate,isbn,authorSort,rating);\r\n\r\n // The tags aassciated with this entry may be changed, so we make\r\n // a copy of the ones currently associated\r\n result.tags = new LinkedList<Tag>(this.getTags());\r\n\r\n // Indicate this is a copy by setting a reference to the parent\r\n // This is used to read/set variables that must be in parent.\r\n result.copyOfBook = (this.copyOfBook == null) ? this : this.copyOfBook;\r\n return result;\r\n }\r\n\r\n public boolean isFlagged() {\r\n if (copyOfBook != null) return copyOfBook.isFlagged();\r\n return isFlags(FLAG_FLAGGED);\r\n }\r\n\r\n public void setFlagged() {\r\n if (copyOfBook != null) {\r\n copyOfBook.setFlagged();\r\n return;\r\n }\r\n setFlags(true, FLAG_FLAGGED);\r\n }\r\n\r\n public void clearFlagged() {\r\n if (copyOfBook != null) {\r\n copyOfBook.clearFlagged();\r\n return;\r\n }\r\n setFlags(false, FLAG_FLAGGED);\r\n }\r\n\r\n /**\r\n * Return whether we believe book has been changed since last run\r\n * @return\r\n */\r\n public boolean isChanged() {\r\n if (copyOfBook != null) return copyOfBook.isChanged();\r\n return isFlags(FLAG_CHANGED);\r\n }\r\n\r\n /**\r\n * Set the changed status to be true\r\n * (default is false, -so should only need to set to true.\r\n * If neccesary could change to pass in required state).\r\n */\r\n public void setChanged() {\r\n if (copyOfBook != null) {\r\n copyOfBook.setChanged();\r\n return;\r\n }\r\n setFlags(true, FLAG_CHANGED);\r\n }\r\n\r\n public List<CustomColumnValue> getCustomColumnValues() {\r\n return customColumnValues;\r\n }\r\n\r\n public void setCustomColumnValues (List <CustomColumnValue> values) {\r\n assert copyOfBook == null:\r\n customColumnValues = values;\r\n }\r\n\r\n public CustomColumnValue getCustomColumnValue (String name) {\r\n assert false : \"getCustomColumnValue() not yet ready for use\";\r\n return null;\r\n }\r\n\r\n public void setCustomColumnValue (String name, String value) {\r\n assert false : \"setCustomColumnValue() not yet ready for use\";\r\n }\r\n\r\n public void setDone() {\r\n if (copyOfBook != null) {\r\n copyOfBook.setDone();\r\n return;\r\n }\r\n setFlags(true, FLAG_DONE);\r\n }\r\n\r\n public boolean isDone() {\r\n if (copyOfBook != null) return copyOfBook.isDone();\r\n return isFlags(FLAG_DONE);\r\n }\r\n\r\n /**\r\n * Set referenced flag.\r\n */\r\n public void setReferenced() {\r\n if (copyOfBook != null) {\r\n copyOfBook.setReferenced();\r\n return;\r\n }\r\n setFlags(true, FLAG_REFERENCED);\r\n }\r\n\r\n /**\r\n * Get referenced flag\r\n *\r\n * @return\r\n */\r\n public boolean isReferenced() {\r\n if (copyOfBook != null) return copyOfBook.isReferenced();\r\n return isFlags(FLAG_REFERENCED);\r\n }\r\n}\r", "public abstract class GenericDataObject implements SplitableByLetter {\r\n private final static Logger logger = LogManager.getLogger(Author.class);\r\n\r\n // METHODS and PROPERTIES that must be implemented in derived classes)\r\n\r\n public abstract String getColumnName(); // Calibre lookup name\r\n public abstract ColumType getColumnType(); // Calibre column type\r\n public abstract String getDisplayName(); // Name that is used for Display purposes\r\n public abstract String getSortName(); // Sort name (if different to Display Name)\r\n public abstract String getTextToSort(); // Text to sort by (that takes into account whether DisplayName or SortName is to be used)\r\n public abstract String getTextToDisplay(); // Text for display that takes into account whether DisplaName or SortName is to be used.\r\n\r\n // METHODS and PROPERTIES\r\n\r\n static void sortObjectsByTitle(List<GenericDataObject> objs) {\r\n Collections.sort(objs, new Comparator<GenericDataObject>() {\r\n public int compare(GenericDataObject o1, GenericDataObject o2) {\r\n return Helper.checkedCollatorCompareIgnoreCase(o1.getTextToSort(), o2.getTextToSort());\r\n }\r\n });\r\n }\r\n\r\nstatic Comparator<GenericDataObject> comparator = new Comparator<GenericDataObject>() {\r\n\r\n public int compare(GenericDataObject o1, GenericDataObject o2) {\r\n String s1 = (o1 == null ? \"\" : o1.getTextToSort());\r\n String s2 = (o2 == null ? \"\" : o2.getTextToSort());\r\n return s1.compareTo(s2);\r\n }\r\n};\r\n\r\n public static <T extends SplitableByLetter> Map<String, List<T>> splitByLetter(List<T> objects) {\r\n return splitByLetter(objects, comparator);\r\n }\r\n /**\r\n * Split a list of items by the first letter that is different in some (e.g. Mortal, More and Morris will be splitted on t, e and r)\r\n * @param objects\r\n * @return\r\n */\r\n public static <T extends SplitableByLetter> Map<String, List<T>> splitByLetter(List<T> objects, Comparator comparator) {\r\n Map<String, List<T>> splitMap = new HashMap<String, List<T>>();\r\n\r\n // construct a list of all strings to split\r\n Vector<String> stringsToSplit = new Vector<String>(objects.size());\r\n String commonPart = null;\r\n for (T object : objects) {\r\n if (object == null)\r\n continue;\r\n String string = object.getTextToSort();\r\n\r\n // remove any diacritic mark\r\n String temp = Normalizer.normalize(string, Normalizer.Form.NFD);\r\n Pattern pattern = Pattern.compile(\"\\\\p{InCombiningDiacriticalMarks}+\");\r\n String norm = pattern.matcher(temp).replaceAll(\"\");\r\n string = norm;\r\n stringsToSplit.add(string);\r\n\r\n // find the common part\r\n if (commonPart == null) {\r\n commonPart = string.toUpperCase();\r\n } else if (commonPart.length() > 0) {\r\n String tempCommonPart = commonPart;\r\n while (tempCommonPart.length() > 0 && !string.toUpperCase().startsWith(tempCommonPart)) {\r\n tempCommonPart = tempCommonPart.substring(0, tempCommonPart.length()-1);\r\n }\r\n commonPart = tempCommonPart.toUpperCase();\r\n }\r\n }\r\n\r\n // note the position of the first different char\r\n int firstDifferentCharPosition = commonPart.length();\r\n\r\n // browse all objects and split them up\r\n for (int i=0; i<objects.size(); i++) {\r\n T object = objects.get(i);\r\n if (object == null)\r\n continue;\r\n\r\n String string = stringsToSplit.get(i);\r\n String discriminantPart = \"_\";\r\n if (Helper.isNotNullOrEmpty(string)) {\r\n if (firstDifferentCharPosition + 1 >= string.length())\r\n discriminantPart = string.toUpperCase();\r\n else\r\n discriminantPart = string.substring(0, firstDifferentCharPosition+1).toUpperCase();\r\n\r\n // find the already existing list (of items split by this discriminant part)\r\n List<T> list = splitMap.get(discriminantPart);\r\n if (list == null) {\r\n // no list yet, create one\r\n list = new LinkedList<T>();\r\n splitMap.put(discriminantPart, list);\r\n }\r\n\r\n // add the current item to the list\r\n list.add(object);\r\n }\r\n }\r\n\r\n // sort each list\r\n for (String letter : splitMap.keySet()) {\r\n List<T> objectsInThisLetter = splitMap.get(letter);\r\n Collections.sort(objectsInThisLetter, comparator);\r\n }\r\n return splitMap;\r\n }\r\n\r\n}\r", "public class Tag extends GenericDataObject implements SplitableByLetter, Comparable<Tag> {\r\n private final String id;\r\n private final String name;\r\n private String[] partsOfTag;\r\n // Flags\r\n // NOTE: Using byte plus bit settings is more memory efficient than using boolean types\r\n private final static byte FLAG_ALL_CLEAR = 0;\r\n private final static byte FLAG_DONE = 0x01;\r\n private final static byte FLAG_REFERENCED = 0x02;\r\n private byte flags = FLAG_ALL_CLEAR;\r\n\r\n // CONSTRUCTOR\r\n\r\n public Tag(String id, String name) {\r\n super();\r\n this.id = id;\r\n this.name = name;\r\n }\r\n\r\n // METHODS and PROPERTIES implementing Abstract ones from Base class)\r\n\r\n public ColumType getColumnType() {\r\n return ColumType.COLUMN_TAGS;\r\n }\r\n public String getColumnName() {\r\n return \"tags\";\r\n }\r\n public String getDisplayName() {\r\n return name;\r\n }\r\n public String getSortName() {\r\n return name;\r\n }\r\n public String getTextToSort() {\r\n return name;\r\n }\r\n public String getTextToDisplay() {\r\n return name;\r\n }\r\n\r\n // METHODS and PROPERTIES\r\n\r\n public String getId() {\r\n return id;\r\n }\r\n\r\n\r\n\r\n public String toString() {\r\n return getTextToSort();\r\n }\r\n\r\n\r\n public String[] getPartsOfTag(String splitTagsOn) {\r\n if (partsOfTag == null) {\r\n List<String> parts = Helper.tokenize(getTextToSort(), splitTagsOn);\r\n partsOfTag = new String[parts.size()];\r\n int[] partsOfTagHash = new int[partsOfTag.length];\r\n for (int i = 0; i < parts.size(); i++) {\r\n String part = parts.get(i);\r\n partsOfTag[i] = part;\r\n partsOfTagHash[i] = (part == null ? -1 : part.hashCode());\r\n }\r\n }\r\n return partsOfTag;\r\n }\r\n\r\n public int compareTo(Tag o) {\r\n if (o == null)\r\n return 1;\r\n return Helper.trueStringCompare(getId(), o.getId());\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == null)\r\n return false;\r\n if (obj instanceof Tag) {\r\n return (Helper.checkedCompare(((Tag) obj).getId(), getId()) == 0);\r\n } else\r\n return super.equals(obj);\r\n }\r\n\r\n public void setDone() {\r\n flags |= FLAG_DONE;\r\n }\r\n public boolean isDone () {\r\n return ((flags & FLAG_DONE) != 0);\r\n }\r\n\r\n public void setReferenced() {\r\n flags |= FLAG_REFERENCED;\r\n }\r\n public boolean isReferenced () {\r\n return ((flags & FLAG_REFERENCED) != 0);\r\n }\r\n}\r", "public class TrookSpecificSearchDatabaseManager {\r\n\r\n private static final int MIN_KEYWORD_LEN = 3;\r\n\r\n private static File databaseFile = null;\r\n private static Connection connection = null;\r\n private static Map<String, Long> keywords = new HashMap<String, Long>();\r\n private static List<Book> storedBooks = new LinkedList<Book>();\r\n private static List<Author> storedAuthors = new LinkedList<Author>();\r\n private static List<Series> storedSeries = new LinkedList<Series>();\r\n private static List<Tag> storedTags = new LinkedList<Tag>();\r\n private static long keywordCounter = 0;\r\n private static long resultCounter = 0;\r\n\r\n private static final Logger logger = LogManager.getLogger(TrookSpecificSearchDatabaseManager.class);\r\n\r\n public static void setDatabaseFile(File dbFile) {\r\n databaseFile = dbFile;\r\n }\r\n\r\n public static File getDatabaseFile() {\r\n return databaseFile;\r\n }\r\n\r\n public static Connection getConnection() {\r\n if (connection == null) {\r\n initConnection();\r\n }\r\n return connection;\r\n }\r\n\r\n public static void closeConnection() {\r\n if (connection != null) {\r\n try {\r\n connection.close();\r\n } catch (SQLException e) {\r\n // Ignore any exception\r\n }\r\n }\r\n }\r\n\r\n public static boolean databaseExists() {\r\n if (databaseFile == null)\r\n return false;\r\n if (!databaseFile.exists())\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n private static void initConnection() {\r\n try {\r\n Class.forName(\"org.sqlite.JDBC\");\r\n if (databaseFile == null)\r\n return;\r\n if (databaseExists())\r\n databaseFile.delete();\r\n String url = databaseFile.toURI().getPath();\r\n connection = DriverManager.getConnection(\"jdbc:sqlite:\" + url);\r\n Statement stat = connection.createStatement();\r\n // drop the indexes\r\n stat.executeUpdate(\"DROP INDEX IF EXISTS KEYWORDS_RESULTS_RELATION_INDEX_ON_RESULTS;\");\r\n stat.executeUpdate(\"DROP INDEX IF EXISTS KEYWORDS_RESULTS_RELATION_INDEX_ON_KEYWORD;\");\r\n stat.executeUpdate(\"DROP INDEX IF EXISTS RESULTS_INDEX;\");\r\n stat.executeUpdate(\"DROP INDEX IF EXISTS KEYWORDS_INDEX;\");\r\n // drop the tables\r\n stat.executeUpdate(\"DROP TABLE IF EXISTS keywords_results_relation\");\r\n stat.executeUpdate(\"DROP TABLE IF EXISTS results\");\r\n stat.executeUpdate(\"DROP TABLE IF EXISTS keywords\");\r\n // create the tables\r\n stat.executeUpdate(\"CREATE TABLE keywords (keyword_id INTEGER PRIMARY KEY, keyword_value TEXT);\");\r\n stat.executeUpdate(\"CREATE TABLE results (result_id INTEGER PRIMARY KEY, result_type TEXT, result_entry TEXT);\");\r\n stat.executeUpdate(\"CREATE TABLE keywords_results_relation (keyword_id INTEGER, result_id INTEGER);\");\r\n // create the indexes\r\n stat.executeUpdate(\"CREATE UNIQUE INDEX KEYWORDS_INDEX ON keywords(keyword_id ASC);\");\r\n stat.executeUpdate(\"CREATE UNIQUE INDEX RESULTS_INDEX ON results(result_id ASC);\");\r\n stat.executeUpdate(\"CREATE INDEX KEYWORDS_RESULTS_RELATION_INDEX_ON_KEYWORD ON keywords_results_relation(keyword_id ASC);\");\r\n stat.executeUpdate(\"CREATE INDEX KEYWORDS_RESULTS_RELATION_INDEX_ON_RESULTS ON keywords_results_relation(result_id ASC);\");\r\n } catch (ClassNotFoundException e) {\r\n logger.error(e); Helper.statsErrors++;\r\n } catch (SQLException e) {\r\n logger.error(e); Helper.statsErrors++;\r\n }\r\n }\r\n\r\n\r\n\r\n private static long addResult(String opdsEntry, ResultType type) throws SQLException {\r\n PreparedStatement ps = getConnection().prepareStatement(\"INSERT INTO results(result_id, result_type, result_entry) values (?, ?, ?);\");\r\n ps.setLong(1, ++resultCounter);\r\n ps.setString(2, type.name().toUpperCase(Locale.ENGLISH));\r\n ps.setString(3, opdsEntry);\r\n ps.execute();\r\n return resultCounter;\r\n }\r\n\r\n private static long addKeyword(String keyword) throws SQLException {\r\n // check if keyword already exist (we test in memory to be quicker)\r\n if (keywords.containsKey(keyword))\r\n return keywords.get(keyword);\r\n else {\r\n PreparedStatement ps = getConnection().prepareStatement(\"INSERT INTO keywords(keyword_id, keyword_value) values (?, ?);\");\r\n ps.setLong(1, ++keywordCounter);\r\n ps.setString(2, keyword);\r\n ps.execute();\r\n keywords.put(keyword, keywordCounter);\r\n }\r\n return keywordCounter;\r\n }\r\n\r\n private static void addKeywordResultRelation(long keywordId, long resultId) throws SQLException {\r\n PreparedStatement ps = getConnection().prepareStatement(\"INSERT INTO keywords_results_relation(keyword_id, result_id) values (?, ?);\");\r\n ps.setLong(1, keywordId);\r\n ps.setLong(2, resultId);\r\n ps.execute();\r\n }\r\n\r\n private static List<String> keywordize(String pKeywordString) {\r\n List<String> keywords = new LinkedList<String>();\r\n List<String> result = new LinkedList<String>();\r\n String keywordString = pKeywordString.toUpperCase(Locale.ENGLISH);\r\n StringBuffer currentKeyword = null;\r\n for (int pos = 0; pos < keywordString.length(); pos++) {\r\n char c = keywordString.charAt(pos);\r\n if (!Character.isLetterOrDigit(c)) {\r\n // skip and break keywords at non letter or digits\r\n if (currentKeyword != null) {\r\n // process current keyword\r\n keywords.add(currentKeyword.toString());\r\n currentKeyword = null;\r\n }\r\n continue;\r\n }\r\n if (currentKeyword == null)\r\n currentKeyword = new StringBuffer();\r\n currentKeyword.append(c);\r\n }\r\n\r\n // process the last keyword\r\n if (currentKeyword != null) {\r\n keywords.add(currentKeyword.toString());\r\n currentKeyword = null;\r\n }\r\n\r\n // make packages with keywords, in increasing size\r\n for (int size = 1; size <= keywords.size(); size++) {\r\n int pos = 0;\r\n while (pos + size <= keywords.size()) {\r\n StringBuffer keywordPackage = new StringBuffer();\r\n for (int i = pos; i < pos + size; i++) {\r\n keywordPackage.append(keywords.get(i));\r\n keywordPackage.append(' ');\r\n }\r\n String s = keywordPackage.toString();\r\n result.add(s.substring(0, s.length() - 1));\r\n pos++;\r\n }\r\n }\r\n\r\n // add the \"whole string\" keyword\r\n result.add(keywordString);\r\n\r\n return result;\r\n }\r\n\r\n public static void addEntry(String opdsEntry, ResultType type, String... keywordStrings) throws SQLException {\r\n // add the result\r\n long resultId = addResult(opdsEntry, type);\r\n\r\n for (String keywordString : keywordStrings) {\r\n // process the keyword string\r\n List<String> keywords = keywordize(keywordString);\r\n for (String keyword : keywords) {\r\n if (keyword.length() >= MIN_KEYWORD_LEN) {\r\n long keywordId = addKeyword(keyword);\r\n addKeywordResultRelation(keywordId, resultId);\r\n }\r\n }\r\n }\r\n }\r\n\r\n private static void addEntryToTrookSearchDatabase(Element entry, ResultType type, String... keywords) {\r\n try {\r\n StringWriter sw = new StringWriter();\r\n JDOMManager.getCompactXML().output(entry, sw);\r\n String opdsEntry = sw.getBuffer().toString();\r\n addEntry(opdsEntry, type, keywords);\r\n } catch (IOException e) {\r\n logger.warn(e.getMessage()); Helper.statsWarnings++;\r\n } catch (SQLException e) {\r\n logger.warn(e.getMessage()); Helper.statsWarnings++;\r\n }\r\n }\r\n\r\n public static void addAuthor(Author item, Element entry) {\r\n if (ConfigurationManager.getCurrentProfile().getDeviceMode() == DeviceMode.Nook) {\r\n if (!storedAuthors.contains(item)) {\r\n logger.debug(\"adding result for \" + item);\r\n String keywords = item.getDisplayName();\r\n addEntryToTrookSearchDatabase(entry, ResultType.AUTHOR, keywords);\r\n storedAuthors.add(item);\r\n }\r\n }\r\n }\r\n\r\n public static void addSeries(Series item, Element entry) {\r\n if (ConfigurationManager.getCurrentProfile().getDeviceMode() == DeviceMode.Nook) {\r\n if (!storedSeries.contains(item)) {\r\n logger.debug(\"adding result for \" + item);\r\n String keywords = item.getDisplayName();\r\n // TODO do this after Doug has added support for noise words filtering in series \r\n // String noNoise = item.getTitleForSort(ConfigurationManager.getCurrentProfile().getBookLanguageTag());\r\n addEntryToTrookSearchDatabase(entry, ResultType.SERIES, keywords);\r\n storedSeries.add(item);\r\n }\r\n }\r\n }\r\n\r\n public static void addTag(Tag item, Element entry) {\r\n if (ConfigurationManager.getCurrentProfile().getDeviceMode() == DeviceMode.Nook) {\r\n if (!storedTags.contains(item)) {\r\n logger.debug(\"adding result for \" + item);\r\n String keywords = item.getTextToSort();\r\n addEntryToTrookSearchDatabase(entry, ResultType.TAG, keywords);\r\n storedTags.add(item);\r\n }\r\n }\r\n }\r\n\r\n public static void addBook(Book item, Element entry) {\r\n if (ConfigurationManager.getCurrentProfile().getDeviceMode() == DeviceMode.Nook) {\r\n if (!storedBooks.contains(item)) {\r\n logger.debug(\"adding result for \" + item);\r\n String keywords = item.getDisplayName();\r\n String noNoise = item.getSortName();\r\n addEntryToTrookSearchDatabase(entry, ResultType.BOOK, keywords, noNoise);\r\n storedBooks.add(item);\r\n }\r\n }\r\n }\r\n}\r", "public class Helper {\r\n\r\n private final static Logger logger = LogManager.getLogger(Helper.class);\r\n private static final String DEFAULT_PREFIX = \"com.gmail.dpierron.\";\r\n static final int DEFAULT_STACK_DEPTH = 5;\r\n\r\n /**\r\n * checked s1.equals(s2)\r\n */\r\n public static final boolean stringEquals(String s1, String s2) {\r\n return objectEquals(s1, s2);\r\n }\r\n\r\n /**\r\n * checked s1.equals(s2)\r\n */\r\n public static final boolean objectEquals(Object o1, Object o2) {\r\n if (o1 == null || o2 == null)\r\n return (o1 == null && o2 == null);\r\n\r\n return o1.equals(o2);\r\n }\r\n\r\n public static String newId() {\r\n String result = new VMID().toString();\r\n result = result.replace('0', 'G');\r\n result = result.replace('1', 'H');\r\n result = result.replace('2', 'I');\r\n result = result.replace('3', 'J');\r\n result = result.replace('4', 'K');\r\n result = result.replace('5', 'L');\r\n result = result.replace('6', 'M');\r\n result = result.replace('7', 'N');\r\n result = result.replace('8', 'O');\r\n result = result.replace('9', 'P');\r\n result = result.replaceAll(\"-\", \"\");\r\n result = result.replaceAll(\":\", \"\");\r\n return result;\r\n }\r\n\r\n public static void logStack(Logger logger) {\r\n logStack(logger, 2, DEFAULT_STACK_DEPTH, DEFAULT_PREFIX);\r\n }\r\n\r\n public static void logStack(Logger logger, int maxDepth) {\r\n logStack(logger, 2, maxDepth, DEFAULT_PREFIX);\r\n }\r\n\r\n public static void logStack(Logger logger, int skip, int maxDepth) {\r\n logStack(logger, skip + 2, maxDepth, DEFAULT_PREFIX);\r\n }\r\n\r\n public static void logStack(Logger logger, int skip, int maxDepth, String removePrefix) {\r\n Exception e = new RuntimeException();\r\n e.fillInStackTrace();\r\n StackTraceElement[] calls = e.getStackTrace();\r\n for (int i = skip; i < maxDepth + skip; i++) {\r\n if (i >= calls.length)\r\n break;\r\n StackTraceElement call = e.getStackTrace()[i];\r\n String msg = call.toString();\r\n if (removePrefix != null) {\r\n int pos = msg.indexOf(removePrefix);\r\n if (pos > -1)\r\n msg = msg.substring(pos + removePrefix.length());\r\n }\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"Stack trace [\" + (i - skip) + \"] -> \" + msg);\r\n }\r\n }\r\n\r\n public static String concatenateList(Collection toConcatenate) {\r\n return concatenateList(null, toConcatenate, (String[]) null);\r\n }\r\n\r\n public static String concatenateList(String separator, Collection toConcatenate) {\r\n return concatenateList(separator, toConcatenate, (String[]) null);\r\n }\r\n\r\n public static String concatenateList(Collection toConcatenate, String... methodName) {\r\n return concatenateList(null, toConcatenate, methodName);\r\n }\r\n\r\n public static String concatenateList(String separator, Collection toConcatenate, String... methodName) {\r\n try {\r\n if (toConcatenate == null || toConcatenate.size() == 0)\r\n return \"\";\r\n StringBuffer lines = new StringBuffer();\r\n String theSeparator = (separator == null ? \", \" : separator);\r\n for (Object o : toConcatenate) {\r\n Object result = o;\r\n if (methodName == null) {\r\n result = o.toString();\r\n } else {\r\n for (String theMethodName : methodName) {\r\n Method method = null;\r\n try {\r\n method = result.getClass().getMethod(theMethodName);\r\n } catch (SecurityException e) {\r\n logger.warn(e.getMessage(), e); Helper.statsWarnings++;\r\n } catch (NoSuchMethodException e) {\r\n logger.warn(e.getMessage(), e); Helper.statsWarnings++;\r\n }\r\n\r\n if (method != null)\r\n try {\r\n result = method.invoke(result);\r\n } catch (IllegalArgumentException e) {\r\n logger.warn(e.getMessage(), e); Helper.statsWarnings++;\r\n } catch (IllegalAccessException e) {\r\n logger.warn(e.getMessage(), e); Helper.statsWarnings++;\r\n } catch (InvocationTargetException e) {\r\n logger.warn(e.getMessage(), e); Helper.statsWarnings++;\r\n }\r\n }\r\n }\r\n\r\n lines.append(result);\r\n lines.append(theSeparator);\r\n }\r\n String sLines = lines.length() >= theSeparator.length() ? lines.substring(0, lines.length() - theSeparator.length()) : \"\";\r\n return sLines;\r\n } catch (Exception e) {\r\n return \"\";\r\n }\r\n }\r\n\r\n public static Collection transformList(Collection toTransform, String... methodName) {\r\n List transformed = new LinkedList();\r\n try {\r\n if (toTransform == null || toTransform.size() == 0)\r\n return toTransform;\r\n for (Object o : toTransform) {\r\n Object result = o;\r\n if (methodName == null) {\r\n result = o.toString();\r\n } else {\r\n for (String theMethodName : methodName) {\r\n Method method;\r\n method = result.getClass().getMethod(theMethodName);\r\n result = method.invoke(result);\r\n }\r\n }\r\n transformed.add(result);\r\n }\r\n return transformed;\r\n } catch (Exception e) {\r\n return transformed;\r\n }\r\n }\r\n\r\n public static List<String> tokenize(String text, String delim) {\r\n return tokenize(text, delim, false);\r\n }\r\n\r\n public static List<String> tokenize(String text, String delim, boolean trim) {\r\n List<String> result = new LinkedList<String>();\r\n if (isNotNullOrEmpty(text)) {\r\n // Note: Do not use replaceall as this uses regular expressions for the 'delim'\r\n // parameter which can ahve unexpected side effects if special characters used.\r\n // String s = text.replaceAll(delim, \"�\");\r\n String s = text.replace(delim, \"�\");\r\n String[] tokens = s.split(\"�\");\r\n for (String token : tokens) {\r\n if (trim)\r\n token = token.trim();\r\n result.add(token);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n public static String deTokenize(Collection<String> list, String delim) {\r\n if (list.size() > 0) {\r\n StringBuffer sb = new StringBuffer();\r\n for (String text : list) {\r\n if (sb.length() > 0)\r\n sb.append(delim);\r\n sb.append(text);\r\n }\r\n return sb.toString();\r\n } else\r\n return \"\";\r\n }\r\n\r\n public static String leftPad(String s, char paddingCharacter, int length) {\r\n if (s.length() >= length)\r\n return s;\r\n StringBuffer sb = new StringBuffer();\r\n for (int i = s.length(); i < length; i++) {\r\n sb.append(paddingCharacter);\r\n }\r\n sb.append(s);\r\n return sb.toString();\r\n }\r\n\r\n public static String pad(String s, char paddingCharacter, int length) {\r\n if (s.length() >= length)\r\n return s;\r\n StringBuffer sb = new StringBuffer(s);\r\n for (int i = s.length(); i < length; i++) {\r\n sb.append(paddingCharacter);\r\n }\r\n return sb.toString();\r\n }\r\n\r\n /**\r\n * @return the last numeric component of string s (that is, the part of the\r\n * string to the right of the last non-numeric character)\r\n */\r\n public static String getLastNumericComponent(String s) {\r\n int i = s.length() - 1;\r\n while ((i >= 0) && (Character.isDigit(s.charAt(i))))\r\n i--;\r\n if (i < 0)\r\n return s;\r\n if (i == s.length() - 1 && !Character.isDigit(s.charAt(i)))\r\n return null;\r\n return (s.substring(i + 1));\r\n }\r\n\r\n /**\r\n * @return the right part of string s, after the first occurence of string\r\n * toSubstract, or the whole string s if it does not contain\r\n * toSubstract\r\n */\r\n public static String substractString(String s, String toSubstract) {\r\n if (isNullOrEmpty(s))\r\n return s;\r\n if (isNullOrEmpty(toSubstract))\r\n return s;\r\n if (!s.startsWith(toSubstract))\r\n return s;\r\n return s.substring(toSubstract.length());\r\n }\r\n\r\n public static boolean trueBooleanEquals(Object o1, Object o2) {\r\n return trueBoolean(o1) == trueBoolean(o2);\r\n }\r\n\r\n public static boolean trueBoolean(Object o) {\r\n if (o == null)\r\n return false;\r\n if (o instanceof Boolean)\r\n return ((Boolean) o).booleanValue();\r\n else\r\n return new Boolean(o.toString()).booleanValue();\r\n }\r\n\r\n public static Integer parseInteger(String s) {\r\n if (isNullOrEmpty(s))\r\n return null;\r\n try {\r\n int i = Integer.parseInt(s);\r\n return new Integer(i);\r\n } catch (NumberFormatException e) {\r\n return null;\r\n }\r\n }\r\n\r\n public static boolean trueStringEquals(Object o1, Object o2) {\r\n return trueString(o1).equals(trueString(o2));\r\n }\r\n\r\n public static int trueStringCompare(Object o1, Object o2) {\r\n return trueString(o1).compareTo(trueString(o2));\r\n }\r\n\r\n public static String trueString(Object o) {\r\n if (o == null)\r\n return \"\";\r\n else\r\n return o.toString();\r\n }\r\n\r\n public static Object[] arrayThis(Object[] theArray, Object... objects) {\r\n ArrayList result = listThis(objects);\r\n return result.toArray(theArray);\r\n }\r\n\r\n public static ArrayList listThis(Object... objects) {\r\n return listThis(false, objects);\r\n }\r\n\r\n public static ArrayList listThis(boolean duplicates, Object... objects) {\r\n ArrayList result = new ArrayList();\r\n if (objects != null)\r\n for (Object object : objects) {\r\n if (object == null)\r\n continue;\r\n if (object instanceof List) {\r\n List list = (List) object;\r\n if (duplicates) {\r\n result.addAll(list);\r\n } else {\r\n if (list != null)\r\n for (Object item : list) {\r\n if (item == null)\r\n continue;\r\n if (!result.contains(item))\r\n result.add(item);\r\n }\r\n }\r\n } else {\r\n result.add(object);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * This method takes a string and wraps it to a line length of no more than\r\n * wrap_length. If prepend is not null, each resulting line will be prefixed\r\n * with the prepend string. In that case, resultant line length will be no\r\n * more than wrap_length + prepend.length()\r\n */\r\n\r\n public static String wrap(String inString, int wrap_length, String prepend) {\r\n char[] charAry;\r\n\r\n int p, p2, offset = 0, marker;\r\n\r\n StringBuffer result = new StringBuffer();\r\n\r\n /* -- */\r\n\r\n if (inString == null) {\r\n return null;\r\n }\r\n\r\n if (wrap_length < 0) {\r\n throw new IllegalArgumentException(\"bad params\");\r\n }\r\n\r\n if (prepend != null) {\r\n result.append(prepend);\r\n }\r\n\r\n charAry = inString.toCharArray();\r\n\r\n p = marker = 0;\r\n\r\n // each time through the loop, p starts out pointing to the same char as\r\n // marker\r\n\r\n while (marker < charAry.length) {\r\n while (p < charAry.length && (charAry[p] != '\\n') && ((p - marker) < wrap_length)) {\r\n p++;\r\n }\r\n\r\n if (p == charAry.length) {\r\n result.append(inString.substring(marker, p));\r\n return result.toString();\r\n }\r\n\r\n if (charAry[p] == '\\n') {\r\n /*\r\n * We've got a newline. This newline is bound to have terminated the\r\n * while loop above. Step p back one character so that the isspace(*p)\r\n * check below will detect that it hit the \\n, and will do the right\r\n * thing.\r\n */\r\n\r\n result.append(inString.substring(marker, p + 1));\r\n\r\n if (prepend != null) {\r\n result.append(prepend);\r\n }\r\n\r\n p = marker = p + 1;\r\n\r\n continue;\r\n }\r\n\r\n p2 = p - 1;\r\n\r\n /*\r\n * We've either hit the end of the string, or we've gotten past the\r\n * wrap_length. Back p2 up to the last space before the wrap_length, if\r\n * there is such a space. Note that if the next character in the string\r\n * (the character immediately after the break point) is a space, we don't\r\n * need to back up at all. We'll just print up to our current location, do\r\n * the newline, and skip to the next line.\r\n */\r\n\r\n if (p < charAry.length) {\r\n if (isspace(charAry[p])) {\r\n offset = 1; /*\r\n * the next character is white space. We'll want to skip\r\n * that.\r\n */\r\n } else {\r\n /* back p2 up to the last white space before the break point */\r\n\r\n while ((p2 > marker) && !isspace(charAry[p2])) {\r\n p2--;\r\n }\r\n\r\n offset = 0;\r\n }\r\n }\r\n\r\n /*\r\n * If the line was completely filled (no place to break), we'll just copy\r\n * the whole line out and force a break.\r\n */\r\n\r\n if (p2 == marker) {\r\n p2 = p - 1;\r\n }\r\n\r\n if (!isspace(charAry[p2])) {\r\n /*\r\n * If weren't were able to back up to a space, copy out the whole line,\r\n * including the break character (in this case, we'll be making the\r\n * string one character longer by inserting a newline).\r\n */\r\n\r\n result.append(inString.substring(marker, p2 + 1));\r\n } else {\r\n /*\r\n * The break character is whitespace. We'll copy out the characters up\r\n * to but not including the break character, which we will effectively\r\n * replace with a newline.\r\n */\r\n\r\n result.append(inString.substring(marker, p2));\r\n }\r\n\r\n /* If we have not reached the end of the string, newline */\r\n\r\n if (p < charAry.length) {\r\n result.append(\"\\n\");\r\n\r\n if (prepend != null) {\r\n result.append(prepend);\r\n }\r\n }\r\n\r\n p = marker = p2 + 1 + offset;\r\n }\r\n\r\n return result.toString();\r\n }\r\n\r\n public static String wrap(String inString, int wrap_length) {\r\n return wrap(inString, wrap_length, null);\r\n }\r\n\r\n public static String wrap(String inString) {\r\n return wrap(inString, 150, null);\r\n }\r\n\r\n public static boolean isspace(char c) {\r\n return (c == '\\n' || c == ' ' || c == '\\t');\r\n }\r\n\r\n /**\r\n * checks whether the object o is contained in the collection c\r\n *\r\n * @param comparator if not null, used to determine if two items are the same\r\n */\r\n public static boolean contains(Collection c, Object o, Comparator comparator) {\r\n if (comparator == null) {\r\n // simply check if 'c' contains the pointer 'o'\r\n return c.contains(o);\r\n } else {\r\n // look into 'c' for occurence of 'o'\r\n for (Object o2 : c) {\r\n if (comparator.compare(o, o2) == 0) { // the objects match\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Computes the intersection between two collections\r\n *\r\n * @param c1 the first collection\r\n * @param c2 the second (obviously) collection\r\n */\r\n public static Collection intersect(Collection c1, Collection c2) {\r\n return intersect(c1, c2, null);\r\n }\r\n\r\n /**\r\n * Computes the intersection between two collections\r\n *\r\n * @param c1 the first collection\r\n * @param c2 the second (obviously) collection\r\n * @param comparator is used to determine if two items are the same\r\n */\r\n public static Collection intersect(Collection c1, Collection c2, Comparator comparator) {\r\n\r\n Collection result = new LinkedList();\r\n\r\n if (c1 == null || c2 == null || c1.size() == 0 || c2.size() == 0)\r\n return result;\r\n\r\n /*\r\n * This algorithm is shamelessly stolen from Collections.disjoint() ...\r\n * \r\n * We're going to iterate through c1 and test for inclusion in c2. If c1 is\r\n * a Set and c2 isn't, swap the collections. Otherwise, place the shorter\r\n * collection in c1. Hopefully this heuristic will minimize the cost of the\r\n * operation.\r\n */\r\n Collection left = c1;\r\n Collection right = c2;\r\n if ((left instanceof Set) && !(right instanceof Set) || (left.size() > right.size())) {\r\n\r\n left = c2;\r\n right = c1;\r\n }\r\n\r\n for (Object l : left) {\r\n if (contains(right, l, comparator))\r\n result.add(l);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns true if the object specified is nor null nor empty (e.g., an empty\r\n * string, or an empty collection)\r\n *\r\n * @param object the object to check\r\n * @return true if the text specified is nor null nor empty, false otherwise\r\n */\r\n public final static boolean isNotNullOrEmpty(Object object) {\r\n return !(isNullOrEmpty(object));\r\n }\r\n\r\n /**\r\n * Returns true if the object specified is nor null nor empty (e.g., an empty\r\n * string, or an empty collection, or in this case a zero-valued number)\r\n *\r\n * @param object the object to check\r\n * @return true if the text specified is null or empty, false otherwise\r\n */\r\n public final static boolean isNotNullOrEmptyOrZero(Object object) {\r\n return !(isNullOrEmpty(object, true));\r\n }\r\n\r\n /**\r\n * Returns true if the object specified is null or empty (e.g., an empty\r\n * string, or an empty collection)\r\n *\r\n * @param object the object to check\r\n * @return true if the text specified is null or empty, false otherwise\r\n */\r\n public final static boolean isNullOrEmpty(Object object) {\r\n return (isNullOrEmpty(object, false));\r\n }\r\n\r\n /**\r\n * Returns true if the object specified is null or empty (e.g., an empty\r\n * string, or an empty collection, or in this case a zero-valued number)\r\n *\r\n * @param object the object to check\r\n * @return true if the text specified is null or empty, false otherwise\r\n */\r\n public final static boolean isNullOrEmptyOrZero(Object object) {\r\n return (isNullOrEmpty(object, true));\r\n }\r\n\r\n private final static boolean isNullOrEmpty(Object object, boolean zeroEqualsEmpty) {\r\n if (object == null)\r\n return true;\r\n if (object instanceof Collection)\r\n return ((Collection) object).size() == 0;\r\n else if (object instanceof Map)\r\n return ((Map) object).size() == 0;\r\n else if (object.getClass().isArray())\r\n return ((Object[]) object).length == 0;\r\n else if (object instanceof Number && zeroEqualsEmpty)\r\n return ((Number) object).longValue() == 0;\r\n else\r\n return object.toString().length() == 0;\r\n }\r\n\r\n /**\r\n * Returns the list of files corresponding to the extension, in the currentDir\r\n * and below\r\n */\r\n public static List<File> recursivelyGetFiles(final String extension, File currentDir) {\r\n List<File> result = new LinkedList<File>();\r\n recursivelyGetFiles(extension, currentDir, result);\r\n return result;\r\n }\r\n\r\n private static void recursivelyGetFiles(final String extension, File currentDir, List<File> filesList) {\r\n String[] files = currentDir.list(new FilenameFilter() {\r\n\r\n public boolean accept(File dir, String name) {\r\n File f = new File(dir, name);\r\n return f.isDirectory() || name.endsWith(extension);\r\n }\r\n\r\n });\r\n\r\n for (String filename : files) {\r\n File f = new File(currentDir, filename);\r\n if (f.isDirectory())\r\n recursivelyGetFiles(extension, f, filesList);\r\n else\r\n filesList.add(f);\r\n }\r\n }\r\n\r\n /**\r\n * forces a string into a specific encoding\r\n */\r\n public static String forceCharset(String text, String charset) {\r\n String result = text;\r\n try {\r\n result = new String(text.getBytes(charset));\r\n } catch (UnsupportedEncodingException e) {\r\n logger.error(e.getMessage(), e); Helper.statsErrors++;\r\n }\r\n return result;\r\n }\r\n\r\n public static Object getDelegateOrNull(Object source) {\r\n return getDelegateOrNull(source, false);\r\n }\r\n\r\n public static Object getDelegateOrNull(Object source, boolean digDeep) {\r\n if (source == null)\r\n return null;\r\n Object result = source;\r\n try {\r\n Method method = source.getClass().getMethod(\"getDelegate\", (Class[]) null);\r\n if (method != null)\r\n result = method.invoke(source, (Object[]) null);\r\n } catch (SecurityException e) {\r\n // let's return the source object\r\n } catch (NoSuchMethodException e) {\r\n // let's return the source object\r\n } catch (IllegalArgumentException e) {\r\n // let's return the source object\r\n } catch (IllegalAccessException e) {\r\n // let's return the source object\r\n } catch (InvocationTargetException e) {\r\n // let's return the source object\r\n }\r\n if (digDeep && (result != source))\r\n return getDelegateOrNull(result, digDeep);\r\n else\r\n return result;\r\n }\r\n\r\n public static List filter(List source, List unwantedKeys, String method) {\r\n if (isNullOrEmpty(unwantedKeys))\r\n return source;\r\n if (isNullOrEmpty(source))\r\n return source;\r\n List result = new LinkedList();\r\n for (Object object : source) {\r\n if (object == null)\r\n continue;\r\n Object key = null;\r\n try {\r\n Method keyGetter = object.getClass().getMethod(method, (Class[]) null);\r\n if (keyGetter != null)\r\n key = keyGetter.invoke(object, (Object[]) null);\r\n } catch (SecurityException e) {\r\n // key stays null\r\n } catch (NoSuchMethodException e) {\r\n // key stays null\r\n } catch (IllegalArgumentException e) {\r\n // key stays null\r\n } catch (IllegalAccessException e) {\r\n // key stays null\r\n } catch (InvocationTargetException e) {\r\n // key stays null\r\n }\r\n if (key == null)\r\n key = object.toString();\r\n if (key != null && !unwantedKeys.contains(key))\r\n result.add(object);\r\n }\r\n return result;\r\n }\r\n\r\n public static List filter(List source, List<Class> unwantedClasses) {\r\n if (isNullOrEmpty(unwantedClasses))\r\n return source;\r\n if (isNullOrEmpty(source))\r\n return source;\r\n List result = new LinkedList();\r\n for (Object object : source) {\r\n if (object == null)\r\n continue;\r\n if (!unwantedClasses.contains(object.getClass()))\r\n result.add(object);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Fetch the entire contents of a text stream, and return it in a String.\r\n * This style of implementation does not throw Exceptions to the caller.\r\n */\r\n public static String readTextFile(InputStream is) {\r\n //...checks on aFile are elided\r\n StringBuilder contents = new StringBuilder();\r\n\r\n try {\r\n //use buffering, reading one line at a time\r\n //FileReader always assumes default encoding is OK!\r\n BufferedReader input = new BufferedReader(new InputStreamReader(is));\r\n try {\r\n String line = null; //not declared within while loop\r\n /*\r\n * readLine is a bit quirky :\r\n * it returns the content of a line MINUS the newline.\r\n * it returns null only for the END of the stream.\r\n * it returns an empty String if two newlines appear in a row.\r\n */\r\n while ((line = input.readLine()) != null) {\r\n contents.append(line);\r\n contents.append(System.getProperty(\"line.separator\"));\r\n }\r\n } finally {\r\n input.close();\r\n }\r\n } catch (IOException ex) {\r\n ex.printStackTrace();\r\n }\r\n\r\n return contents.toString();\r\n }\r\n\r\n public static String readTextFile(String fullPathFilename) throws IOException {\r\n return readTextFile(new FileInputStream(fullPathFilename));\r\n }\r\n\r\n public static File putBytesIntoFile(byte[] bytes, File file) throws IOException {\r\n FileOutputStream out = new FileOutputStream(file);\r\n try {\r\n out.write(bytes);\r\n } finally {\r\n out.close();\r\n }\r\n return file;\r\n }\r\n\r\n public static File getFileFromBytes(byte[] bytes) throws IOException {\r\n String prefix = new VMID().toString();\r\n return getFileFromBytes(bytes, prefix);\r\n }\r\n\r\n public static File getFileFromBytes(byte[] bytes, String prefix) throws IOException {\r\n File f = File.createTempFile(prefix, null);\r\n return putBytesIntoFile(bytes, f);\r\n }\r\n\r\n public static byte[] getBytesFromFile(File file) throws IOException {\r\n InputStream is = new FileInputStream(file);\r\n\r\n // Get the size of the file\r\n long length = file.length();\r\n\r\n // You cannot create an array using a long type.\r\n // It needs to be an int type.\r\n // Before converting to an int type, check\r\n // to ensure that file is not larger than Integer.MAX_VALUE.\r\n if (length > Integer.MAX_VALUE) {\r\n // File is too large\r\n }\r\n\r\n // Create the byte array to hold the data\r\n byte[] bytes = new byte[(int) length];\r\n\r\n // Read in the bytes\r\n int offset = 0;\r\n int numRead = 0;\r\n while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {\r\n offset += numRead;\r\n }\r\n\r\n // Ensure all the bytes have been read in\r\n if (offset < bytes.length) {\r\n throw new IOException(\"Could not completely read file \" + file.getName());\r\n }\r\n\r\n // Close the input stream and return bytes\r\n is.close();\r\n return bytes;\r\n }\r\n\r\n public static String nowAs14CharString() {\r\n final DateFormat format = new SimpleDateFormat(\"yyyyMMddHHmmss\");\r\n return format.format(new Date());\r\n }\r\n\r\n public static String removeLeadingZeroes(String value) {\r\n return removeLeadingChars(value, '0');\r\n }\r\n\r\n public static String removeLeadingChars(String value, char charToRemove) {\r\n if (Helper.isNotNullOrEmpty(value)) {\r\n String regex = \"^\" + charToRemove + \"*\";\r\n return value.replaceAll(regex, \"\");\r\n }\r\n return value;\r\n }\r\n\r\n public static String makeString(String baseString, int number) {\r\n if (Helper.isNotNullOrEmpty(baseString) && (number > 0)) {\r\n StringBuffer sb = new StringBuffer();\r\n for (int i = 0; i < number; i++)\r\n sb.append(baseString);\r\n return sb.toString();\r\n }\r\n return \"\";\r\n }\r\n\r\n /**\r\n * Convert the stack trace into a string suitable for logging\r\n * @param t\r\n * @return\r\n */\r\n public static String getStackTrace(Throwable t) {\r\n StringBuilder sb = new StringBuilder(\"\");\r\n if (t != null) {\r\n for (StackTraceElement element : t.getStackTrace()) {\r\n sb.append(element.toString() + '\\n');\r\n }\r\n }\r\n return sb.toString();\r\n }\r\n\r\n public static Stack<Throwable> unwrap(Throwable t) {\r\n Stack<Throwable> result = new Stack<Throwable>();\r\n while (t != null) {\r\n result.add(t);\r\n t = t.getCause();\r\n }\r\n return result;\r\n }\r\n\r\n public static class ListCopier<T> {\r\n public List<T> copyList(List<T> original, int pMaxSize) {\r\n if (original == null)\r\n return null;\r\n int maxSize = pMaxSize;\r\n if (maxSize < 0)\r\n maxSize = original.size();\r\n if (original.size() <= maxSize)\r\n return new LinkedList<T>(original);\r\n List<T> result = new LinkedList<T>();\r\n for (int i = 0; i < maxSize; i++) {\r\n result.add(original.get(i));\r\n }\r\n return result;\r\n }\r\n }\r\n\r\n\r\n public static String shorten(String s, int maxSize) {\r\n if (isNullOrEmpty(s) || maxSize < 2)\r\n return s;\r\n if (s.length() > maxSize)\r\n return s.substring(0, maxSize) + \"...\";\r\n else\r\n return s;\r\n }\r\n\r\n\r\n // ITIMPI: It appears this routine is no longer used!\r\n // the logic has been subsumed into Catalog.merge()\r\n /*\r\n public static void copy(File src, File dst, boolean checkDates) throws IOException {\r\n if (src == null || dst == null) return;\r\n\r\n if (!src.exists()) return;\r\n\r\n if (src.isDirectory()) {\r\n\r\n if (!dst.exists()) dst.mkdirs();\r\n else if (!dst.isDirectory()) return;\r\n } else {\r\n\r\n boolean copy = false;\r\n if (!dst.exists()) {\r\n // ITIMPI: Is there a reason this is not logged via logger()?\r\n System.out.println(\"creating dirs \" + dst.getPath());\r\n dst.mkdirs();\r\n copy = true;\r\n }\r\n copy = copy || (!checkDates || (src.lastModified() > dst.lastModified()));\r\n if (copy) {\r\n InputStream in = new FileInputStream(src);\r\n copy(in, dst);\r\n }\r\n }\r\n }\r\n */\r\n\r\n public static void copy(File src, File dst) throws IOException {\r\n InputStream in = null;\r\n try {\r\n in = new FileInputStream(src);\r\n Helper.copy(in, dst);\r\n } finally {\r\n if (in != null)\r\n in.close();\r\n }\r\n\r\n }\r\n\r\n public static void copy(InputStream in, File dst) throws IOException {\r\n if (!dst.exists()) {\r\n if (dst.getName().endsWith(\"_Page\"))\r\n assert true;\r\n dst.getParentFile().mkdirs();\r\n }\r\n OutputStream out = null;\r\n try {\r\n out = new FileOutputStream(dst);\r\n\r\n copy(in, out);\r\n\r\n } finally {\r\n if (out != null)\r\n out.close();\r\n }\r\n }\r\n\r\n public static void copy(InputStream in, OutputStream out) throws IOException {\r\n try {\r\n // Transfer bytes from in to out\r\n byte[] buf = new byte[1024];\r\n int len;\r\n while ((len = in.read(buf)) > 0) {\r\n out.write(buf, 0, len);\r\n }\r\n } finally {\r\n if (out != null)\r\n out.close();\r\n }\r\n }\r\n\r\n private final static String[] FilesToKeep = new String[] { \".htaccess\", \"index.html\" };\r\n\r\n /**\r\n * Delete the given folder/files.\r\n *\r\n * You can specifiy whether the file should not be deleted if it is on\r\n * the list of those to keep, or should be deleted unconditionally\r\n *\r\n * @param path File to delete\r\n * @param check Specify whether to be kept if on reserved list\r\n */\r\n\r\n static public void delete (File path, boolean check) {\r\n\r\n if (path.exists()) {\r\n // Allow for list of Delete file xceptions (#c2o-112)\r\n if (check) {\r\n for (String f : FilesToKeep) {\r\n if (path.getName().toLowerCase().endsWith(f)) {\r\n if (logger.isTraceEnabled())\r\n logger.trace(\"File not deleted (on exception list): \" + path);\r\n return;\r\n }\r\n }\r\n }\r\n if (path.isDirectory()) {\r\n File[] files = path.listFiles();\r\n if (files != null)\r\n for (int i = 0; i < files.length; i++) {\r\n delete(files[i], check);\r\n }\r\n }\r\n path.delete();\r\n }\r\n }\r\n\r\n /**\r\n * Given a path, get a count of the contained folders and files\r\n * @param path\r\n * @return\r\n */\r\n static public long count(File path) {\r\n int result = 0;\r\n if (path.exists()) {\r\n if (path.isDirectory()) {\r\n File[] files = path.listFiles();\r\n if (files != null)\r\n for (int i = 0; i < files.length; i++) {\r\n result += count(files[i]);\r\n }\r\n }\r\n result++;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Routine to carry out comparisons using the object type's\r\n * compareTo methods. Allows for either option to be passed\r\n * in a null.\r\n * NOTE: This uses the object's compareTo for method, so for\r\n * string objects this is a strict comparison that does\r\n * not take into account locale differences. If you want\r\n * locale to be considerd then use the collator methods.\r\n * @param o1\r\n * @param o2\r\n * @return\r\n */\r\n public static int checkedCompare(Comparable o1, Comparable o2) {\r\n if (o1 == null) {\r\n if (o2 == null)\r\n return 0;\r\n else\r\n return 1;\r\n } else if (o2 == null) {\r\n if (o1 == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return o1.compareTo(o2);\r\n }\r\n\r\n /**\r\n * A checked string comparison that allows for null parameters\r\n * but ignores case differences.\r\n * @param s1\r\n * @param s2\r\n * @return\r\n */\r\n public static int checkedCompareIgnorCase (String s1, String s2) {\r\n if (s1 == null) {\r\n if (s2 == null)\r\n return 0;\r\n else\r\n return 1;\r\n } else if (s2 == null) {\r\n if (s1 == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return s1.toUpperCase().compareTo(s2.toUpperCase());\r\n }\r\n\r\n /**\r\n * A checked string compare that uses the collator methods\r\n * that take into account local. This method uses the\r\n * default locale.\r\n * @param s1\r\n * @param s2\r\n * @return\r\n */\r\n public static int checkedCollatorCompare (String s1, String s2, Collator collator) {\r\n if (s1 == null) {\r\n if (s2 == null)\r\n return 0;\r\n else\r\n return 1;\r\n } else if (s2 == null) {\r\n if (s1 == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return collator.compare(s1, s2);\r\n }\r\n public static int checkedCollatorCompareIgnoreCase (String s1, String s2, Collator collator) {\r\n return checkedCollatorCompare(s1.toUpperCase(), s2.toUpperCase(), collator);\r\n }\r\n\r\n /**\r\n * A checked string compare that uses the collator methods\r\n * that take into account local. This method uses the\r\n * default locale.\r\n * @param s1\r\n * @param s2\r\n * @return\r\n */\r\n public static int checkedCollatorCompare (String s1, String s2) {\r\n final Collator collator = Collator.getInstance();\r\n return checkedCollatorCompare(s1, s2, collator);\r\n }\r\n /**\r\n * A checked string compare that uses the collator methods\r\n * that take into account local. This method uses the\r\n * default locale.\r\n * @param s1 First string to compare\r\n * @param s2 Second string to compare\r\n * @return\r\n */\r\n public static int checkedCollatorCompareIgnoreCase (String s1, String s2) {\r\n return checkedCollatorCompare(s1.toUpperCase(), s2.toUpperCase());\r\n }\r\n\r\n public static int checkedCollatorCompare (String s1, String s2, Locale locale) {\r\n return checkedCollatorCompare(s1, s2, Collator.getInstance(locale));\r\n }\r\n public static int checkedCollatorCompareIgnoreCase (String s1, String s2, Locale locale) {\r\n return checkedCollatorCompare(s1.toUpperCase(), s2.toUpperCase(), locale);\r\n }\r\n\r\n public static ArrayList<File> listFilesIn(File dir) {\r\n ArrayList<File> result = new ArrayList<File>();\r\n if (dir != null && dir.isDirectory()) {\r\n String[] children = dir.list();\r\n if (children != null) {\r\n for (String childName : children) {\r\n File child = new File(dir, childName);\r\n if (child.isDirectory()) {\r\n result.addAll(listFilesIn(child));\r\n }\r\n result.add(child);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n public static String toTitleCase(String s) {\r\n if (Helper.isNullOrEmpty(s))\r\n return s;\r\n\r\n StringBuffer sb = new StringBuffer(s.length());\r\n sb.append(Character.toUpperCase(s.charAt(0)));\r\n sb.append(s.substring(1));\r\n return sb.toString();\r\n }\r\n\r\n /**\r\n * Code to remove HTML tags from an HTML string\r\n *\r\n * TODO: Consider whether this can be better implemented\r\n * TODO: using FOM and the InnterText metthod?\r\n *\r\n * TODO: Might want to consider replacing </p> tags with CR/LF?\r\n * @param s\r\n * @return\r\n */\r\n public static String removeHtmlElements(String s) {\r\n // process possible HTML tags\r\n StringBuffer sb = new StringBuffer();\r\n if (s != null) {\r\n boolean skipping = false;\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (!skipping) {\r\n if (c == '<')\r\n skipping = true;\r\n else\r\n sb.append(c);\r\n } else {\r\n if (c == '>')\r\n skipping = false;\r\n }\r\n }\r\n } else {\r\n return \"\";\r\n }\r\n return sb.toString();\r\n }\r\n\r\n public static String stringToHex(String base) {\r\n StringBuffer buffer = new StringBuffer();\r\n int intValue;\r\n for (int x = 0; x < base.length(); x++) {\r\n int cursor = 0;\r\n intValue = base.charAt(x);\r\n String binaryChar = new String(Integer.toBinaryString(base.charAt(x)));\r\n for (int i = 0; i < binaryChar.length(); i++) {\r\n if (binaryChar.charAt(i) == '1') {\r\n cursor += 1;\r\n }\r\n }\r\n if ((cursor % 2) > 0) {\r\n intValue += 128;\r\n }\r\n buffer.append(Integer.toHexString(intValue) + \" \");\r\n }\r\n return buffer.toString();\r\n }\r\n\r\n public static String convertToHex(String s) {\r\n if (isNullOrEmpty(s)) return \"\";\r\n StringBuffer sb = new StringBuffer();\r\n for (int pos=0;pos<s.length();pos++) {\r\n int codepoint = s.codePointAt(pos);\r\n sb.append(Integer.toHexString(codepoint));\r\n }\r\n return sb.toString();\r\n }\r\n\r\n /**\r\n * This function is the 'worker' one for handling derived names\r\n * for split-by-letter or split by page number.\r\n *\r\n * Any characters that are not alpha-numeric or the split character are hex encoded\r\n * to make the results safe to use in a URN or filename.\r\n *\r\n * As an optimisation to try and keep values start, it assumed that if the end of the\r\n * string passed in as the base corresponds to the start of the new encoded splitText\r\n * then it is only necessay to extend the name to make it unique by the difference.\r\n *\r\n * @param baseString The base string fromt he previous level\r\n * @param splitText The text for this split level\r\n * @param splitSeparator The seperator to be used between levels\r\n * @return The link to this level for parent\r\n */\r\n public static String getSplitString (String baseString, String splitText, String splitSeparator) {\r\n StringBuffer encodedSplitText = new StringBuffer();\r\n encodedSplitText.append(splitSeparator);\r\n\r\n // Get the encoded form of the splitText\r\n // TODO ITIMPI: Need to check why this encoding is needed!\r\n for (int x= 0; x < splitText.length(); x++) {\r\n char c = splitText.charAt(x);\r\n if (Character.isLetterOrDigit(c)) {\r\n // Alphanumerics are passed through unchanged\r\n encodedSplitText.append(c);\r\n } else {\r\n // Other characters are hex encoded\r\n encodedSplitText.append(Integer.toHexString(c));\r\n }\r\n }\r\n // Now see if we only we need to extend the basename or add a new section\r\n int pos = baseString.lastIndexOf(splitSeparator);\r\n if (pos > 0) {\r\n // Get the amount we want to check\r\n String checkPart = baseString.substring(pos);\r\n if (encodedSplitText.toString().length() != checkPart.length()\r\n && encodedSplitText.toString().startsWith(checkPart)) {\r\n baseString = baseString.substring(0,pos);\r\n }\r\n }\r\n return baseString + encodedSplitText.toString();\r\n }\r\n\r\n /*\r\n * Convert a parameter option 'glob' that contains ? and * wildcards to a regex\r\n *\r\n * Adapted from routine found via google search\r\n */\r\n public static String convertGlobToRegEx(String line) {\r\n line = line.trim();\r\n int strLen = line.length();\r\n StringBuilder sb = new StringBuilder(strLen);\r\n // Remove beginning and ending * globs because they're useless\r\n // TODO: ITMPI This does not seem to be true - not sure why code was originally here!\r\n /*\r\n if (line.startsWith(\"*\"))\r\n {\r\n line = line.substring(1);\r\n strLen--;\r\n }\r\n if (line.endsWith(\"*\"))\r\n {\r\n line = line.substring(0, strLen-1);\r\n strLen--;\r\n }\r\n */\r\n boolean escaping = false;\r\n int inCurlies = 0;\r\n for (char currentChar : line.toCharArray())\r\n {\r\n switch (currentChar)\r\n {\r\n // Wild car characters\r\n case '*':\r\n if (escaping)\r\n sb.append(\"\\\\*\");\r\n else\r\n sb.append(\".+\");\r\n escaping = false;\r\n break;\r\n case '?':\r\n if (escaping)\r\n sb.append(\"\\\\?\");\r\n else\r\n sb.append('.');\r\n escaping = false;\r\n break;\r\n // Characters needing special treatment\r\n case '.':\r\n case '(':\r\n case ')':\r\n case '+':\r\n case '|':\r\n case '^':\r\n case '$':\r\n case '@':\r\n case '%':\r\n // TODO ITIMPI: Following added as special cases below seem not relevant\r\n case '[':\r\n case ']':\r\n case '\\\\':\r\n case '{':\r\n case '}':\r\n case ',':\r\n sb.append('\\\\');\r\n sb.append(currentChar);\r\n escaping = false;\r\n break;\r\n/*\r\n case '\\\\':\r\n if (escaping)\r\n {\r\n sb.append(\"\\\\\\\\\");\r\n escaping = false;\r\n }\r\n else\r\n escaping = true;\r\n break;\r\n case '{':\r\n if (escaping)\r\n {\r\n sb.append(\"\\\\{\");\r\n }\r\n else\r\n {\r\n sb.append('(');\r\n inCurlies++;\r\n }\r\n escaping = false;\r\n break;\r\n case '}':\r\n if (inCurlies > 0 && !escaping)\r\n {\r\n sb.append(')');\r\n inCurlies--;\r\n }\r\n else if (escaping)\r\n sb.append(\"\\\\}\");\r\n else\r\n sb.append(\"}\");\r\n escaping = false;\r\n break;\r\n case ',':\r\n if (inCurlies > 0 && !escaping)\r\n {\r\n sb.append('|');\r\n }\r\n else if (escaping)\r\n sb.append(\"\\\\,\");\r\n else\r\n sb.append(\",\");\r\n break;\r\n*/\r\n // characters that can just be passed through unchanged\r\n default:\r\n escaping = false;\r\n sb.append(currentChar);\r\n }\r\n }\r\n return sb.toString();\r\n }\r\n\r\n // All possible locales\r\n private final static Locale[] availableLocales = Locale.getAvailableLocales();\r\n // Saved subset that we have actually used for faster searching\r\n // (can have duplicates under different length keys)\r\n private static HashMap<String,Locale> usedLocales = new HashMap<String, Locale>();\r\n /**\r\n * Get the local that corresponds to the provided language string\r\n * The following assumptions are made about the supplied parameter:\r\n * - If it is 2 characters in length then it is assumed to be the ISO2 value\r\n * - If it is 3 characters in length then it is assumed to be the ISO3 value\r\n * - If it is 4+ characters then it is assumed to be the Display Language text\r\n * If no match can be found then the English Locale is always returned\r\n * TODO: Perhaps we should consider returning null if no match found?\r\n *\r\n * @param lang\r\n * @return Locale\r\n */\r\n public static Locale getLocaleFromLanguageString(String lang) {\r\n if (usedLocales.containsKey(lang)) {\r\n return usedLocales.get(lang);\r\n }\r\n if (lang != null && lang.length() > 1) {\r\n for (Locale l : availableLocales) {\r\n switch (lang.length()) {\r\n // Note te case of a 2 character lang needs special treatment - see Locale code for getLangugage\r\n case 2: String s = l.toString();\r\n String ll = l.getLanguage();\r\n if (s.length() < 2 || s.length() > 2) break; // Ignore entries that are not 2 characters\r\n if (! s.equalsIgnoreCase(lang)) break;\r\n usedLocales.put(lang,l);\r\n return l;\r\n case 3: if (! l.getISO3Language().equalsIgnoreCase(lang)) break;\r\n usedLocales.put(lang,l);\r\n return l;\r\n default: if (! l.getDisplayLanguage().equalsIgnoreCase(lang)) break;\r\n usedLocales.put(lang,l);\r\n return l;\r\n }\r\n }\r\n }\r\n logger.warn(\"Program Error: Unable to find locale for '\" + lang + \"'\"); Helper.statsWarnings++;\r\n return null;\r\n }\r\n /**\r\n * Convert a pseudo=html string to plain text\r\n *\r\n * We sometimes use a form of Pseudo-HTML is strings that are to be\r\n * displayed in the GUI. These can be identifed by the fact that they\r\n * start with <HTML> andd contain <BR> where end-of-line is wanted.\r\n */\r\n public static String getTextFromPseudoHtmlText (String htmltext) {\r\n String text;\r\n if (! htmltext.toUpperCase().startsWith(\"<HTML>\")) {\r\n text = htmltext;\r\n } else {\r\n text = htmltext.substring(\"<HTML>\".length()).toUpperCase().replace(\"<br>\", \"\\r\\n\");\r\n }\r\n return text;\r\n }\r\n\r\n private static File installDirectory;\r\n\r\n /**\r\n *\r\n * @return\r\n */\r\n public static File getInstallDirectory() {\r\n if (installDirectory == null) {\r\n URL mySource = Helper.class.getProtectionDomain().getCodeSource().getLocation();\r\n File sourceFile = new File(mySource.getPath());\r\n installDirectory = sourceFile.getParentFile();\r\n }\r\n return installDirectory;\r\n }\r\n\r\n // Some Stats to accumulate\r\n // NOTE. We make them public to avoid needing getters\r\n public static long statsXmlChanged; // Count of files where we realise during generation that XML unchanged\r\n public static long statsXmlDiscarded; // count of XML files generated and then discarded as not needed for final catalog\r\n public static long statsHtmlChanged; // Count of files where HTML not generated as XML unchanged.\r\n public static long statsXmlUnchanged; // Count of files where we realise during generation that XML unchanged\r\n public static long statsHtmlUnchanged; // Count of files where HTML not generated as XML unchanged.\r\n public static long statsCopyExistHits; // Count of Files that are copied because target does not exist\r\n public static long statsCopyLengthHits; // Count of files that are copied because lengths differ\r\n public static long statsCopyDateMisses; // Count of files that are not copied because source older\r\n public static long statsCopyCrcHits; // Count of files that are copied because CRC different\r\n public static long statsCopyCrcMisses; // Count of files copied because CRC same\r\n public static long statsCopyToSelf; // Count of cases where copy to self requested\r\n public static long statsCopyUnchanged; // Count of cases where copy skipped because file was not even generated\r\n public static long statsCopyDeleted; // Count of files/folders deleted during copy process\r\n public static long statsBookUnchanged; // We detected that the book was unchanged since last run\r\n public static long statsBookChanged; // We detected that the book was changed since last run\r\n public static long statsCoverUnchanged; // We detected that the cover was unchanged since last run\r\n public static long statsCoverChanged; // We detected that the cover was changed since last run\r\n public static long statsWarnings; // Number of warning messages logged in a catalog run\r\n public static long statsErrors; // Number of error messages logged in a catalog run\r\n\r\n public static void resetStats() {\r\n statsXmlChanged\r\n = statsXmlDiscarded\r\n = statsHtmlChanged\r\n = statsXmlUnchanged\r\n = statsHtmlUnchanged\r\n = statsCopyExistHits\r\n = statsCopyLengthHits\r\n = statsCopyCrcHits\r\n = statsCopyCrcMisses\r\n = statsCopyDateMisses\r\n = statsCopyUnchanged\r\n = statsBookUnchanged\r\n = statsBookChanged\r\n = statsCoverUnchanged\r\n = statsCoverChanged\r\n = statsWarnings\r\n = statsErrors\r\n = 0;\r\n }\r\n}\r" ]
import com.gmail.dpierron.calibre.configuration.Icons; import com.gmail.dpierron.calibre.datamodel.Book; import com.gmail.dpierron.calibre.datamodel.GenericDataObject; import com.gmail.dpierron.calibre.datamodel.Tag; import com.gmail.dpierron.tools.i18n.Localization; import com.gmail.dpierron.calibre.trook.TrookSpecificSearchDatabaseManager; import com.gmail.dpierron.tools.Helper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import java.io.IOException; import java.util.*;
package com.gmail.dpierron.calibre.opds; /** * Class for defining methods that define a tag sub catalog */ public class TagListSubCatalog extends TagsSubCatalog { private final static Logger logger = LogManager.getLogger(TagListSubCatalog.class); public TagListSubCatalog(List<Object> stuffToFilterOut, List<Book> books) { super(stuffToFilterOut, books); setCatalogType(Constants.TAGLIST_TYPE); } public TagListSubCatalog(List<Book> books) { super(books); setCatalogType(Constants.TAGLIST_TYPE); } @Override //Composite<Element, String> getCatalog(Breadcrumbs pBreadcrumbs, boolean inSubDir) throws IOException { Element getCatalog(Breadcrumbs pBreadcrumbs, boolean inSubDir) throws IOException { return getListOfTags(pBreadcrumbs, getTags(), pBreadcrumbs.size() > 1, 0, Localization.Main.getText("tags.title"), getTags().size() > 1 ? Localization.Main.getText("tags.alphabetical", getTags().size()) : (getTags().size() == 1 ? Localization.Main.getText("authors.alphabetical.single") : "") , Constants.INITIAL_URN_PREFIX + getCatalogType() + getCatalogLevel(), getCatalogBaseFolderFileName(), null); } // private Composite<Element, String> getListOfTags( private Element getListOfTags( Breadcrumbs pBreadcrumbs,
List<Tag> listTags,
2
utapyngo/owl2vcs
src/main/java/owl2vcs/io/FunctionalChangesetSerializer.java
[ "public abstract class ChangeSet {\r\n\r\n protected ChangeSet() {\r\n }\r\n\r\n private SetOntologyFormatData formatChange;\r\n\r\n private Collection<PrefixChangeData> prefixChanges;\r\n\r\n private SetOntologyIDData ontologyIdChange;\r\n\r\n private Collection<ImportChangeData> importChanges;\r\n\r\n private Collection<OWLOntologyChangeData> annotationChanges;\r\n\r\n private Collection<AxiomChangeData> axiomChanges;\r\n\r\n public SetOntologyFormatData getFormatChange() {\r\n return formatChange;\r\n }\r\n\r\n public Collection<PrefixChangeData> getPrefixChanges() {\r\n return prefixChanges;\r\n }\r\n\r\n public SetOntologyIDData getOntologyIdChange() {\r\n return ontologyIdChange;\r\n }\r\n\r\n public Collection<ImportChangeData> getImportChanges() {\r\n return importChanges;\r\n }\r\n\r\n public Collection<OWLOntologyChangeData> getAnnotationChanges() {\r\n return annotationChanges;\r\n }\r\n\r\n public Collection<AxiomChangeData> getAxiomChanges() {\r\n return axiomChanges;\r\n }\r\n\r\n protected void setFormatChange(final SetOntologyFormatData formatChange) {\r\n this.formatChange = formatChange;\r\n }\r\n\r\n protected void setPrefixChanges(final Collection<PrefixChangeData> prefixChanges) {\r\n this.prefixChanges = prefixChanges;\r\n }\r\n\r\n protected void setOntologyIdChange(final SetOntologyIDData ontologyIdChange) {\r\n this.ontologyIdChange = ontologyIdChange;\r\n }\r\n\r\n protected void setImportChanges(final Collection<ImportChangeData> importChanges) {\r\n this.importChanges = importChanges;\r\n }\r\n\r\n protected void setAnnotationChanges(final Collection<OWLOntologyChangeData> annotationChanges) {\r\n this.annotationChanges = annotationChanges;\r\n }\r\n\r\n protected void setAxiomChanges(final Collection<AxiomChangeData> axiomChanges) {\r\n this.axiomChanges = axiomChanges;\r\n }\r\n\r\n /**\r\n * Count all changes.\r\n *\r\n * @return\r\n */\r\n public int size() {\r\n int sum = 0;\r\n if (formatChange != null)\r\n sum++;\r\n if (ontologyIdChange != null)\r\n sum++;\r\n sum += prefixChanges.size();\r\n sum += importChanges.size();\r\n sum += annotationChanges.size();\r\n sum += axiomChanges.size();\r\n return sum;\r\n }\r\n\r\n public Collection<Object> asCollection() {\r\n ArrayList<Object> result = new ArrayList<Object>();\r\n if (formatChange != null)\r\n result.add(formatChange);\r\n result.addAll(prefixChanges);\r\n if (ontologyIdChange != null)\r\n result.add(ontologyIdChange);\r\n result.addAll(importChanges);\r\n result.addAll(annotationChanges);\r\n result.addAll(axiomChanges);\r\n return result;\r\n }\r\n\r\n @SuppressWarnings({ \"unchecked\", \"serial\" })\r\n public Iterable<OWLOntologyChangeData> all() {\r\n return Iterables.concat(new ArrayList<OWLOntologyChangeData>() {\r\n {\r\n add(formatChange);\r\n }\r\n }, prefixChanges, new ArrayList<OWLOntologyChangeData>() {\r\n {\r\n add(ontologyIdChange);\r\n }\r\n }, importChanges, annotationChanges, axiomChanges);\r\n }\r\n\r\n public <R, E extends Exception> void accept(final CustomOntologyChangeDataVisitor<R, E> visitor)\r\n throws E {\r\n if (formatChange != null)\r\n formatChange.accept(visitor);\r\n for (final PrefixChangeData c : prefixChanges)\r\n c.accept(visitor);\r\n if (ontologyIdChange != null)\r\n ontologyIdChange.accept(visitor);\r\n for (final OWLOntologyChangeData c : importChanges)\r\n c.accept(visitor);\r\n for (final OWLOntologyChangeData c : annotationChanges)\r\n c.accept(visitor);\r\n for (final OWLOntologyChangeData c : axiomChanges)\r\n c.accept(visitor);\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n final int prime = 31;\r\n int result = 1;\r\n result = prime * result + ((annotationChanges == null) ? 0 : annotationChanges.hashCode());\r\n result = prime * result + ((axiomChanges == null) ? 0 : axiomChanges.hashCode());\r\n result = prime * result + ((formatChange == null) ? 0 : formatChange.hashCode());\r\n result = prime * result + ((importChanges == null) ? 0 : importChanges.hashCode());\r\n result = prime * result + ((ontologyIdChange == null) ? 0 : ontologyIdChange.hashCode());\r\n result = prime * result + ((prefixChanges == null) ? 0 : prefixChanges.hashCode());\r\n return result;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj)\r\n return true;\r\n if (obj == null)\r\n return false;\r\n if (!(obj instanceof ChangeSet))\r\n return false;\r\n ChangeSet other = (ChangeSet) obj;\r\n if (annotationChanges == null) {\r\n if (other.annotationChanges != null)\r\n return false;\r\n } else if (!setsEqual(annotationChanges, other.annotationChanges))\r\n return false;\r\n if (axiomChanges == null) {\r\n if (other.axiomChanges != null)\r\n return false;\r\n } else if (!setsEqual(axiomChanges, other.axiomChanges))\r\n return false;\r\n if (formatChange == null) {\r\n if (other.formatChange != null)\r\n return false;\r\n } else if (!formatChange.equals(other.formatChange))\r\n return false;\r\n if (importChanges == null) {\r\n if (other.importChanges != null)\r\n return false;\r\n } else if (!setsEqual(importChanges, other.importChanges))\r\n return false;\r\n if (ontologyIdChange == null) {\r\n if (other.ontologyIdChange != null)\r\n return false;\r\n } else if (!ontologyIdChange.equals(other.ontologyIdChange))\r\n return false;\r\n if (prefixChanges == null) {\r\n if (other.prefixChanges != null)\r\n return false;\r\n } else if (!setsEqual(prefixChanges, other.prefixChanges))\r\n return false;\r\n return true;\r\n }\r\n\r\n private <T> boolean setsEqual(Collection<T> c1, Collection<T> c2) {\r\n if ((c1 instanceof Set) && (c2 instanceof Set))\r\n return c1.equals(c2);\r\n if ((c1 instanceof Set))\r\n return c1.equals(new HashSet<T>(c2));\r\n if ((c2 instanceof Set))\r\n return new HashSet<T>(c1).equals(c2);\r\n return new HashSet<T>(c1).equals(new HashSet<T>(c2));\r\n }\r\n\r\n public boolean isEmpty() {\r\n return (formatChange == null) && (prefixChanges == null || prefixChanges.isEmpty())\r\n && (ontologyIdChange == null) && (importChanges == null || importChanges.isEmpty())\r\n && (annotationChanges == null || annotationChanges.isEmpty())\r\n && (axiomChanges == null || axiomChanges.isEmpty());\r\n }\r\n\r\n public void applyTo(final OWLOntology ontology) throws UnsupportedOntologyFormatException {\r\n OWLOntologyManager manager = ontology.getOWLOntologyManager();\r\n List<OWLOntologyChange> changes = new ArrayList<OWLOntologyChange>();\r\n // prefix changes can only be applied to ontology in a prefix format\r\n OWLOntologyFormat oldFormat = manager.getOntologyFormat(ontology);\r\n Map<String, String> newPrefixMap = null;\r\n if (manager.getOntologyFormat(ontology).isPrefixOWLOntologyFormat()) {\r\n PrefixOWLOntologyFormat oldPrefixFormat = oldFormat.asPrefixOWLOntologyFormat();\r\n Map<String, String> oldPrefixMap = new HashMap<String, String>(\r\n oldPrefixFormat.getPrefixName2PrefixMap());\r\n newPrefixMap = new HashMap<String, String>(oldPrefixMap);\r\n @SuppressWarnings(\"serial\")\r\n OWLEntityRenamer renamer = new OWLEntityRenamer(manager, new HashSet<OWLOntology>() {\r\n {\r\n add(ontology);\r\n }\r\n });\r\n for (PrefixChangeData c : prefixChanges) {\r\n if (c instanceof AddPrefixData) {\r\n // prefix should not be there\r\n assert oldPrefixMap.get(c.getPrefixName()) == null;\r\n newPrefixMap.put(c.getPrefixName(), c.getPrefix());\r\n } else if (c instanceof RemovePrefixData) {\r\n // prefix should already be there\r\n assert oldPrefixMap.get(c.getPrefixName()).equals(c.getPrefix());\r\n newPrefixMap.remove(c.getPrefixName());\r\n } else if (c instanceof ModifyPrefixData) {\r\n ModifyPrefixData mc = (ModifyPrefixData) c;\r\n // prefix should already be there\r\n assert oldPrefixMap.get(mc.getPrefixName()) != null;\r\n // and it should not be equal to new prefix\r\n String oldPrefix = oldPrefixMap.get(mc.getPrefixName());\r\n assert !oldPrefix.equals(mc.getPrefix());\r\n newPrefixMap.put(mc.getPrefixName(), mc.getPrefix());\r\n // rename entities\r\n // don't add changes to the \"changes\" ArrayList but apply them at once\r\n for (OWLEntity e : ontology.getSignature()) {\r\n if (e.getIRI().getStart().equals(mc.getOldPrefix()))\r\n manager.applyChanges(renamer.changeIRI(e, IRI.create(mc.getPrefix(), e.getIRI().getFragment())));\r\n }\r\n } else if (c instanceof RenamePrefixData) {\r\n String prefixToFind = c.getPrefix();\r\n String oldPrefixName = null;\r\n String newPrefixName = ((RenamePrefixData) c).getPrefixName();\r\n for (Map.Entry<String, String> e : oldPrefixMap.entrySet()) {\r\n if (e.getValue().equals(prefixToFind)) {\r\n oldPrefixName = e.getKey();\r\n break;\r\n }\r\n }\r\n // prefix name should already be there\r\n assert oldPrefixName != null;\r\n // and it should not be equal to the new name\r\n assert !oldPrefixName.equals(newPrefixName);\r\n\r\n newPrefixMap.remove(oldPrefixName);\r\n newPrefixMap.put(newPrefixName, c.getPrefix());\r\n }\r\n }\r\n }\r\n OWLOntologyFormat newFormat;\r\n if (formatChange != null) {\r\n newFormat = formatChange.getNewFormat();\r\n } else {\r\n newFormat = oldFormat;\r\n }\r\n // copy prefixes to new format\r\n if (newFormat.isPrefixOWLOntologyFormat()) {\r\n PrefixOWLOntologyFormat newPrefixFormat = newFormat.asPrefixOWLOntologyFormat();\r\n if (newPrefixMap != null) {\r\n newPrefixFormat.clearPrefixes();\r\n for (Map.Entry<String, String> e : newPrefixMap.entrySet()) {\r\n newPrefixFormat.setPrefix(e.getKey(), e.getValue());\r\n }\r\n }\r\n }\r\n // apply format (with prefixes)\r\n manager.setOntologyFormat(ontology, newFormat);\r\n // ontology ID\r\n if (ontologyIdChange != null)\r\n manager.applyChange(ontologyIdChange.createOntologyChange(ontology));\r\n // prepare and apply other changes\r\n for (OWLOntologyChangeData c : axiomChanges)\r\n changes.add(c.createOntologyChange(ontology));\r\n for (OWLOntologyChangeData c : annotationChanges)\r\n changes.add(c.createOntologyChange(ontology));\r\n for (OWLOntologyChangeData c : importChanges)\r\n changes.add(c.createOntologyChange(ontology));\r\n manager.applyChanges(changes);\r\n }\r\n}\r", "public enum ChangeFormat {\n COMPACT,\n INDENTED\n};", "public interface ChangeRenderer {\r\n\r\n String render(OWLOntologyChangeData change);\r\n Character getSymbol(OWLOntologyChangeData change);\r\n}\r", "public class FullFormProvider implements ShortFormProvider {\n\n @Override\n public final String getShortForm(final OWLEntity entity) {\n return \"<\" + entity.getIRI().toString() + \">\";\n }\n\n @Override\n public void dispose() {\n }\n\n}", "public class FunctionalChangeRenderer implements ChangeRenderer {\r\n\r\n private OWLObjectRenderer objectRenderer;\r\n private ChangeFormat changeFormat;\r\n\r\n public FunctionalChangeRenderer(final ShortFormProvider provider,\r\n final ChangeFormat changeFormat) {\r\n objectRenderer = new SimplerRenderer();\r\n objectRenderer.setShortFormProvider(provider);\r\n this.changeFormat = changeFormat;\r\n }\r\n\r\n /**\r\n * Render ontology changes.\r\n */\r\n @Override\r\n public final String render(final OWLOntologyChangeData change) {\r\n if (change == null)\r\n return null;\r\n // Custom changes\r\n if (change instanceof SetOntologyFormatData)\r\n return render((SetOntologyFormatData) change);\r\n else if (change instanceof AddPrefixData)\r\n return render((AddPrefixData) change);\r\n else if (change instanceof RemovePrefixData)\r\n return render((RemovePrefixData) change);\r\n else if (change instanceof ModifyPrefixData)\r\n return render((ModifyPrefixData) change);\r\n else if (change instanceof RenamePrefixData)\r\n return render((RenamePrefixData) change);\r\n // Standard changes\r\n else if (change instanceof SetOntologyIDData)\r\n return render((SetOntologyIDData) change);\r\n else if (change instanceof AddImportData)\r\n return render((AddImportData) change);\r\n else if (change instanceof RemoveImportData)\r\n return render((RemoveImportData) change);\r\n else if (change instanceof AddOntologyAnnotationData)\r\n return render((AddOntologyAnnotationData) change);\r\n else if (change instanceof RemoveOntologyAnnotationData)\r\n return render((RemoveOntologyAnnotationData) change);\r\n else if (change instanceof AddAxiomData)\r\n return render((AddAxiomData) change);\r\n else if (change instanceof RemoveAxiomData)\r\n return render((RemoveAxiomData) change);\r\n else\r\n return \"UnknownChangeType: \" + change.getClass().getName();\r\n }\r\n\r\n public final String render(final SetOntologyFormatData change) {\r\n return indentString(\"*\", \"OntologyFormat(\\\"\"\r\n + change.getNewFormat().toString() + \"\\\")\");\r\n }\r\n\r\n public final String render(final AddPrefixData change) {\r\n return indentString(\"+\", \"Prefix(\" + change.getPrefixName() + \"=<\"\r\n + change.getPrefix() + \">)\");\r\n }\r\n\r\n public final String render(final RemovePrefixData change) {\r\n return indentString(\"-\", \"Prefix(\" + change.getPrefixName() + \"=<\"\r\n + change.getPrefix() + \">)\");\r\n }\r\n\r\n public final String render(final ModifyPrefixData change) {\r\n return indentString(\"*\", \"Prefix(\" + change.getPrefixName() + \"=<\"\r\n + change.getOldPrefix() + \"> <\" + change.getPrefix() + \">)\");\r\n }\r\n\r\n public final String render(final RenamePrefixData change) {\r\n return indentString(\"#\", \"Prefix(\" + change.getOldPrefixName() + \" \"\r\n + change.getPrefixName() + \"=<\"\r\n + change.getPrefix() + \">)\");\r\n }\r\n\r\n private String renderOntologyId(final OWLOntologyID id) {\r\n if (id.isAnonymous())\r\n return \"\";\r\n else {\r\n final StringBuilder sb = new StringBuilder();\r\n sb.append(id.getOntologyIRI().toQuotedString());\r\n if (id.getVersionIRI() != null) {\r\n sb.append(\" \");\r\n sb.append(id.getVersionIRI().toQuotedString());\r\n }\r\n return sb.toString();\r\n }\r\n }\r\n\r\n public final String render(final SetOntologyIDData change) {\r\n final OWLOntologyID newid = change.getNewId();\r\n return indentString(\"*\", \"OntologyID(\" + renderOntologyId(newid) + \")\");\r\n }\r\n\r\n public final String render(final AddImportData change) {\r\n return indentString(\"+\", \"Import(<\"\r\n + change.getDeclaration().getIRI().toString() + \">)\");\r\n }\r\n\r\n public final String render(final RemoveImportData change) {\r\n return indentString(\"-\", \"Import(<\"\r\n + change.getDeclaration().getIRI().toString() + \">)\");\r\n }\r\n\r\n public final String render(final AddOntologyAnnotationData change) {\r\n return indentString(\"+\", objectRenderer.render(change.getAnnotation()));\r\n }\r\n\r\n public final String render(final RemoveOntologyAnnotationData change) {\r\n return indentString(\"-\", objectRenderer.render(change.getAnnotation()));\r\n }\r\n\r\n public final String render(final AddAxiomData change) {\r\n return indentString(\"+\", objectRenderer.render(change.getAxiom()));\r\n }\r\n\r\n public final String render(final RemoveAxiomData change) {\r\n return indentString(\"-\", objectRenderer.render(change.getAxiom()));\r\n }\r\n\r\n private String writeIndent(final StringBuilder sb, final int indent) {\r\n sb.append(\"\\n\");\r\n for (int i = 0; i < indent; i++)\r\n sb.append(\" \");\r\n return sb.toString();\r\n }\r\n\r\n protected final String indentString(final String prefix,\r\n final String compactString) {\r\n String indentedString = compactString;\r\n if (changeFormat == ChangeFormat.INDENTED) {\r\n final int indentSize = 2;\r\n final StringBuilder sb = new StringBuilder();\r\n int indent;\r\n if (prefix != null)\r\n indent = prefix.length() + 1;\r\n else\r\n indent = 0;\r\n boolean quote = false;\r\n for (final char c : compactString.toCharArray())\r\n switch (c) {\r\n case '(':\r\n indent += indentSize;\r\n // sb.append(':');\r\n writeIndent(sb, indent);\r\n break;\r\n case ')':\r\n indent -= indentSize;\r\n writeIndent(sb, indent);\r\n break;\r\n case ' ':\r\n if (quote)\r\n sb.append(c);\r\n else\r\n writeIndent(sb, indent);\r\n break;\r\n case '\"':\r\n quote = !quote;\r\n default:\r\n sb.append(c);\r\n }\r\n indentedString = sb.toString().trim();\r\n }\r\n if (prefix == null)\r\n return indentedString;\r\n else\r\n return prefix + \" \" + indentedString;\r\n }\r\n\r\n @Override\r\n public Character getSymbol(OWLOntologyChangeData change) {\r\n if (change == null)\r\n return '?';\r\n // Standard changes\r\n if (change instanceof SetOntologyFormatData)\r\n return '*';\r\n else if (change instanceof AddPrefixData)\r\n return '+';\r\n else if (change instanceof RemovePrefixData)\r\n return '-';\r\n else if (change instanceof ModifyPrefixData)\r\n return '*';\r\n else if (change instanceof RenamePrefixData)\r\n return '#';\r\n // Custom changes\r\n else if (change instanceof SetOntologyIDData)\r\n return '*';\r\n else if (change instanceof AddImportData)\r\n return '+';\r\n else if (change instanceof RemoveImportData)\r\n return '-';\r\n else if (change instanceof AddOntologyAnnotationData)\r\n return '+';\r\n else if (change instanceof RemoveOntologyAnnotationData)\r\n return '-';\r\n else if (change instanceof AddAxiomData)\r\n return '+';\r\n else if (change instanceof RemoveAxiomData)\r\n return '-';\r\n else\r\n return '?';\r\n }\r\n}\r" ]
import java.io.PrintStream; import java.io.UnsupportedEncodingException; import org.semanticweb.owlapi.change.OWLOntologyChangeData; import org.semanticweb.owlapi.util.ShortFormProvider; import owl2vcs.changeset.ChangeSet; import owl2vcs.render.ChangeFormat; import owl2vcs.render.ChangeRenderer; import owl2vcs.render.FullFormProvider; import owl2vcs.render.FunctionalChangeRenderer;
package owl2vcs.io; public class FunctionalChangesetSerializer { public void write(ChangeSet cs, PrintStream out) {
write(cs, out, new FullFormProvider(), ChangeFormat.COMPACT);
1
KodeMunkie/imagetozxspec
src/main/java/uk/co/silentsoftware/core/converters/spectrum/TapeConverter.java
[ "public static byte[] copyBytes(byte[] from, byte[] to, int fromIndex) {\n\tSystem.arraycopy(from, 0, to, fromIndex, from.length);\n\treturn to;\n}", "public static byte getChecksum(byte[] bytes) {\n\tint checksum = 0;\n\tfor (byte b: bytes) {\n\t\tchecksum^=b;\n\t}\n\treturn (byte)checksum;\n}\t", "public static void put(ByteBuffer bb, byte[] bytes, int from) {\n\tint counter = 0;\n\tfor (byte b : bytes) {\n\t\tbb.put(from+counter, b);\n\t\t++counter;\n\t}\n}", "public class OptionsObject {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(OptionsObject.class);\n\t\n\t/**\n\t * The version of preferences\n\t */\n\t@PreferencesField\n\tprivate int prefsVersion = 1;\n\t\n\t/**\n\t * The number of starts this app has had\n\t */\n\t@PreferencesField\n\tprivate int starts = 0;\n\t\n\t/**\n\t * Path to the VLC binary\n\t */\n\t@PreferencesField\n\tprivate String pathToVideoEngineLibrary = null;\n\n\t/**\n\t * The number of frames to sample from the video per second\n\t */\n\t@PreferencesField\n\tprivate volatile double videoFramesPerSecond = 10;\n\n\t/**\n\t * The number of milliseconds delay for each gif frame\n\t */\n\t@PreferencesField\n\tprivate volatile int gifDisplayTimeMillis = 100;\n\n\t/**\n\t * CPU time is diverted more to processing than rendering or other less important tasks\n\t */\n\t@PreferencesField\n\tprivate volatile boolean turboMode = false;\n\n\t/**\n\t * Prefix identifier for custom basic loaders\n\t */\n\tpublic final static String CUSTOM_LOADER_PREFIX = getCaption(\"loader_custom\") + \" \";\n\n\t/**\n\t * Basic loader for slideshows/video (tap output)\n\t */\n\tprivate final List<BasicLoader> basicLoaders;\n\t{\n\t\tbasicLoaders = new ArrayList<>();\n\t\tbasicLoaders.add(new BasicLoader(getCaption(\"loader_simple\"), \"/simple.tap\"));\n\t\tbasicLoaders.add(new BasicLoader(getCaption(\"loader_buffered\"), \"/buffered.tap\"));\n\t\tbasicLoaders.add(new BasicLoader(getCaption(\"loader_gigascreen\"), \"/gigascreen.tap\"));\n\t\tbasicLoaders.add(new BasicLoader(CUSTOM_LOADER_PREFIX, null));\n\t}\n\n\t/**\n\t * The chosen basic loader\n\t */\n\t@PreferencesField\n\tprivate volatile int basicLoader = 0;\n\n\t/**\n\t * Error diffusion dither strategies available\n\t */\n\tprivate final List<ErrorDiffusionDitherStrategy> errorDithers;\n\t{\n\t\terrorDithers = new ArrayList<>();\n\t\terrorDithers.add(new AtkinsonDitherStrategy());\n\t\terrorDithers.add(new BurkesDitherStrategy());\n\t\terrorDithers.add(new FloydSteinbergDitherStrategy());\n\t\terrorDithers.add(new JarvisJudiceNinkeDitherStrategy());\n\t\terrorDithers.add(new LowErrorAtkinsonDitherStrategy());\n\t\terrorDithers.add(new NoDitherStrategy());\n\t\terrorDithers.add(new SierraFilterLightStrategy());\n\t\terrorDithers.add(new StuckiDitherStrategy());\n\t}\n\n\t/**\n\t * Ordered dither strategies available\n\t */\n\tprivate final List<OrderedDitherStrategy> orderedDithers;\n\t{\n\t\torderedDithers = new ArrayList<>();\n\t\torderedDithers.add(new BayerTwoByOneOrderedDitherStrategy());\n\t\torderedDithers.add(new BayerTwoByTwoOrderedDitherStrategy());\n\t\torderedDithers.add(new OmegaOrderedDitherStrategy()); \n\t\torderedDithers.add(new BayerFourByFourDitherStrategy());\n\t\torderedDithers.add(new BayerEightByEightDitherStrategy());\n\t\torderedDithers.add(new MagicSquareDitherStrategy());\n\t\torderedDithers.add(new NasikMagicSquareDitherStrategy());\n\t}\n\n\t/**\n\t * Any non standard dither strategies (e.g character dither)\n\t */\n\tprivate final List<DitherStrategy> otherDithers;\n\t{\n\t\totherDithers = new ArrayList<>();\n\t\totherDithers.add(new CharacterDitherStrategy());\n\t}\n\t\n\t/**\n\t * The chosen dither strategy\n\t */\n\t@PreferencesField\n\tprivate volatile int selectedDitherStrategy = 0;\n\n\t/**\n\t * The chosen dither strategy type\n\t */\n\t@PreferencesField\n\tprivate volatile String selectedDitherStrategyType = ErrorDiffusionDitherStrategy.class.getName();\n\n\tpublic final static ScalingObject INTERLACED = new ScalingObject(getCaption(\"scaling_interlace\"),\n\t\t\tSpectrumDefaults.SCREEN_WIDTH, SpectrumDefaults.SCREEN_HEIGHT*2);\n\n\t/**\n\t * Scaling modes available\n\t */\n\tprivate final List<ScalingObject> scalings;\n\t{\n\t\tscalings = new ArrayList<>();\n\t\tscalings.add(new ScalingObject(getCaption(\"scaling_default\"), SpectrumDefaults.SCREEN_WIDTH, SpectrumDefaults.SCREEN_HEIGHT));\n\t\tscalings.add(INTERLACED);\n\t\tscalings.add(new ScalingObject(getCaption(\"scaling_none\"), -1, -1));\n\t\tscalings.add(new ScalingObject(getCaption(\"scaling_width_prop\"), SpectrumDefaults.SCREEN_WIDTH, -1));\n\t\tscalings.add(new ScalingObject(getCaption(\"scaling_height_prop\"), -1, SpectrumDefaults.SCREEN_HEIGHT));\n\t}\n\n\t/**\n\t * ZX Spectrum scaling mode\n\t */\n\tpublic final ScalingObject zxScaling = scalings.get(0);\t\n\t\n\t/**\n\t * Currently selected scaling mode\n\t */\n\t@PreferencesField\n\tpublic volatile int scaling = 0;\n\n\tpublic static final GigaScreenPaletteStrategy GIGASCREEN_PALETTE_STRATEGY = new GigaScreenPaletteStrategy();\n\n\t/**\n\t * Pixel colouring strategy - akin to screen modes on the Spectrum\n\t * i.e. 2, 15 or 102 colours.\n\t */\n\tprivate final List<ColourChoiceStrategy> colourModes;\n\t{\n\t\tcolourModes = new ArrayList<>();\n\t\tcolourModes.add(new FullPaletteStrategy());\n\t\tcolourModes.add(GIGASCREEN_PALETTE_STRATEGY);\n\t\tcolourModes.add(new MonochromePaletteStrategy());\n\t}\n\n\t/**\n\t * Currently selected pixel colouring strategy\n\t */\n\t@PreferencesField\n\tprivate volatile int colourMode = 0;\n\n\t/**\n\t * Attribute favouritism choice - when colours need to be changed to a two\n\t * colour attribute block of 8x8 what is favoured?\n\t */\n\tprivate final List<AttributeStrategy> attributeModes;\n\t{\n\t\tattributeModes = new ArrayList<>();\n\t\tattributeModes.add(new FavourHalfBrightAttributeStrategy());\n\t\tattributeModes.add(new FavourBrightAttributeStrategy());\n\t\tattributeModes.add(new FavourMostPopularAttributeStrategy());\n\t\tattributeModes.add(new ForceHalfBrightAttributeStrategy()); \n\t\tattributeModes.add(new ForceBrightAttributeStrategy());\n\t\tattributeModes.add(new ForceReducedHalfBrightAttributeStrategy());\n\t};\n\n\t/**\n\t * Currently selected attribute favouritism mode\n\t */\n\t@PreferencesField\n\tprivate volatile int attributeMode = 0;\n\n\t/**\n\t * Attribute favouritism choice for Gigascreen. This is similar to the regular\n\t * attribute modes but needs to take account for the fact that the extra\n\t * colours are created by using two Spectrum screens (e.g. black+white full bright = grey)\n\t */\n\tprivate final List<GigaScreenAttributeStrategy> gigaScreenAttributeModes;\n\t{\n\t\tgigaScreenAttributeModes = new ArrayList<>();\n\t\tgigaScreenAttributeModes.add(new GigaScreenHalfBrightPaletteStrategy());\n\t\tgigaScreenAttributeModes.add(new GigaScreenBrightPaletteStrategy());\n\t\tgigaScreenAttributeModes.add(new GigaScreenMixedPaletteStrategy());\n\t};\n\n\tprivate final List<ColourDistanceStrategy> colourDistancesModes;\n\t{\n\t\tcolourDistancesModes = new ArrayList<>();\n\t\tcolourDistancesModes.add(new CompuphaseColourDistanceStrategy());\n\t\tcolourDistancesModes.add(new ClassicColourDistanceStrategy());\n\t\tcolourDistancesModes.add(new EuclideanColourDistance());\n\t}\n\n\t/**\n\t * Currently selected gigascreen attribute mode\n\t */\n\t@PreferencesField\n\tprivate volatile int gigaScreenAttributeMode = 0;\n\n\t/**\n\t * The chosen giga screen hsb option \n\t */\n\t@PreferencesField\n\tprivate volatile String gigaScreenPaletteOrder = GigaScreenPaletteOrder.Luminosity.name();\n\n\t/**\n\t * The video converting libraries supported\n\t */\n\tprivate final List<VideoImportEngine> videoImportEngines;\n\t{\n\t\tvideoImportEngines = new ArrayList<>();\n\t\tvideoImportEngines.add(new HumbleVideoImportEngine());\n\t\t\n\t\t// VLCJ doesn't work on MacOS.\n\t\tif (SystemUtils.IS_OS_MAC_OSX) {\n\t\t\tlog.info(\"Disabling VLCJ import engine - not supported on OSX\");\n\t\t} else {\n\t\t\tvideoImportEngines.add(new VLCVideoImportEngine());\n\t\t}\n\t};\n\n\t/**\n\t * Currently selected video converter\n\t */\n\t@PreferencesField\n\tprivate volatile int videoImportEngine = 0;\n\n\t/**\n\t * Display frames per second\n\t */\n\t@PreferencesField\n\tprivate volatile boolean fpsCounter = false;\n\n\t/**\n\t * Display frames per second\n\t */\n\t@PreferencesField\n\tprivate volatile boolean showWipPreview = true;\n\n\t/**\n\t * Export image formats available\n\t */\n\tprivate final String[] imageFormats = new String[] { \"png\", \"jpg\" };\n\n\t/**\n\t * Currently selected image export format\n\t */\n\t@PreferencesField\n\tprivate volatile String imageFormat = imageFormats[0];\n\n\t/**\n\t * Image pre-process contrast setting\n\t */\n\t@PreferencesField\n\tprivate volatile float contrast = 1;\n\n\t/**\n\t * Image pre-process brightness setting\n\t */\n\t@PreferencesField\n\tprivate volatile float brightness = 0;\n\n\t/**\n\t * Image pre-process saturation setting\n\t */\n\t@PreferencesField\n\tprivate volatile float saturation = 0;\n\n\t/**\n\t * Monochrome b/w threshold - determines what value a colour rgb values\n\t * must all be below for it to be considered black\n\t */\n\t@PreferencesField\n\tprivate volatile int blackThreshold = 128;\n\n\t/**\n\t * Flag for allowing regular image export\n\t */\n\t@PreferencesField\n\tprivate volatile boolean exportImage = true;\n\n\t/**\n\t * Flag for allowing Spectrum screen file export\n\t */\n\t@PreferencesField\n\tprivate volatile boolean exportScreen = false;\n\n\t/**\n\t * Flag for allowing Spectrum tape (slideshow) file export\n\t */\n\t@PreferencesField\n\tprivate volatile boolean exportTape = false;\n\n\t/**\n\t * Flag to export an anim gif\n\t */\n\t@PreferencesField\n\tprivate volatile boolean exportAnimGif = false;\n\n\t/**\n\t * Flag to export a text dither as a text file\n\t */\n\t@PreferencesField\n\tprivate volatile boolean exportText = false;\n\n\t/**\n\t * The monochrome mode ink colour (spectrum palette index)\n\t */\n\t@PreferencesField\n\tprivate volatile int monochromeInkIndex = 0;\n\n\t/**\n\t * The monochrome mode paper colour (spectrum palette index)\n\t */\n\t@PreferencesField\n\tprivate volatile int monochromePaperIndex = 7;\n\n\t/**\n\t * Intensity for ordered dithering\n\t */\n\t@PreferencesField\n\tprivate volatile int orderedDitherIntensity = 1;\n\n\t/**\n\t * Serpentine dithering mode (image rows traversed \n\t * in alternate directions)\n\t */\n\t@PreferencesField\n\tprivate volatile boolean serpentine = false;\n\n\t/**\n\t * Constrains the error of the error diffusion to \n\t * 8x8 pixels (a single attribute block). Can lead\n\t * to a grid pattern effect.\n\t */\n\t@PreferencesField\n\tprivate volatile boolean constrainedErrorDiffusion = false;\n\n\t/**\n\t * Algorithm to compare colour likeness\n\t */\n\t@PreferencesField\n\tprivate volatile int colourDistanceStrategy = 0;\n\n\t/**\n\t * Singleton instance of this class\n\t */\n\tprivate final static OptionsObject instance;\n\n\tstatic {\n\t\tOptional<OptionsObject> tempRef = PreferencesService.load();\n\t\tif (tempRef.isPresent()) {\n\t\t\tinstance = tempRef.get();\n\t\t} else {\n\t\t\tinstance = new OptionsObject();\n\t\t}\n\t\t// Start this early as some engines take a number of seconds to load\n\t\tinstance.getVideoImportEngine().initVideoImportEngine(Optional.ofNullable(instance.getPathToVideoEngineLibrary()));\n\t\tlog.info(\"Options initialised\");\n\t}\n\t\n\t/**\n\t * Retrieves the only option object instance\n\t * \n\t * @return the singleton instance of this object\n\t */\n\tpublic static OptionsObject getInstance() {\n\t\tif (instance == null) {\n\t\t\tlog.error(\"Options instance is null!\");\n\t\t}\n\t\treturn instance;\n\t}\n\t\n\tpublic int getStarts() {\n\t\treturn starts;\n\t}\n\n\tpublic void setStarts(int starts) {\n\t\tthis.starts = starts;\n\t}\n\n\tpublic void setTurboMode(boolean turbo) {\n\t\tthis.turboMode = turbo;\n\t}\n\t\n\tpublic boolean getTurboMode() {\n\t\treturn turboMode;\n\t}\t\n\t\n\tpublic ErrorDiffusionDitherStrategy[] getErrorDithers() {\n\t\treturn errorDithers.toArray(new ErrorDiffusionDitherStrategy[0]);\n\t}\n\n\tpublic ScalingObject[] getScalings() {\n\t\treturn scalings.toArray(new ScalingObject[0]);\n\t}\n\n\tpublic ScalingObject getScaling() {\n\t\treturn scalings.get(scaling);\n\t}\n\n\tpublic ScalingObject getZXDefaultScaling() {\n\t\treturn zxScaling;\n\t}\n\n\tpublic void setScaling(ScalingObject scaling) {\n\t\tthis.scaling = scalings.indexOf(scaling);\n\t}\n\n\tpublic float getContrast() {\n\t\treturn contrast;\n\t}\n\n\tpublic void setContrast(float contrast) {\n\t\tthis.contrast = contrast;\n\t}\n\n\tpublic float getBrightness() {\n\t\treturn brightness;\n\t}\n\n\tpublic void setBrightness(float brightness) {\n\t\tthis.brightness = brightness;\n\t}\n\n\tpublic float getSaturation() {\n\t\treturn saturation;\n\t}\n\n\tpublic void setSaturation(float saturation) {\n\t\tthis.saturation = saturation;\n\t}\n\n\tpublic void setFpsCounter(boolean fpsCounter) {\n\t\tthis.fpsCounter = fpsCounter;\n\t}\n\n\tpublic void setShowWipPreview(boolean showWipPreview) {\n\t\tthis.showWipPreview = showWipPreview;\n\t}\n\n\tpublic String getImageFormat() {\n\t\treturn imageFormat;\n\t}\n\n\tpublic void setImageFormat(String imageFormat) {\n\t\tthis.imageFormat = imageFormat;\n\t}\n\n\tpublic String[] getImageFormats() {\n\t\treturn imageFormats;\n\t}\n\n\tpublic boolean getFpsCounter() {\n\t\treturn fpsCounter;\n\t}\n\n\tpublic boolean getShowWipPreview() {\n\t\treturn showWipPreview;\n\t}\n\n\tpublic boolean getExportImage() {\n\t\treturn exportImage;\n\t}\n\n\tpublic void setExportImage(boolean exportImage) {\n\t\tthis.exportImage = exportImage;\n\t}\n\n\tpublic boolean getExportScreen() {\n\t\treturn exportScreen;\n\t}\n\n\tpublic void setExportScreen(boolean exportScreen) {\n\t\tthis.exportScreen = exportScreen;\n\t}\n\n\tpublic boolean getExportAnimGif() {\n\t\treturn exportAnimGif;\n\t}\n\n\tpublic void setExportAnimGif(boolean exportAnimGif) {\n\t\tthis.exportAnimGif = exportAnimGif;\n\t}\n\n\tpublic boolean getExportText() {\n\t\treturn exportText;\n\t}\n\n\tpublic void setExportText(boolean exportText) {\n\t\tthis.exportText = exportText;\n\t}\n\n\tpublic boolean getExportTape() {\n\t\treturn exportTape;\n\t}\n\n\tpublic void setExportTape(boolean exportTape) {\n\t\tthis.exportTape = exportTape;\n\t}\n\n\tpublic ColourChoiceStrategy getColourMode() {\n\t\treturn colourModes.get(colourMode);\n\t}\n\n\tpublic void setColourMode(ColourChoiceStrategy colourMode) {\n\t\tthis.colourMode = colourModes.indexOf(colourMode);\n\t}\n\n\tpublic ColourChoiceStrategy[] getColourModes() {\n\t\treturn colourModes.toArray(new ColourChoiceStrategy[0]);\n\t}\n\n\tpublic int getMonochromeInkIndex() {\n\t\treturn monochromeInkIndex;\n\t}\n\n\tpublic void setMonochromeInkIndex(int monochromeInkIndex) {\n\t\tthis.monochromeInkIndex = monochromeInkIndex;\n\t}\n\n\tpublic int getMonochromePaperIndex() {\n\t\treturn monochromePaperIndex;\n\t}\n\n\tpublic void setMonochromePaperIndex(int monochromePaperIndex) {\n\t\tthis.monochromePaperIndex = monochromePaperIndex;\n\t}\n\n\tpublic int getBlackThreshold() {\n\t\treturn blackThreshold;\n\t}\n\n\tpublic void setBlackThreshold(int blackThreshold) {\n\t\tthis.blackThreshold = blackThreshold;\n\t}\n\n\tpublic OrderedDitherStrategy[] getOrderedDithers() {\n\t\treturn orderedDithers.toArray(new OrderedDitherStrategy[0]);\n\t}\n\n\tpublic DitherStrategy[] getOtherDithers() {\n\t\treturn otherDithers.toArray(new DitherStrategy[0]);\n\t}\n\t\n\tpublic DitherStrategy getSelectedDitherStrategy() {\n\t\tif (ErrorDiffusionDitherStrategy.class.getName().equals(selectedDitherStrategyType)) {\n\t\t\treturn errorDithers.get(selectedDitherStrategy);\n\t\t}\n\t\tif (OrderedDitherStrategy.class.getName().equals(selectedDitherStrategyType)) {\n\t\t\treturn orderedDithers.get(selectedDitherStrategy);\n\t\t}\n\t\tif (CharacterDitherStrategy.class.getName().equals(selectedDitherStrategyType)) {\n\t\t\treturn otherDithers.get(selectedDitherStrategy);\n\t\t}\n\t\tthrow new IllegalStateException(\"Unknown dither strategy \"+selectedDitherStrategy);\n\t}\n\n\tpublic void setSelectedDitherStrategy(DitherStrategy selectedDitherStrategy) {\n\t\tif (errorDithers.contains(selectedDitherStrategy)) {\n\t\t\tthis.selectedDitherStrategy = errorDithers.indexOf(selectedDitherStrategy);\n\t\t\tthis.selectedDitherStrategyType = ErrorDiffusionDitherStrategy.class.getName();\n\t\t}\n\t\tif (orderedDithers.contains(selectedDitherStrategy)) {\n\t\t\tthis.selectedDitherStrategy = orderedDithers.indexOf(selectedDitherStrategy);\n\t\t\tthis.selectedDitherStrategyType = OrderedDitherStrategy.class.getName();\n\t\t}\n\t\tif (otherDithers.contains(selectedDitherStrategy)) {\n\t\t\tthis.selectedDitherStrategy = otherDithers.indexOf(selectedDitherStrategy);\n\t\t\tthis.selectedDitherStrategyType = CharacterDitherStrategy.class.getName();\n\t\t}\n\t}\n\n\tpublic int getOrderedDitherIntensity() {\n\t\treturn orderedDitherIntensity;\n\t}\n\n\tpublic void setOrderedDitherIntensity(int orderedDitherIntensity) {\n\t\tthis.orderedDitherIntensity = orderedDitherIntensity;\n\t}\n\n\tpublic AttributeStrategy getAttributeMode() {\n\t\treturn attributeModes.get(attributeMode);\n\t}\n\n\tpublic void setAttributeMode(AttributeStrategy attributeMode) {\n\t\tthis.attributeMode = attributeModes.indexOf(attributeMode);\n\t}\n\n\tpublic AttributeStrategy[] getAttributeModes() {\n\t\treturn attributeModes.toArray(new AttributeStrategy[0]);\n\t}\n\n\tpublic BasicLoader[] getBasicLoaders() {\n\t\treturn basicLoaders.toArray(new BasicLoader[0]);\n\t}\n\n\tpublic BasicLoader getBasicLoader() {\n\t\treturn basicLoaders.get(basicLoader);\n\t}\n\n\tpublic void setBasicLoader(BasicLoader basicLoader) {\n\t\tthis.basicLoader = basicLoaders.indexOf(basicLoader);\n\t}\n\n\tpublic double getVideoFramesPerSecond() {\n\t\treturn videoFramesPerSecond;\n\t}\n\n\tpublic void setVideoFramesPerSecond(double videoFramesPerSecond) {\n\t\tthis.videoFramesPerSecond = videoFramesPerSecond;\n\t}\n\n\tpublic int getGifDisplayTimeMillis() {\n\t\treturn gifDisplayTimeMillis;\n\t}\n\n\tpublic void setGifDisplayTimeMillis(int gifDisplayTimeMillis) {\n\t\tthis.gifDisplayTimeMillis = gifDisplayTimeMillis;\n\t}\n\n\tpublic boolean getSerpentine() {\n\t\treturn serpentine;\n\t}\n\n\tpublic void setSerpentine(boolean serpentine) {\n\t\tthis.serpentine = serpentine;\n\t}\n\n\tpublic boolean getConstrainedErrorDiffusion() {\n\t\treturn constrainedErrorDiffusion;\n\t}\n\n\tpublic void setConstrainedErrorDiffusion(boolean constrainedErrorDiffusion) {\n\t\tthis.constrainedErrorDiffusion = constrainedErrorDiffusion;\n\t}\n\n\tpublic VideoImportEngine getVideoImportEngine() {\n\t\treturn videoImportEngines.get(videoImportEngine);\n\t}\n\n\tpublic void setVideoImportEngine(VideoImportEngine videoImportEngine) {\n\t\tthis.videoImportEngine = videoImportEngines.indexOf(videoImportEngine);\n\t}\n\n\tpublic VideoImportEngine[] getVideoImportEngines() {\n\t\treturn videoImportEngines.toArray(new VideoImportEngine[0]);\n\t}\n\n\tpublic String getPathToVideoEngineLibrary() {\n\t\treturn pathToVideoEngineLibrary;\n\t}\n\n\tpublic void setPathToVideoEngineLibrary(String path) {\n\t\tthis.pathToVideoEngineLibrary = path;\n\t}\n\n\tpublic GigaScreenAttributeStrategy[] getGigaScreenAttributeStrategies() {\n\t\treturn gigaScreenAttributeModes.toArray(new GigaScreenAttributeStrategy[0]);\n\t}\n\n\tpublic GigaScreenAttributeStrategy getGigaScreenAttributeStrategy() {\n\t\treturn gigaScreenAttributeModes.get(gigaScreenAttributeMode);\n\t}\n\n\tpublic void setGigaScreenAttributeStrategy(GigaScreenAttributeStrategy gigaScreenAttributeStrategy) {\n\t\tthis.gigaScreenAttributeMode = gigaScreenAttributeModes.indexOf(gigaScreenAttributeStrategy);\n\t}\n\n\tpublic GigaScreenPaletteOrder[] getGigaScreenPaletteOrders() {\n\t\treturn GigaScreenPaletteOrder.values();\n\t}\n\n\tpublic GigaScreenPaletteOrder getGigaScreenPaletteOrder() {\n\t\treturn GigaScreenPaletteOrder.valueOf(gigaScreenPaletteOrder);\n\t}\n\n\tpublic void setGigaScreenPaletteOrder(GigaScreenPaletteOrder gigaScreenAttributeOrderingOption) {\n\t\tthis.gigaScreenPaletteOrder = gigaScreenAttributeOrderingOption.name();\n\t}\n\n\tpublic ColourDistanceStrategy getColourDistanceMode() {\n\t\treturn colourDistancesModes.get(colourDistanceStrategy);\n\t}\n\n\tpublic ColourDistanceStrategy[] getColourDistances() {\n\t\treturn colourDistancesModes.toArray(new ColourDistanceStrategy[0]);\n\t}\n\n\tpublic void setColourDistanceStrategy(ColourDistanceStrategy colourDistanceStrategy) {\n\t\tthis.colourDistanceStrategy = colourDistancesModes.indexOf(colourDistanceStrategy);\n\t}\n}", "public final class ByteHelper {\n\n\t/**\n\t * Private constructor since we want static use only\n\t */\n\tprivate ByteHelper(){}\n\n\t/**\n\t * Noddy method to reverse a BitSet. \n\t * Basically this is just to fix the endianness of\n\t * the image bits since bitset doesn't provide a\n\t * means of changing the bit (not byte) endianness\n\t * \n\t * @param bs the bitset to change the endianness of (by reference)\n\t * @return the reversed bitset\n\t */\n\tpublic static BitSet reverseBitSet(BitSet bs) {\n\t\tfinal BitSet copy = new BitSet(8);\n\t\tint counter = 0;\n\t\tint size = bs.length();\n\t\t// For all bits\n\t\tfor (int i = 0; i < size; ++i) {\n\t\t\t\n\t\t\t// If at the end of a byte\n\t\t\tif (i % 8 == 0 && i != 0) {\n\t\t\t\t\n\t\t\t\t// Read all the bits in reverse order\n\t\t\t\tfor (int j=8; j>=1; j--) {\n\t\t\t\t\t\n\t\t\t\t\t// Zero the original range \n\t\t\t\t\tbs.clear(i-j);\n\t\t\t\t\t\n\t\t\t\t\t// Copy the current byte (in reverse order) back to the original\n\t\t\t\t\tif (copy.get(j-1)){\n\t\t\t\t\t\tbs.set(i-j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Zero the copy completely to start on the next byte\n\t\t\t\tcopy.clear();\n\t\t\t\tcounter = 0;\n\t\t\t}\n\t\t\t\n\t\t\t// Copy the bits in the same order into a copy\n\t\t\tif (bs.get(i)) {\n\t\t\t\tcopy.set(counter);\n\t\t\t}\n\t\t\t++counter;\t\t\n\t\t}\n\t\treturn bs;\n\t}\n\t\n\t/**\n\t * Copy bytes completely from a source byte array to \n\t * a destination byte array starting at the fromIndex\n\n\t * @param from the array to copy from \n\t * @param to the array to copy to\n\t * @param fromIndex the destination array index to start copy to\n\t * @return the copied byte array\n\t */\n\tpublic static byte[] copyBytes(byte[] from, byte[] to, int fromIndex) {\n\t\tSystem.arraycopy(from, 0, to, fromIndex, from.length);\n\t\treturn to;\n\t}\n\t\n\t/**\n\t * The missing method on a ByteBuffer - allows copying\n\t * of multiple bytes into the buffer at a buffer offset\n\t * \n\t * @param bb the byte buffer to copy the array into\n\t * @param bytes the bytes to copy\n\t * @param from the offset into the bytebuffer from which to copy\n\t */\n\tpublic static void put(ByteBuffer bb, byte[] bytes, int from) {\n\t\tint counter = 0;\n\t\tfor (byte b : bytes) {\n\t\t\tbb.put(from+counter, b);\n\t\t\t++counter;\n\t\t}\n\t}\n\t\n\t/**\n\t * Implementation of an XOR checksum\n\t * \n\t * @param bytes the bytes to xor\n\t * @return the xor result\n\t */\n\tpublic static byte getChecksum(byte[] bytes) {\n\t\tint checksum = 0;\n\t\tfor (byte b: bytes) {\n\t\t\tchecksum^=b;\n\t\t}\n\t\treturn (byte)checksum;\n\t}\t\n}" ]
import uk.co.silentsoftware.config.OptionsObject; import uk.co.silentsoftware.core.helpers.ByteHelper; import static uk.co.silentsoftware.core.helpers.ByteHelper.copyBytes; import static uk.co.silentsoftware.core.helpers.ByteHelper.getChecksum; import static uk.co.silentsoftware.core.helpers.ByteHelper.put; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* Image to ZX Spec * Copyright (C) 2019 Silent Software (Benjamin Brown) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.silentsoftware.core.converters.spectrum; /** * Converter to output a Tape image format file (.tap) */ public class TapeConverter { private final Logger log = LoggerFactory.getLogger(this.getClass()); /** * Outputs an SCR format image into a tap file part * (i.e. a standard data block). * * @see <a href="http://www.zx-modules.de/fileformats/tapformat.html">http://www.zx-modules.de/fileformats/tapformat.html</a> * * @param image the SCR image data to add to the tap file * @return the tap file section containing the Spectrum encoded image */ public byte[] createTapPart(byte[] image) { // Standard ROM data block header ByteBuffer imageData = ByteBuffer.allocate(2+image.length); imageData.order(ByteOrder.LITTLE_ENDIAN); imageData.put(0, (byte)255); // 255 indicates ROM loading block - cast just for show put(imageData, image, 1); // SCR image data imageData.put(6913, getChecksum(imageData.array())); // XOR checksum // Screen header ByteBuffer imageHeader = ByteBuffer.allocate(19); imageHeader.order(ByteOrder.LITTLE_ENDIAN); imageHeader.put(0, (byte)0); // Indicates ROM header imageHeader.put(1, (byte)3); // Indicates BYTE header put(imageHeader, "Loading...".getBytes(), 2); // Program loading name imageHeader.putShort(12, (short)6912); // Length of data (should be 6912) imageHeader.putShort(14, (short)16384); // Start address to import to imageHeader.putShort(16, (short)32768); // Unused, must be 32768 imageHeader.put(18, getChecksum(imageHeader.array())); // XOR checksum // Copy image header block into data block sub block ByteBuffer imageHeaderBlock = ByteBuffer.allocate(2+imageHeader.array().length); imageHeaderBlock.order(ByteOrder.LITTLE_ENDIAN); imageHeaderBlock.putShort((short)(imageHeader.array().length)); put(imageHeaderBlock, imageHeader.array(), 2); // Copy image data into data block sub block ByteBuffer imageDataBlock = ByteBuffer.allocate(2+imageData.array().length); imageDataBlock.order(ByteOrder.LITTLE_ENDIAN); imageDataBlock.putShort((short)(imageData.array().length)); put(imageDataBlock, imageData.array(), 2); // Combined the header sub block and image data sub block and return the bytes byte[] b = new byte[imageHeaderBlock.array().length+imageDataBlock.array().length]; b = copyBytes(imageHeaderBlock.array(), b, 0); b = copyBytes(imageDataBlock.array(), b, imageHeaderBlock.array().length); return b; } /** * Returns a the new tap file bytes containing * a basic SCR loader followed by the SCR images * that have been already converted to TAP parts * * @param parts the TAP parts (data blocks) contain SCR images * @return the entire tap file as bytes */ public byte[] createTap(List<byte[]> parts) { byte[] loader = createLoader(); int size = loader.length; for (byte[] b: parts) { size+=b.length; } byte[] result = new byte[size]; ByteHelper.copyBytes(loader, result, 0); int index = loader.length; for (byte[] b: parts) { ByteHelper.copyBytes(b, result, index); index += b.length; } return result; } /** * Creates and returns the TAP loader from the options * selected loader file. N.b this byte data will already * be in little endian order. * * @return the byte data contained in the loader file */ private byte[] createLoader() {
OptionsObject oo = OptionsObject.getInstance();
3
ryft/NetVis
workspace/netvis/src/netvis/visualisations/DataflowVisualisation.java
[ "public class DataController implements ActionListener {\n\tDataFeeder dataFeeder;\n\tTimer timer;\n\tfinal List<DataControllerListener> listeners;\n\tfinal List<PacketFilter> filters;\n\tfinal List<Packet> allPackets;\n\tfinal List<Packet> filteredPackets;\n\tprivate int noUpdated = 0;\n\tprotected int intervalsComplete = 0;\n\tJPanel filterPanel;\n\n\t/**\n\t * @param dataFeeder\n\t * @param updateInterval\n\t * The time interval at which the data is updating.\n\t */\n\tpublic DataController(DataFeeder dataFeeder, int updateInterval) {\n\t\tthis.dataFeeder = dataFeeder;\n\t\tlisteners = new ArrayList<DataControllerListener>();\n\t\tfilters = new ArrayList<PacketFilter>();\n\t\tfilteredPackets = new ArrayList<Packet>();\n\t\tallPackets = new ArrayList<Packet>();\n\t\ttimer = new Timer(updateInterval, this);\n\t\tfilterPanel = new JPanel();\n\t\tNormaliseFactory.INSTANCE.setDataController(this);\n\t\tfilterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.Y_AXIS));\n\t\tfilterPanel.add(Box.createVerticalGlue());\n\t\ttimer.start();\n\t}\n\n\tpublic void FinishEverything() {\n\t\tthis.timer.stop();\n\t\tfor (DataControllerListener l : listeners)\n\t\t\tl.everythingEnds();\n\t}\n\n\tpublic void addListener(DataControllerListener listener) {\n\t\tlisteners.add(listener);\n\t}\n\n\tpublic void removeListener(DataControllerListener listener) {\n\t\tlisteners.remove(listener);\n\t}\n\n\tpublic void addFilter(PacketFilter packetFilter) {\n\t\tfilters.add(packetFilter);\n\t\tif (packetFilter instanceof FixedFilter) {\n\t\t\tJComponent comp = packetFilter.getPanel();\n\t\t\tcomp.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);\n\t\t\tfilterPanel.add(comp);\n\t\t}\n\t\tallDataChanged();\n\t}\n\n\tpublic void removeFilter(PacketFilter packetFilter) {\n\t\tfilters.remove(packetFilter);\n\t\tif (packetFilter instanceof FixedFilter) {\n\t\t\tfilterPanel.remove(packetFilter.getPanel());\n\t\t}\n\t\tallDataChanged();\n\t}\n\n\tpublic Iterator<PacketFilter> filterIterator() {\n\t\treturn filters.iterator();\n\t}\n\n\t/**\n\t * Returns all the packets with the filters applied\n\t */\n\tpublic List<Packet> getPackets() {\n\t\treturn Collections.unmodifiableList(filteredPackets);\n\t}\n\n\t/**\n\t * The action of the timer.\n\t */\n\t@Override\n\tpublic void actionPerformed(ActionEvent e) {\n\t\tList<Packet> newPackets = dataFeeder.getNewPackets();\n\n\t\tif (newPackets != null) {\n\t\t\tallPackets.addAll(newPackets); // First add the new packets to the\n\t\t\t\t\t\t\t\t\t\t\t// controller\n\t\t\tintervalsComplete++;\n\n\t\t\tapplyFilters(newPackets); // Then apply the filters to them\n\t\t\tfilteredPackets.addAll(newPackets);\n\n\t\t\tfor (DataControllerListener l : listeners)\n\t\t\t\tl.newPacketsArrived(newPackets);\n\t\t}\n\n\t\t// set timer interval to the one suggested by the feeder\n\t\ttimer.setDelay(dataFeeder.updateInterval());\n\n\t\t// If we've reached the end of the capture, stop the timer\n\t\tif (!dataFeeder.hasNext())\n\t\t\ttimer.stop();\n\t}\n\n\t// Redraw only when all the filters have applied their changes\n\tpublic void filterUpdated() {\n\t\tnoUpdated++;\n\t\tif (noUpdated == filters.size()) {\n\t\t\tallDataChanged();\n\t\t\tnoUpdated = 0;\n\t\t}\n\t}\n\n\t/**\n\t * \n\t * @param list\n\t * List to be filtered\n\t */\n\tprivate void applyFilters(List<Packet> list) {\n\t\tList<Packet> toBeRemoved = new ArrayList<Packet>();\n\t\tfor (PacketFilter f : filters)\n\t\t\tfor (Packet p : list)\n\t\t\t\tif (!f.filter(p))\n\t\t\t\t\ttoBeRemoved.add(p);\n\t\tlist.removeAll(toBeRemoved);\n\t}\n\n\t/**\n\t * Informs listeners that all the data has changed.\n\t */\n\tprivate void allDataChanged() {\n\t\tfilteredPackets.clear();\n\t\tfilteredPackets.addAll(allPackets);\n\t\tapplyFilters(filteredPackets);\n\n\t\tfor (DataControllerListener l : listeners)\n\t\t\tl.allDataChanged(filteredPackets, timer.getDelay(), intervalsComplete);\n\n\t\ttimer.start();\n\t}\n\n\t/**\n\t * Sets a new data feeder and resets the state of the controller and\n\t * listeners\n\t * \n\t * @param newDataFeeder\n\t * New data feeder\n\t */\n\tpublic void setDataFeeder(DataFeeder newDataFeeder) {\n\t\tthis.dataFeeder = newDataFeeder;\n\t\tthis.allPackets.clear();\n\t\tallDataChanged();\n\t}\n\n\tpublic DataFeeder getDataFeeder() {\n\t\treturn dataFeeder;\n\t}\n\n\tpublic JPanel fixedFiltersPanel() {\n\t\treturn filterPanel;\n\t}\n\n}", "public class NormaliseFactory {\n\tpublic static final NormaliseFactory INSTANCE = new NormaliseFactory();\n\n\tList<Normaliser> normalisers;\n\n\tprivate DataController dataController;\n\n\tprivate NormaliseFactory() {\n\t\tnormalisers = new ArrayList<Normaliser>();\n\t\tnormalisers.add(new SourceMACNorm());\n\t\tnormalisers.add(new SourceIPNorm());\n\t\tnormalisers.add(new SourcePortNorm());\n\t\tnormalisers.add(new DestinationPortNorm());\n\t\tnormalisers.add(new DestinationIPNorm());\n\t\tnormalisers.add(new DestinationMACNorm());\t\n\t\tnormalisers.add(new ProtocolNorm());\n\n\t}\n\n\tpublic List<Normaliser> getNormalisers() {\n\t\treturn normalisers;\n\t}\n\tpublic int getIndex(Normaliser n){\n\t\treturn normalisers.lastIndexOf(n);\n\t}\n\tpublic Normaliser getNormaliser(int norm_id) {\n\t\tif (norm_id < normalisers.size())\n\t\t\treturn normalisers.get(norm_id);\n\t\telse\n\t\t\treturn null;\n\t}\n\n\tpublic abstract class Normaliser {\n\t\tdouble lowerBound = 0, upperBound = 1;\n\t\tNormalisationFilter myFilter = null;\n\t\tprotected abstract double normaliseFunction(Packet p);\n\t\tprotected abstract String denormaliseFunction (double v);\n\t\tpublic abstract String name();\n\t\tpublic double normalise(Packet p){\n\t\t\tdouble v = this.normaliseFunction(p);\n\t\t\tv = (v - lowerBound)/(upperBound - lowerBound);\n\t\t\t//System.out.println(lowerBound);\n\t\t\t//System.out.println(v);\n\t\n\t\t\treturn v;\n\t\t}\n\t\tpublic String denormalise(double v){\n\t\t\tv = v * (upperBound - lowerBound);\n\t\t\tv += lowerBound;\n\t\t\treturn denormaliseFunction(v);\n\t\t}\n\t\tpublic void filter(double lowerBound, double upperBound){\t\t\n\t\t\tdouble interval = this.upperBound - this.lowerBound;\n\t\t\tthis.upperBound = this.lowerBound + upperBound*interval;\n\t\t\t\tif (this.upperBound > 1) this.upperBound = 1;\n\t\t\tthis.lowerBound += lowerBound*interval;\n\t\t\t\tif (this.lowerBound < 0) this.lowerBound = 0;\n\t\t\tif (myFilter != null)\n\t\t\t\tdataController.removeFilter(myFilter);\n\t\t\tmyFilter = new NormalisationFilter(this);\n\t\t\tdataController.addFilter(myFilter);\n\t\t}\n\t\tpublic void clearFilter() {\n\t\t\tthis.lowerBound = 0;\n\t\t\tthis.upperBound = 1;\n\t\t\tdataController.removeFilter(myFilter);\n\t\t\tmyFilter = null;\n\t\t}\n\t}\n\n\tprivate class SourcePortNorm extends Normaliser {\n\t\tpublic double normaliseFunction(Packet p) {\n\t\t\treturn DataUtilities.normalisePort(p.sport);\n\t\t}\n\n\t\tpublic String name() {\n\t\t\treturn \"Src Port\";\n\t\t}\n\n\t\t@Override\n\t\tpublic String denormaliseFunction(double v) {\n\t\t\treturn DataUtilities.denormalisePort(v);\n\t\t}\n\t}\n\n\tprivate class DestinationPortNorm extends Normaliser {\n\t\tpublic double normaliseFunction(Packet p) {\n\t\t\treturn DataUtilities.normalisePort(p.dport);\n\t\t}\n\n\t\tpublic String name() {\n\t\t\treturn \"Dest Port\";\n\t\t}\n\n\t\t@Override\n\t\tpublic String denormaliseFunction(double v) {\n\t\t\treturn DataUtilities.denormalisePort(v);\n\t\t}\n\t}\n\n\tprivate class SourceIPNorm extends Normaliser {\n\t\tpublic double normaliseFunction(Packet p) {\n\t\t\treturn DataUtilities.normaliseIP(p.sip);\n\t\t}\n\n\t\tpublic String name() {\n\t\t\treturn \"Src IP\";\n\t\t}\n\n\t\t@Override\n\t\tpublic String denormaliseFunction(double v) {\n\t\t\treturn DataUtilities.denormaliseIP(v);\n\t\t}\n\t}\n\n\tprivate class DestinationIPNorm extends Normaliser {\n\t\tpublic double normaliseFunction(Packet p) {\n\t\t\treturn DataUtilities.normaliseIP(p.dip);\n\t\t}\n\n\t\tpublic String name() {\n\t\t\treturn \"Dest IP\";\n\t\t}\n\n\t\t@Override\n\t\tpublic String denormaliseFunction(double v) {\n\t\t\treturn DataUtilities.denormaliseIP(v);\n\t\t}\n\t}\n\t\n\tprivate class SourceMACNorm extends Normaliser {\n\t\tpublic double normaliseFunction(Packet p) {\n\t\t\tif (DataUtilities.macMap.containsKey(p.smac))\n\t\t\t\treturn DataUtilities.macMap.get(p.smac);\n\t\t\telse {\n\t\t\t\tdouble value = DataUtilities.normaliseIP(p.sip);\n\t\t\t\tvalue += (Math.random()/100); \n\t\t\t\tif (value < 0) value = -value;\n\t\t\t\tif (value > 1) value = 2 - value;\n\t\t\t\tDataUtilities.macMap.put(p.smac, value);\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t}\n\n\t\tpublic String name() {\n\t\t\treturn \"Src MAC Address\";\n\t\t}\n\n\t\t@Override\n\t\tpublic String denormaliseFunction(double v) {\n\t\t\treturn String.valueOf(v);\n\t\t}\n\t}\n\tprivate class ProtocolNorm extends Normaliser {\n\n\t\t@Override\n\t\tprotected double normaliseFunction(Packet p) {\n\t\t\treturn DataUtilities.normaliseProtocol(p.protocol);\n\t\t}\n\n\t\t@Override\n\t\tprotected String denormaliseFunction(double v) {\n\t\t\treturn String.valueOf(v);\n\t\t}\n\n\t\t@Override\n\t\tpublic String name() {\n\t\t\t// TODO Auto-generated method stub\n\t\t\treturn \"Protocol\";\n\t\t}\n\t\t\n\t}\n\tprivate class DestinationMACNorm extends Normaliser {\n\t\tpublic double normaliseFunction(Packet p) {\n\t\t\treturn DataUtilities.normaliseMAC(p.dmac);\n\t\t}\n\n\t\tpublic String name() {\n\t\t\treturn \"Dest MAC Adress\";\n\t\t}\n\n\t\t@Override\n\t\tpublic String denormaliseFunction(double v) {\n\t\t\treturn String.valueOf(v);\n\t\t}\n\t}\n\n\tpublic void setDataController(DataController dataController) {\n\t\tthis.dataController = dataController;\n\t}\n\n}", "public abstract class Normaliser {\n\tdouble lowerBound = 0, upperBound = 1;\n\tNormalisationFilter myFilter = null;\n\tprotected abstract double normaliseFunction(Packet p);\n\tprotected abstract String denormaliseFunction (double v);\n\tpublic abstract String name();\n\tpublic double normalise(Packet p){\n\t\tdouble v = this.normaliseFunction(p);\n\t\tv = (v - lowerBound)/(upperBound - lowerBound);\n\t\t//System.out.println(lowerBound);\n\t\t//System.out.println(v);\n\t\n\t\treturn v;\n\t}\n\tpublic String denormalise(double v){\n\t\tv = v * (upperBound - lowerBound);\n\t\tv += lowerBound;\n\t\treturn denormaliseFunction(v);\n\t}\n\tpublic void filter(double lowerBound, double upperBound){\t\t\n\t\tdouble interval = this.upperBound - this.lowerBound;\n\t\tthis.upperBound = this.lowerBound + upperBound*interval;\n\t\t\tif (this.upperBound > 1) this.upperBound = 1;\n\t\tthis.lowerBound += lowerBound*interval;\n\t\t\tif (this.lowerBound < 0) this.lowerBound = 0;\n\t\tif (myFilter != null)\n\t\t\tdataController.removeFilter(myFilter);\n\t\tmyFilter = new NormalisationFilter(this);\n\t\tdataController.addFilter(myFilter);\n\t}\n\tpublic void clearFilter() {\n\t\tthis.lowerBound = 0;\n\t\tthis.upperBound = 1;\n\t\tdataController.removeFilter(myFilter);\n\t\tmyFilter = null;\n\t}\n}", "public interface UndoAction {\r\n\tpublic void execute_undo();\r\n}\r", "public class UndoController {\r\n\tpublic final static UndoController INSTANCE = new UndoController();\r\n\tfinal Stack<UndoAction> undoMoves;\r\n\tJPanel panel;\r\n\tJButton undoButton;\r\n\t\r\n\tprivate UndoController(){\r\n\t\tundoMoves = new Stack<UndoAction>();\r\n\t\t panel = new JPanel();\r\n\t\t undoButton = new JButton(\"Back\");\r\n\t\t \r\n\t\t undoButton.addActionListener(new ActionListener(){\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void actionPerformed(ActionEvent e) {\r\n\t\t\t\t\texecuteUndo();\r\n\t\t\t\t}\r\n\t\t });\r\n\t\t panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));\r\n\t\t panel.setAlignmentX(JPanel.LEFT_ALIGNMENT);\r\n\t}\r\n\tprotected void updateButton() {\r\n\t\tif (panel.getComponents().length == 0 && !undoMoves.empty()){\r\n\t\t\tpanel.add(undoButton);\r\n\t\t}\r\n\t\tif (panel.getComponents().length != 0 && undoMoves.empty()){\r\n\t\t\tpanel.remove(undoButton);\r\n\t\t}\r\n\t}\r\n\tpublic void addUndoMove(UndoAction undoMove){\r\n\t\tundoMoves.push(undoMove);\r\n\t\tupdateButton();\r\n\t}\r\n\tpublic void executeUndo(){\r\n\t\tif (!undoMoves.empty())\r\n\t\t\tundoMoves.pop().execute_undo();\r\n\t\tupdateButton();\r\n\t}\r\n\tpublic void clearUndoStack(){\r\n\t\tundoMoves.clear();\r\n\t\tupdateButton();\r\n\t}\r\n\tpublic JPanel getPanel(){\r\n\t\treturn panel;\r\n\t}\r\n}\r", "public class Packet {\r\n\tpublic final int no, sport, dport, length;\r\n\tpublic final double time;\r\n\tpublic final String smac, dmac, info, protocol, sip, dip;\r\n\r\n\t/**\r\n\t * \r\n\t * @param no\r\n\t * Packet number\r\n\t * @param time\r\n\t * Time elapsed since first packet (seconds)\r\n\t * @param sip\r\n\t * Source IPv4/6 address\r\n\t * @param smac\r\n\t * Source hardware (MAC) address\r\n\t * @param sport\r\n\t * Source Port\r\n\t * @param dip\r\n\t * Destination IPv4/6 address\r\n\t * @param dmac\r\n\t * Destination hardware (MAC) address\r\n\t * @param dport\r\n\t * Destination Port\r\n\t * @param protocol\r\n\t * Communication protocol\r\n\t * @param length\r\n\t * Packet Length(Bytes)\r\n\t * @param info\r\n\t * Detected description of packet purpose\r\n\t */\r\n\tpublic Packet(int no, double time, String sip, String smac, int sport, String dip, String dmac,\r\n\t\t\tint dport, String protocol, int length, String info) {\r\n\t\tthis.no = no;\r\n\t\tthis.time = time;\r\n\t\tthis.sip = sip;\r\n\t\tthis.smac = smac;\r\n\t\tthis.sport = sport;\r\n\t\tthis.dip = dip;\r\n\t\tthis.dmac = dmac;\r\n\t\tthis.dport = dport;\r\n\t\tthis.protocol = protocol;\r\n\t\tthis.length = length;\r\n\t\tthis.info = info;\r\n\t}\r\n\r\n}\r", "public class OpenGLPanel extends JPanel {\n\n\tprivate static final long serialVersionUID = 1L;\n\tprivate Visualisation currentVis;\n\n\tpublic OpenGLPanel() {\n\t\tcurrentVis = null;\n\t}\n\n\tpublic void redraw() {\n\t\tcurrentVis.display();\n\t}\n\n\tpublic void setVis(Visualisation vis) {\n\t\tif (currentVis != null)\n\t\t\tthis.remove(currentVis);\n\t\tcurrentVis = vis;\n\t\tthis.add(vis);\n\t\tresizeVisualisation();\n\t}\n\n\tpublic Visualisation getVis() {\n\t\treturn currentVis;\n\t}\n\n\tpublic void resizeVisualisation() {\n\t\tcurrentVis.setPreferredSize(getSize());\n\t\tcurrentVis.setSize(getSize());\n\t}\n}", "public class VisControlsContainer extends JPanel {\r\n\tJPanel lastCtrl;\r\n\r\n\tpublic VisControlsContainer() {\r\n\t\tsuper();\r\n\t\tlastCtrl = null;\r\n\t}\r\n\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic void setVisControl(JPanel newPanel) {\r\n\t\tif (lastCtrl != null)\r\n\t\t\tthis.remove(lastCtrl);\r\n\r\n\t\tif (newPanel != null)\r\n\t\t\tthis.add(newPanel);\r\n\t\tlastCtrl = newPanel;\r\n\t\tthis.repaint();\r\n\t}\r\n\r\n}\r", "public class ColourPalette {\n\n\t// Static constants to be used on initiation\n\tpublic final static int SCHEME_QUALITATIVE = 0;\n\tpublic final static int SCHEME_SEQUENTIAL = 1;\n\tpublic final static int SCHEME_DIVERGENT = 2;\n\n\tprotected final int SCHEME;\n\tprotected int currentIndex = 0;\n\n\t/**\n\t * Calculates the colour which is a mix of the two provided, according to a\n\t * given ratio.\n\t * \n\t * @param color1\n\t * This colour will become more apparent with higher ratios\n\t * @param color2\n\t * This colour will become more apparent with lower ratios\n\t * @param ratio\n\t * The ratio between components of colours 1 and 2\n\t * @return The mixed colour according to the specified parameters\n\t */\n\tpublic static Color getColourShade(Color color1, Color color2, double ratio) {\n\n\t\tassert (ratio >= 0 && ratio <= 1);\n\n\t\tint red = (int) Math.round(color1.getRed() * ratio + color2.getRed() * (1 - ratio));\n\t\tint green = (int) Math.round(color1.getGreen() * ratio + color2.getGreen() * (1 - ratio));\n\t\tint blue = (int) Math.round(color1.getBlue() * ratio + color2.getBlue() * (1 - ratio));\n\n\t\treturn new Color(red, green, blue);\n\t}\n\n\t// Define colours to be picked from (Qualitative, Sequential, Divergent)\n\tpublic static final Color[][] colourSchemes = {\n\t\t\t{ new Color(141, 211, 199), new Color(255, 255, 179), new Color(190, 186, 218),\n\t\t\t\t\tnew Color(251, 128, 114), new Color(128, 177, 211), new Color(253, 180, 98),\n\t\t\t\t\tnew Color(179, 222, 105), new Color(252, 205, 229), new Color(217, 217, 217),\n\t\t\t\t\tnew Color(188, 128, 189), new Color(204, 235, 197), new Color(255, 237, 111) },\n\t\t\t{ new Color(255, 255, 204), new Color(255, 237, 160), new Color(254, 217, 118),\n\t\t\t\t\tnew Color(254, 178, 76), new Color(253, 141, 60), new Color(252, 78, 42),\n\t\t\t\t\tnew Color(227, 26, 28), new Color(189, 0, 38), new Color(128, 0, 38) },\n\t\t\t{ new Color(178, 24, 43), new Color(214, 96, 77), new Color(244, 165, 130),\n\t\t\t\t\tnew Color(253, 219, 199), new Color(247, 247, 247), new Color(209, 229, 240),\n\t\t\t\t\tnew Color(146, 197, 222), new Color(67, 147, 195), new Color(33, 102, 172) } };\n\n\t/**\n\t * A colour palette to provide colours for data visualisation.\n\t * \n\t * @param colourScheme\n\t * The colour scheme to use. Please provide a ColourPalette\n\t * constant.\n\t */\n\tpublic ColourPalette(int colourScheme) {\n\t\tSCHEME = colourScheme;\n\t}\n\n\tpublic Color getNextColour() {\n\n\t\tColor thisColour = colourSchemes[SCHEME][currentIndex];\n\t\tcurrentIndex = (currentIndex + 1) % colourSchemes[SCHEME].length;\n\t\treturn thisColour;\n\t}\n\n\tpublic static void setColour(GL2 gl, Color colour) {\n\n\t\tgl.glColor3d(normalise(colour.getRed()), normalise(colour.getGreen()),\n\t\t\t\tnormalise(colour.getBlue()));\n\n\t}\n\tpublic static void setColour(GL2 gl, Color colour, double transparency){\n\t\tgl.glColor4d(normalise(colour.getRed()), normalise(colour.getGreen()),\n\t\t\t\tnormalise(colour.getBlue()), transparency);\n\t}\n\n\tpublic void setNextColour(GL2 gl) {\n\t\tsetColour(gl, getNextColour());\n\n\t}\n\n\tprotected static double normalise(int x) {\n\n\t\treturn (x / 256.0);\n\t}\n\n}" ]
import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.Hashtable; import java.util.List; import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import netvis.data.DataController; import netvis.data.NormaliseFactory; import netvis.data.NormaliseFactory.Normaliser; import netvis.data.UndoAction; import netvis.data.UndoController; import netvis.data.model.Packet; import netvis.ui.OpenGLPanel; import netvis.ui.VisControlsContainer; import netvis.util.ColourPalette; import com.jogamp.opengl.util.gl2.GLUT;
GLUT.BITMAP_HELVETICA_12, normPasses.get(visHighlighted).denormalise((double)i/10) ); } } } @Override public void dispose(GLAutoDrawable arg0) { } @Override public void init(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); // Global settings. gl.glEnable(GL2.GL_POINT_SMOOTH); gl.glEnable(GL2.GL_LINE_SMOOTH); gl.glShadeModel(GL2.GL_SMOOTH); gl.glEnable(GL2.GL_BLEND); gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA); gl.glScaled(1.8, 1.8, 1); gl.glTranslated(-0.5, -0.5, 0); gl.glClearColor(0.7f, 0.7f, 0.7f, 1); gl.glLineWidth(1); glut = new GLUT(); } @Override public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) { } @Override protected JPanel createControls() { JPanel panel = new JPanel(); int PAST_MIN = 1, PAST_MAX = 20, PAST_INIT = 1; final JSlider timeFilter = new JSlider(JSlider.HORIZONTAL, PAST_MIN, PAST_MAX, PAST_INIT); timeFilter.setMajorTickSpacing(3); timeFilter.setMinorTickSpacing(1); timeFilter.setPaintTicks(true); timeFilter.setPaintLabels(true); Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>(); labelTable.put( new Integer( 2 ), new JLabel("1 Min") ); labelTable.put( new Integer( 6 ), new JLabel("3 Min") ); labelTable.put( new Integer( PAST_MAX ), new JLabel("All") ); timeFilter.setLabelTable( labelTable ); timeFilter.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { pastLimit = timeFilter.getValue()*30; if (timeFilter.getValue() == 20) pastLimit = 1000; } }); Box box = Box.createHorizontalBox(); box.add(timeFilter); panel.add(box); String[] normNames = new String[NormaliseFactory.INSTANCE.getNormalisers().size()]; for (int i = 0; i < normNames.length; i++) normNames[i] = NormaliseFactory.INSTANCE.getNormaliser(i).name(); final JComboBox<String> normaliserBox = new JComboBox<String>(normNames); normaliserBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { colorPasser = normaliserBox.getSelectedIndex(); } }); box = Box.createHorizontalBox(); box.add(new JLabel("Colour")); box.add(normaliserBox); panel.add(box); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); panel.setAlignmentX(JPanel.LEFT_ALIGNMENT); return panel; } private void drawActivityBar(GL2 gl, float xc, float yc, float radius) { gl.glBegin(GL2.GL_POLYGON); gl.glVertex2f(xc+radius, yc+0.01f); gl.glVertex2f(xc+radius, yc); gl.glVertex2f(xc-radius, yc); gl.glVertex2f(xc-radius, yc+0.01f); gl.glEnd(); } @Override public String getName() { return "Data Flow"; } @Override public String getDescription() { return getName() + "\n\n" + "Saturation indicates time - grey lines are " + "past lines, coloured lines are more recent.\n" + "You can follow a packet by it's colour.\n" + "The red bars show traffic volume. " + "They shrink with each iteration by some percentage\n" + "and grow linearly with each packet, up to a limit.\n" + "Hover over an axis to show the scale.\n" + "Click an axis to switch to the distribution visualisation " + "for that attribute."; } @Override public void mouseClicked(MouseEvent e) { double xClicked = (double)e.getX()/this.getSize().getWidth(); int visChosen = (int)(xClicked * normPasses.size()); VisualisationsController vc = VisualisationsController.GetInstance(); vc.ActivateById(0); vc.getVList().get(0).setState(visChosen);
UndoController.INSTANCE.addUndoMove(new UndoAction(){
3
gaffo/scumd
src/test/java/com/asolutions/scmsshd/commands/git/SCMCommandTest.java
[ "public class ServerSession extends AbstractSession {\n\n private Timer timer;\n private TimerTask authTimerTask;\n private State state = State.ReceiveKexInit;\n private String username;\n private int maxAuthRequests = 20;\n private int nbAuthRequests;\n private int authTimeout = 10 * 60 * 1000; // 10 minutes in milliseconds\n private boolean allowMoreSessions = true;\n\n private List<NamedFactory<UserAuth>> userAuthFactories;\n\n private enum State {\n ReceiveKexInit, Kex, ReceiveNewKeys, WaitingUserAuth, UserAuth, Running, Unknown\n }\n\n public ServerSession(FactoryManager server, IoSession ioSession) throws Exception {\n super(server, ioSession);\n maxAuthRequests = getIntProperty(FactoryManager.MAX_AUTH_REQUESTS, maxAuthRequests);\n authTimeout = getIntProperty(FactoryManager.AUTH_TIMEOUT, authTimeout);\n log.info(\"Session created...\");\n sendServerIdentification();\n sendKexInit();\n }\n\n @Override\n public CloseFuture close(boolean immediately) {\n unscheduleAuthTimer();\n return super.close(immediately);\n }\n\n public String getNegociated(int index) {\n return negociated[index];\n }\n\n public KeyExchange getKex() {\n return kex;\n }\n\n public ServerFactoryManager getServerFactoryManager() {\n return (ServerFactoryManager) factoryManager;\n }\n\n public String getUsername() {\n return username;\n }\n\n protected void handleMessage(Buffer buffer) throws Exception {\n SshConstants.Message cmd = buffer.getCommand();\n log.debug(\"Received packet {}\", cmd);\n switch (cmd) {\n case SSH_MSG_DISCONNECT: {\n int code = buffer.getInt();\n String msg = buffer.getString();\n log.info(\"Received SSH_MSG_DISCONNECT (reason={}, msg={})\", code, msg);\n close(false);\n break;\n }\n case SSH_MSG_UNIMPLEMENTED: {\n int code = buffer.getInt();\n log.info(\"Received SSH_MSG_UNIMPLEMENTED #{}\", code);\n break;\n }\n case SSH_MSG_DEBUG: {\n boolean display = buffer.getBoolean();\n String msg = buffer.getString();\n log.info(\"Received SSH_MSG_DEBUG (display={}) '{}'\", display, msg);\n break;\n }\n case SSH_MSG_IGNORE:\n log.info(\"Received SSH_MSG_IGNORE\");\n break;\n default:\n switch (state) {\n case ReceiveKexInit:\n if (cmd != SshConstants.Message.SSH_MSG_KEXINIT) {\n log.error(\"Ignoring command \" + cmd + \" while waiting for \" + SshConstants.Message.SSH_MSG_KEXINIT);\n break;\n }\n log.info(\"Received SSH_MSG_KEXINIT\");\n receiveKexInit(buffer);\n negociate();\n kex = NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), negociated[SshConstants.PROPOSAL_KEX_ALGS]);\n kex.init(this, serverVersion.getBytes(), clientVersion.getBytes(), I_S, I_C);\n state = State.Kex;\n break;\n case Kex:\n buffer.rpos(buffer.rpos() - 1);\n if (kex.next(buffer)) {\n sendNewKeys();\n state = State.ReceiveNewKeys;\n }\n break;\n case ReceiveNewKeys:\n if (cmd != SshConstants.Message.SSH_MSG_NEWKEYS) {\n disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, \"Protocol error: expected packet \" + SshConstants.Message.SSH_MSG_NEWKEYS + \", got \" + cmd);\n return;\n }\n log.info(\"Received SSH_MSG_NEWKEYS\");\n receiveNewKeys(true);\n state = State.WaitingUserAuth;\n scheduleAuthTimer();\n break;\n case WaitingUserAuth:\n if (cmd != SshConstants.Message.SSH_MSG_SERVICE_REQUEST) {\n log.info(\"Expecting a {}, but received {}\", SshConstants.Message.SSH_MSG_SERVICE_REQUEST, cmd);\n notImplemented();\n } else {\n String request = buffer.getString();\n log.info(\"Received SSH_MSG_SERVICE_REQUEST '{}'\", request);\n if (\"ssh-userauth\".equals(request)) {\n userAuth(buffer);\n } else {\n disconnect(SshConstants.SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE, \"Bad service request: \" + request);\n }\n }\n break;\n case UserAuth:\n if (cmd != SshConstants.Message.SSH_MSG_USERAUTH_REQUEST) {\n disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, \"Protocol error: expected packet \" + SshConstants.Message.SSH_MSG_USERAUTH_REQUEST + \", got \" + cmd);\n return;\n }\n log.info(\"Received SSH_MSG_USERAUTH_REQUEST\");\n userAuth(buffer);\n break;\n case Running:\n switch (cmd) {\n case SSH_MSG_SERVICE_REQUEST:\n serviceRequest(buffer);\n break;\n case SSH_MSG_CHANNEL_OPEN:\n channelOpen(buffer);\n break;\n case SSH_MSG_CHANNEL_REQUEST:\n channelRequest(buffer);\n break;\n case SSH_MSG_CHANNEL_DATA:\n channelData(buffer);\n break;\n case SSH_MSG_CHANNEL_EXTENDED_DATA:\n channelExtendedData(buffer);\n break;\n case SSH_MSG_CHANNEL_WINDOW_ADJUST:\n channelWindowAdjust(buffer);\n break;\n case SSH_MSG_CHANNEL_EOF:\n channelEof(buffer);\n break;\n case SSH_MSG_CHANNEL_CLOSE:\n channelClose(buffer);\n break;\n case SSH_MSG_GLOBAL_REQUEST:\n globalRequest(buffer);\n break;\n default:\n throw new IllegalStateException(\"Unsupported command: \" + cmd);\n }\n break;\n default:\n throw new IllegalStateException(\"Unsupported state: \" + state);\n }\n }\n }\n\n private void scheduleAuthTimer() {\n authTimerTask = new TimerTask() {\n public void run() {\n try {\n processAuthTimer();\n } catch (IOException e) {\n // Ignore\n }\n }\n };\n timer = new Timer(true);\n timer.schedule(authTimerTask, authTimeout);\n }\n\n private void unscheduleAuthTimer() {\n if (authTimerTask != null) {\n authTimerTask.cancel();\n authTimerTask = null;\n }\n if (timer != null) {\n timer.cancel();\n timer = null;\n }\n }\n\n private void processAuthTimer() throws IOException {\n if (!authed) {\n disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR,\n \"User authentication has timed out\");\n }\n }\n\n private void sendServerIdentification() {\n serverVersion = \"SSH-2.0-\" + getFactoryManager().getVersion();\n sendIdentification(serverVersion);\n }\n\n private void sendKexInit() throws IOException {\n serverProposal = createProposal(factoryManager.getKeyPairProvider().getKeyTypes());\n I_S = sendKexInit(serverProposal);\n }\n\n protected boolean readIdentification(Buffer buffer) throws IOException {\n clientVersion = doReadIdentification(buffer);\n if (clientVersion == null) {\n return false;\n }\n log.info(\"Client version string: {}\", clientVersion);\n if (!clientVersion.startsWith(\"SSH-2.0-\")) {\n throw new SshException(SshConstants.SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED,\n \"Unsupported protocol version: \" + clientVersion);\n }\n return true;\n }\n\n private void receiveKexInit(Buffer buffer) throws IOException {\n clientProposal = new String[SshConstants.PROPOSAL_MAX];\n I_C = receiveKexInit(buffer, clientProposal);\n }\n\n private void serviceRequest(Buffer buffer) throws Exception {\n String request = buffer.getString();\n log.info(\"Received SSH_MSG_SERVICE_REQUEST '{}'\", request);\n // TODO: handle service requests\n disconnect(SshConstants.SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE, \"Unsupported service request: \" + request);\n }\n\n private void userAuth(Buffer buffer) throws Exception {\n if (state == State.WaitingUserAuth) {\n log.info(\"Accepting user authentication request\");\n buffer = createBuffer(SshConstants.Message.SSH_MSG_SERVICE_ACCEPT);\n buffer.putString(\"ssh-userauth\");\n writePacket(buffer);\n userAuthFactories = new ArrayList<NamedFactory<UserAuth>>(getServerFactoryManager().getUserAuthFactories());\n log.info(\"Authorized authentication methods: {}\", NamedFactory.Utils.getNames(userAuthFactories));\n state = State.UserAuth;\n } else {\n if (nbAuthRequests++ > maxAuthRequests) {\n throw new SshException(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, \"Too may authentication failures\");\n }\n String username = buffer.getString();\n String svcName = buffer.getString();\n String method = buffer.getString();\n\n log.info(\"Authenticating user '{}' with method '{}'\", username, method);\n Object identity = null;\n NamedFactory<UserAuth> factory = NamedFactory.Utils.get(userAuthFactories, method);\n if (factory != null) {\n UserAuth auth = factory.create();\n try {\n identity = auth.auth(this, username, buffer);\n if (identity == null) {\n // authentication is still ongoing\n log.info(\"Authentication not finished\");\n return;\n } else {\n log.info(\"Authentication succeeded\");\n }\n } catch (Exception e) {\n // Continue\n log.info(\"Authentication failed: {}\", e.getMessage());\n }\n } else {\n log.info(\"Unsupported authentication method '{}'\", method);\n }\n if (identity != null) {\n buffer = createBuffer(SshConstants.Message.SSH_MSG_USERAUTH_SUCCESS);\n writePacket(buffer);\n state = State.Running;\n authed = true;\n this.username = username;\n unscheduleAuthTimer();\n } else {\n buffer = createBuffer(SshConstants.Message.SSH_MSG_USERAUTH_FAILURE);\n NamedFactory.Utils.remove(userAuthFactories, \"none\"); // 'none' MUST NOT be listed\n buffer.putString(NamedFactory.Utils.getNames(userAuthFactories));\n buffer.putByte((byte) 0);\n writePacket(buffer);\n }\n }\n }\n\n public KeyPair getHostKey() {\n return factoryManager.getKeyPairProvider().loadKey(negociated[SshConstants.PROPOSAL_SERVER_HOST_KEY_ALGS]);\n }\n\n private void channelOpen(Buffer buffer) throws Exception {\n String type = buffer.getString();\n int id = buffer.getInt();\n int rwsize = buffer.getInt();\n int rmpsize = buffer.getInt();\n\n log.info(\"Received SSH_MSG_CHANNEL_OPEN {}\", type);\n\n if (closing) {\n buffer = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_FAILURE);\n buffer.putInt(id);\n buffer.putInt(SshConstants.SSH_OPEN_CONNECT_FAILED);\n buffer.putString(\"SSH server is shutting down: \" + type);\n buffer.putString(\"\");\n writePacket(buffer);\n return;\n }\n if (!allowMoreSessions) {\n buffer = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_FAILURE);\n buffer.putInt(id);\n buffer.putInt(SshConstants.SSH_OPEN_CONNECT_FAILED);\n buffer.putString(\"additional sessions disabled\");\n buffer.putString(\"\");\n writePacket(buffer);\n return;\n }\n\n ServerChannel channel = null;\n for (NamedFactory<ServerChannel> factory : getServerFactoryManager().getChannelFactories()) {\n if (factory.getName().equals(type)) {\n channel = factory.create();\n break;\n }\n }\n if (channel == null) {\n buffer = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_FAILURE);\n buffer.putInt(id);\n buffer.putInt(SshConstants.SSH_OPEN_UNKNOWN_CHANNEL_TYPE);\n buffer.putString(\"Unsupported channel type: \" + type);\n buffer.putString(\"\");\n writePacket(buffer);\n return;\n }\n\n int channelId;\n synchronized (channels) {\n channelId = nextChannelId++;\n }\n channels.put(channelId, channel);\n channel.init(this, channelId, id, rwsize, rmpsize);\n buffer = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_CONFIRMATION);\n buffer.putInt(id);\n buffer.putInt(channelId);\n buffer.putInt(channel.getLocalWindow().getSize());\n buffer.putInt(channel.getLocalWindow().getPacketSize());\n writePacket(buffer);\n }\n\n private void globalRequest(Buffer buffer) throws Exception {\n String req = buffer.getString();\n boolean wantReply = buffer.getBoolean();\n if (req.equals(\"[email protected]\")) {\n // Relatively standard KeepAlive directive, just wants failure\n } else if (req.equals(\"[email protected]\")) {\n allowMoreSessions = false;\n } else {\n log.info(\"Received SSH_MSG_GLOBAL_REQUEST {}\" ,req);\n log.error(\"Unknown global request: {}\", req);\n }\n if (wantReply){\n buffer = createBuffer(SshConstants.Message.SSH_MSG_REQUEST_FAILURE);\n writePacket(buffer);\n }\n }\n\n\n}", "public class MockTestCase {\n\n\tprotected Mockery context = new JUnit4Mockery();\n\n\t@Before\n\tpublic void setupMockery() {\n\t\tcontext.setImposteriser(ClassImposteriser.INSTANCE);\n\t}\n\t\n\t@After\n\tpublic void mockeryAssertIsSatisfied(){\n\t\tcontext.assertIsSatisfied();\n\t}\n\n\tprotected void checking(Expectations expectations) {\n\t\tcontext.checking(expectations);\n\t}\n\n}", "public enum AuthorizationLevel {\n\tAUTH_LEVEL_READ_ONLY, \n\tAUTH_LEVEL_READ_WRITE;\n}", "public class FilteredCommand {\r\n\t\r\n\tprivate String command;\r\n\tprivate String argument;\r\n\r\n\tpublic FilteredCommand() {\r\n\t}\r\n\t\r\n\tpublic FilteredCommand(String command, String argument) {\r\n\t\tthis.command = command;\r\n\t\tthis.argument = argument;\r\n\t}\r\n\r\n\tpublic void setArgument(String argument) {\r\n\t\tthis.argument = argument;\r\n\t}\r\n\t\r\n\tpublic void setCommand(String command) {\r\n\t\tthis.command = command;\r\n\t}\r\n\r\n\tpublic String getCommand() {\r\n\t\treturn this.command;\r\n\t}\r\n\r\n\tpublic String getArgument() {\r\n\t\treturn this.argument;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic String toString()\r\n\t{\r\n\t\treturn \"Filtered Command: \" + getCommand() + \", \" + getArgument();\r\n\t}\r\n\r\n}\r", "public interface ISCMCommandHandler {\r\n\r\n\tvoid execute(FilteredCommand filteredCommand, InputStream inputStream,\r\n\t\t\tOutputStream outputStream, OutputStream errorStream,\r\n\t\t\tExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);\r\n\r\n}\r", "public interface IPathToProjectNameConverter {\n\n\tpublic abstract String convert(String toParse)\n\t\t\tthrows UnparsableProjectException;\n\n}", "public interface IProjectAuthorizer {\n\n\tAuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;\n\n}" ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import org.apache.sshd.server.CommandFactory.ExitCallback; import org.apache.sshd.server.session.ServerSession; import org.jmock.Expectations; import org.junit.Before; import org.junit.Test; import com.asolutions.MockTestCase; import com.asolutions.scmsshd.authorizors.AuthorizationLevel; import com.asolutions.scmsshd.commands.FilteredCommand; import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler; import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter; import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.git; public class SCMCommandTest extends MockTestCase { private static final String USERNAME = "username"; private static final String PROJECT = "proj-2"; private FilteredCommand filteredCommand; private IProjectAuthorizer mockProjectAuthorizer; private ServerSession mockSession;
private IPathToProjectNameConverter mockPathToProjectConverter;
5
JoostvDoorn/GlutenVrijApp
app/src/main/java/com/joostvdoorn/glutenvrij/scanner/core/oned/Code128Reader.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 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 class ResultPoint {\n\n private final float x;\n private final float y;\n\n public ResultPoint(float x, float y) {\n this.x = x;\n this.y = y;\n }\n\n public final float getX() {\n return x;\n }\n\n public final float getY() {\n return y;\n }\n\n public boolean equals(Object other) {\n if (other instanceof ResultPoint) {\n ResultPoint otherPoint = (ResultPoint) other;\n return x == otherPoint.x && y == otherPoint.y;\n }\n return false;\n }\n\n public int hashCode() {\n return 31 * Float.floatToIntBits(x) + Float.floatToIntBits(y);\n }\n\n public String toString() {\n StringBuffer result = new StringBuffer(25);\n result.append('(');\n result.append(x);\n result.append(',');\n result.append(y);\n result.append(')');\n return result.toString();\n }\n\n /**\n * <p>Orders an array of three ResultPoints in an order [A,B,C] such that AB < AC and\n * BC < AC and the angle between BC and BA is less than 180 degrees.\n */\n public static void orderBestPatterns(ResultPoint[] patterns) {\n\n // Find distances between pattern centers\n float zeroOneDistance = distance(patterns[0], patterns[1]);\n float oneTwoDistance = distance(patterns[1], patterns[2]);\n float zeroTwoDistance = distance(patterns[0], patterns[2]);\n\n ResultPoint pointA;\n ResultPoint pointB;\n ResultPoint pointC;\n // Assume one closest to other two is B; A and C will just be guesses at first\n if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) {\n pointB = patterns[0];\n pointA = patterns[1];\n pointC = patterns[2];\n } else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) {\n pointB = patterns[1];\n pointA = patterns[0];\n pointC = patterns[2];\n } else {\n pointB = patterns[2];\n pointA = patterns[0];\n pointC = patterns[1];\n }\n\n // Use cross product to figure out whether A and C are correct or flipped.\n // This asks whether BC x BA has a positive z component, which is the arrangement\n // we want for A, B, C. If it's negative, then we've got it flipped around and\n // should swap A and C.\n if (crossProductZ(pointA, pointB, pointC) < 0.0f) {\n ResultPoint temp = pointA;\n pointA = pointC;\n pointC = temp;\n }\n\n patterns[0] = pointA;\n patterns[1] = pointB;\n patterns[2] = pointC;\n }\n\n\n /**\n * @return distance between two points\n */\n public static float distance(ResultPoint pattern1, ResultPoint pattern2) {\n float xDiff = pattern1.getX() - pattern2.getX();\n float yDiff = pattern1.getY() - pattern2.getY();\n return (float) Math.sqrt((double) (xDiff * xDiff + yDiff * yDiff));\n }\n\n /**\n * Returns the z component of the cross product between vectors BC and BA.\n */\n private static float crossProductZ(ResultPoint pointA, ResultPoint pointB, ResultPoint pointC) {\n float bX = pointB.x;\n float bY = pointB.y;\n return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX));\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.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.ResultPoint; import com.joostvdoorn.glutenvrij.scanner.core.common.BitArray; import java.util.Hashtable;
{2, 2, 1, 2, 1, 3}, {2, 2, 1, 3, 1, 2}, // 10 {2, 3, 1, 2, 1, 2}, {1, 1, 2, 2, 3, 2}, {1, 2, 2, 1, 3, 2}, {1, 2, 2, 2, 3, 1}, {1, 1, 3, 2, 2, 2}, // 15 {1, 2, 3, 1, 2, 2}, {1, 2, 3, 2, 2, 1}, {2, 2, 3, 2, 1, 1}, {2, 2, 1, 1, 3, 2}, {2, 2, 1, 2, 3, 1}, // 20 {2, 1, 3, 2, 1, 2}, {2, 2, 3, 1, 1, 2}, {3, 1, 2, 1, 3, 1}, {3, 1, 1, 2, 2, 2}, {3, 2, 1, 1, 2, 2}, // 25 {3, 2, 1, 2, 2, 1}, {3, 1, 2, 2, 1, 2}, {3, 2, 2, 1, 1, 2}, {3, 2, 2, 2, 1, 1}, {2, 1, 2, 1, 2, 3}, // 30 {2, 1, 2, 3, 2, 1}, {2, 3, 2, 1, 2, 1}, {1, 1, 1, 3, 2, 3}, {1, 3, 1, 1, 2, 3}, {1, 3, 1, 3, 2, 1}, // 35 {1, 1, 2, 3, 1, 3}, {1, 3, 2, 1, 1, 3}, {1, 3, 2, 3, 1, 1}, {2, 1, 1, 3, 1, 3}, {2, 3, 1, 1, 1, 3}, // 40 {2, 3, 1, 3, 1, 1}, {1, 1, 2, 1, 3, 3}, {1, 1, 2, 3, 3, 1}, {1, 3, 2, 1, 3, 1}, {1, 1, 3, 1, 2, 3}, // 45 {1, 1, 3, 3, 2, 1}, {1, 3, 3, 1, 2, 1}, {3, 1, 3, 1, 2, 1}, {2, 1, 1, 3, 3, 1}, {2, 3, 1, 1, 3, 1}, // 50 {2, 1, 3, 1, 1, 3}, {2, 1, 3, 3, 1, 1}, {2, 1, 3, 1, 3, 1}, {3, 1, 1, 1, 2, 3}, {3, 1, 1, 3, 2, 1}, // 55 {3, 3, 1, 1, 2, 1}, {3, 1, 2, 1, 1, 3}, {3, 1, 2, 3, 1, 1}, {3, 3, 2, 1, 1, 1}, {3, 1, 4, 1, 1, 1}, // 60 {2, 2, 1, 4, 1, 1}, {4, 3, 1, 1, 1, 1}, {1, 1, 1, 2, 2, 4}, {1, 1, 1, 4, 2, 2}, {1, 2, 1, 1, 2, 4}, // 65 {1, 2, 1, 4, 2, 1}, {1, 4, 1, 1, 2, 2}, {1, 4, 1, 2, 2, 1}, {1, 1, 2, 2, 1, 4}, {1, 1, 2, 4, 1, 2}, // 70 {1, 2, 2, 1, 1, 4}, {1, 2, 2, 4, 1, 1}, {1, 4, 2, 1, 1, 2}, {1, 4, 2, 2, 1, 1}, {2, 4, 1, 2, 1, 1}, // 75 {2, 2, 1, 1, 1, 4}, {4, 1, 3, 1, 1, 1}, {2, 4, 1, 1, 1, 2}, {1, 3, 4, 1, 1, 1}, {1, 1, 1, 2, 4, 2}, // 80 {1, 2, 1, 1, 4, 2}, {1, 2, 1, 2, 4, 1}, {1, 1, 4, 2, 1, 2}, {1, 2, 4, 1, 1, 2}, {1, 2, 4, 2, 1, 1}, // 85 {4, 1, 1, 2, 1, 2}, {4, 2, 1, 1, 1, 2}, {4, 2, 1, 2, 1, 1}, {2, 1, 2, 1, 4, 1}, {2, 1, 4, 1, 2, 1}, // 90 {4, 1, 2, 1, 2, 1}, {1, 1, 1, 1, 4, 3}, {1, 1, 1, 3, 4, 1}, {1, 3, 1, 1, 4, 1}, {1, 1, 4, 1, 1, 3}, // 95 {1, 1, 4, 3, 1, 1}, {4, 1, 1, 1, 1, 3}, {4, 1, 1, 3, 1, 1}, {1, 1, 3, 1, 4, 1}, {1, 1, 4, 1, 3, 1}, // 100 {3, 1, 1, 1, 4, 1}, {4, 1, 1, 1, 3, 1}, {2, 1, 1, 4, 1, 2}, {2, 1, 1, 2, 1, 4}, {2, 1, 1, 2, 3, 2}, // 105 {2, 3, 3, 1, 1, 1, 2} }; private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.25f); private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); private static final int CODE_SHIFT = 98; private static final int CODE_CODE_C = 99; private static final int CODE_CODE_B = 100; private static final int CODE_CODE_A = 101; private static final int CODE_FNC_1 = 102; private static final int CODE_FNC_2 = 97; private static final int CODE_FNC_3 = 96; private static final int CODE_FNC_4_A = 101; private static final int CODE_FNC_4_B = 100; private static final int CODE_START_A = 103; private static final int CODE_START_B = 104; private static final int CODE_START_C = 105; private static final int CODE_STOP = 106;
private static int[] findStartPattern(BitArray row) throws NotFoundException {
6
JEEventStore/JEEventStore
core/src/test/java/org/jeeventstore/notifier/AsyncEventStoreCommitNotifierTest.java
[ "public interface EventStoreCommitNotification {\n\n /**\n * Returns the change set that has been committed to the event store.\n * \n * @return the committed {@link ChangeSet}\n */\n ChangeSet changes();\n \n}", "public interface EventStoreCommitNotifier {\n\n /**\n * Notifies all registered listeners about the committed {@link ChangeSet}.\n * Non-delivered notifications are not persisted during application\n * restarts to avoid expensive 2-phase-commits. If the server crashes or\n * stops while the notification is in progress, clients are expected to \n * recover manually on the next server startup (e.g., by replaying the full\n * event store on application startup using {@link EventStorePersistence#allChanges}).\n * \n * @param changeSet the change set that has been committed, not null\n */\n void notifyListeners(ChangeSet changeSet);\n\n /**\n * Adds an interested listener for the given bucket.\n * The listener must not be registered in that bucket already.\n * \n * @param bucketId the bucket that the listener is interested in\n * @param listener the listener that shall be added, not null\n */\n void addListener(String bucketId, EventStoreCommitListener listener);\n\n /**\n * Removes a registered listener from the given bucket.\n * The listener must be registered in the specified bucket\n * \n * @param bucketId the bucket that the listener was registered for\n * @param listener the listener that shall be removed, not null\n */\n void removeListener(String bucketId, EventStoreCommitListener listener);\n \n}", "public interface ChangeSet extends Serializable {\n\n /**\n * Identifies the bucket to which the event stream belongs.\n * \n * @return the identifier\n */\n String bucketId();\n\n /**\n * Identifies the event stream to which this belongs.\n * \n * @return the identifier\n */\n String streamId();\n\n /**\n * Gets the version of the event stream to which this applies.\n * \n * @return the version\n */\n long streamVersion();\n\n /**\n * Gets the unique identifier for this ChangeSet within the stream.\n * \n * @return the unique identifer\n */\n String changeSetId();\n \n /**\n * Gets an iterator to the events contained within this ChangeSet.\n * \n * @return the iterator\n */\n Iterator<Serializable> events();\n \n}", "public class TestChangeSet implements ChangeSet {\n\n private String bucketId;\n private String id;\n\n public TestChangeSet(String bucketId, String id) {\n this.bucketId = bucketId;\n this.id = id;\n }\n\n @Override\n public String bucketId() {\n return this.bucketId;\n }\n\n @Override\n public String streamId() {\n return this.id;\n }\n\n @Override\n public long streamVersion() {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public String changeSetId() {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public Iterator<Serializable> events() {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n}", "public class DefaultDeployment {\n\n /**\n * Resolve the dependencies for the given maven artifact.\n * @param artifact\n * @return A list of files pointing to the dependencies.\n */\n static File[] resolve(String artifact) {\n\treturn Maven.resolver().loadPomFromFile(\"pom.xml\")\n\t\t.resolve(artifact)\n\t\t.withTransitivity()\n .as(File.class); \n }\n\n public static EnterpriseArchive ear(String artifact) {\n\tSystem.out.println(\"Generating standard EAR deployment\");\n\tEnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class);\n addDependencies(ear, artifact, true);\n return ear;\n }\n\n public static void addDependencies(EnterpriseArchive ear, String artifact, boolean includeArtifact) {\n String lib = artifact.split(\":\")[1];\n try {\n File[] libs = resolve(artifact);\n for (int i = 0; i < libs.length; i++) {\n if (i == 0 && !includeArtifact)\n continue;\n File f = libs[i];\n String filename = (i > 0 ? f.getName() : lib + \".jar\");\n System.out.println(\"Adding dependency #\" + i \n + \": \" + f.getAbsolutePath() \n + \" as \" + filename);\n ear.addAsLibrary(f, filename);\n }\n } catch (RuntimeException e) {\n // printing the error helps with testing\n System.err.println(\">>>>>> ERROR: \" + e + \" / \" + e.getCause());\n throw e;\n }\n }\n\n}" ]
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jeeventstore.ChangeSet; import org.jeeventstore.store.TestChangeSet; import org.jeeventstore.tests.DefaultDeployment; import static org.testng.Assert.*; import org.testng.annotations.Test; import org.jeeventstore.EventStoreCommitNotification; import org.jeeventstore.EventStoreCommitNotifier; import java.io.File; import java.util.UUID; import javax.ejb.EJB; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter;
/* * Copyright (c) 2013-2014 Red Rainbow IT Solutions GmbH, Germany * * 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 org.jeeventstore.notifier; public class AsyncEventStoreCommitNotifierTest extends AbstractEventStoreCommitNotifierTest { @Deployment public static Archive<?> deployment() { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "test.ear") .addAsModule(ShrinkWrap.create(JavaArchive.class, "ejb.jar") .addAsManifestResource(new File("src/test/resources/META-INF/beans.xml")) .addAsManifestResource( new File("src/test/resources/META-INF/ejb-jar-AsyncEventStoreCommitNotifierTest.xml"), "ejb-jar.xml") .addPackage(AsyncEventStoreCommitNotifier.class.getPackage())
.addPackage(ChangeSet.class.getPackage())
2
UweTrottmann/thetvdb-java
src/main/java/com/uwetrottmann/thetvdb/TheTvdb.java
[ "public interface TheTvdbAuthentication {\n\n String PATH_LOGIN = \"login\";\n\n /**\n * Returns a session token to be included in the rest of the requests. Note that API key authentication is required\n * for all subsequent requests and user auth is required for routes in the User section.\n */\n @POST(PATH_LOGIN)\n Call<Token> login(@Body LoginData loginData);\n\n /**\n * Refreshes your current, valid JWT token and returns a new token. Hit this route so that you do not have to post\n * to /login with your API key and credentials once you have already been authenticated.\n */\n @GET(\"refresh_token\")\n Call<Token> refreshToken();\n\n}", "public interface TheTvdbEpisodes {\n\n @GET(\"episodes/{id}\")\n Call<EpisodeResponse> get(\n @Path(\"id\") int id,\n @Header(TheTvdb.HEADER_ACCEPT_LANGUAGE) String language\n );\n\n}", "public interface TheTvdbLanguages {\n\n /**\n * All available languages. These language abbreviations can be used in the Accept-Language header for routes that\n * return translation records.\n */\n @GET(\"languages\")\n Call<LanguagesResponse> allAvailable();\n\n /**\n * Information about a particular language, given the language ID.\n */\n @GET(\"languages/{id}\")\n Call<LanguageResponse> languageDetails(@Path(\"id\") int id);\n\n}", "public interface TheTvdbSearch {\n\n /**\n * Allows the user to search for a series based on the following parameters.\n *\n * @param name Name of the series to search for.\n */\n @GET(\"search/series\")\n Call<SeriesResultsResponse> series(\n @Query(\"name\") String name,\n @Query(\"imdbId\") String imdbId,\n @Query(\"zap2itId\") String zap2itId,\n @Query(\"slug\") String slug,\n @Header(TheTvdb.HEADER_ACCEPT_LANGUAGE) String languages\n );\n\n @GET(\"search/series/params\")\n Call<SearchParamsResponse> params();\n\n}", "public interface TheTvdbSeries {\n\n /**\n * Returns a series records that contains all information known about a particular series id.\n *\n * <p>If a translation is not available null will be returned (such as for seriesName or overview). Also errors will\n * include '\"invalidLanguage\": \"Incomplete or no translation for the given language\"'.\n *\n * @param id ID of the series.\n * @param language See <a href=\"http://en.wikipedia.org/wiki/Content_negotiation\">Content negotiation</a>.\n */\n @GET(\"series/{id}\")\n Call<SeriesResponse> series(\n @Path(\"id\") int id,\n @Header(TheTvdb.HEADER_ACCEPT_LANGUAGE) String language\n );\n\n @HEAD(\"series/{id}\")\n Call<Void> seriesHeader(\n @Path(\"id\") int id,\n @Header(TheTvdb.HEADER_ACCEPT_LANGUAGE) String language\n );\n\n /**\n * @see <a href=\"https://api.thetvdb.com/swagger#!/Series/get_series_id_actors\">/series/{id}/actors</a>\n */\n @GET(\"series/{id}/actors\")\n Call<ActorsResponse> actors(@Path(\"id\") int id);\n\n /**\n * All episodes for a given series. Paginated with 100 results per page.\n *\n * <p>If a translation is not available null will be returned (such as for episodeName or overview) and the\n * associated language property will be ''. Also errors will include '\"invalidLanguage\": \"Some translations were not\n * available in the specified language\"'.\n *\n * @param id ID of the series.\n * @param language See <a href=\"http://en.wikipedia.org/wiki/Content_negotiation\">Content negotiation</a>.\n * @param page Page of results to fetch. Defaults to page 1 if not provided.\n */\n @GET(\"series/{id}/episodes\")\n Call<EpisodesResponse> episodes(\n @Path(\"id\") int id,\n @Query(\"page\") Integer page,\n @Header(TheTvdb.HEADER_ACCEPT_LANGUAGE) String language\n );\n\n /**\n * This route allows the user to query against episodes for the given series. The response is a paginated array of\n * episode records that have been filtered down to basic information.\n *\n * @param id ID of the series.\n * @param language See <a href=\"http://en.wikipedia.org/wiki/Content_negotiation\">Content negotiation</a>. Records\n * are returned with the Episode name and Overview in the desired language, if it exists. If there is no\n * translation\n * for the given language, then the record is still returned but with empty values for the translated fields.\n * @param page Page of results to fetch. Defaults to page 1 if not provided.\n */\n @GET(\"series/{id}/episodes/query\")\n Call<EpisodesResponse> episodesQuery(\n @Path(\"id\") int id,\n @Query(\"absoluteNumber\") Integer absoluteNumber,\n @Query(\"airedSeason\") Integer airedSeason,\n @Query(\"airedEpisode\") Integer airedEpisode,\n @Query(\"dvdSeason\") Integer dvdSeason,\n @Query(\"dvdEpisode\") Double dvdEpisode,\n @Query(\"imdbId\") String imdbId,\n @Query(\"firstAired\") String firstAired,\n @Query(\"page\") Integer page,\n @Header(TheTvdb.HEADER_ACCEPT_LANGUAGE) String language\n );\n\n @GET(\"series/{id}/episodes/summary\")\n Call<EpisodesSummaryResponse> episodesSummary(\n @Path(\"id\") int id\n );\n\n @GET(\"series/{id}/images/query\")\n Call<SeriesImageQueryResultResponse> imagesQuery(\n @Path(\"id\") int id,\n @Query(\"keyType\") String keyType,\n @Query(\"resolution\") String resolution,\n @Query(\"subKey\") String subKey,\n @Header(TheTvdb.HEADER_ACCEPT_LANGUAGE) String language\n );\n\n @GET(\"series/{id}/images/query/params\")\n Call<SeriesImagesQueryParamResponse> imagesQueryParams(\n @Path(\"id\") int id\n );\n\n}", "public interface TheTvdbUpdated {\n\n /**\n * Returns an array of series that have changed in a maximum of one week blocks since the provided fromTime.\n * The user may specify a toTime to grab results for less than a week. Any timespan larger than a week will\n * be reduced down to one week automatically.\n *\n * @param fromTime Epoch time to start your date range.\n * @param toTime Epoch time to end your date range. Must be one week from fromTime\n */\n @GET(\"updated/query\")\n Call<SeriesUpdatesResponse> seriesUpdates(@Query(\"fromTime\") Long fromTime, @Query(\"toTime\") Long toTime);\n}", "public interface TheTvdbUser {\n /**\n * Returns basic information about the currently authenticated user.\n */\n @GET(\"/user\")\n Call<UserResponse> user();\n \n /**\n * Returns an array of favorite series for a given user, will be a blank array if no favorites exist.\n */\n @GET(\"/user/favorites\")\n Call<UserFavoritesResponse> favorites();\n\n /**\n * Deletes the given series ID from the user’s favorite’s list and returns the updated list.\n */\n @DELETE(\"/user/favorites/{id}\")\n Call<UserFavoritesResponse> deleteFavorite(\n @Path(\"id\") long id\n );\n\n /**\n * Adds the supplied series ID to the user’s favorite’s list and returns the updated list.\n */\n @PUT(\"/user/favorites/{id}\")\n Call<UserFavoritesResponse> addFavorite(\n @Path(\"id\") long id\n );\n\n /**\n * Returns an array of ratings for the given user.\n */\n @GET(\"/user/ratings\")\n Call<UserRatingsResponse> ratings();\n\n /**\n * Returns an array of ratings for a given user that match the query.\n */\n @GET(\"/user/ratings/query\")\n Call<UserRatingsResponse> ratingsQuery(\n @Query(\"itemType\") String itemType\n );\n \n /**\n * Returns a list of query params for use in the /user/ratings/query route.\n */\n @GET(\"/user/ratings/query/params\")\n Call<UserRatingsQueryParamsRepsonse> ratingsQueryParams();\n\n /**\n * This route deletes a given rating of a given type.\n */\n @DELETE(\"/user/ratings/{itemType}/{itemId}\")\n Call<UserRatingsResponse> deleteRating(\n @Path(\"itemType\") String itemType,\n @Path(\"itemId\") long itemId\n );\n \n /**\n * This route updates a given rating of a given type.\n */\n @PUT(\"/user/ratings/{itemType}/{itemId}/{itemRating}\")\n Call<UserRatingsResponse> addRating(\n @Path(\"itemType\") String itemType,\n @Path(\"itemId\") long itemId,\n @Path(\"itemRating\") long itemRating\n );\n}" ]
import com.uwetrottmann.thetvdb.services.TheTvdbAuthentication; import com.uwetrottmann.thetvdb.services.TheTvdbEpisodes; import com.uwetrottmann.thetvdb.services.TheTvdbLanguages; import com.uwetrottmann.thetvdb.services.TheTvdbSearch; import com.uwetrottmann.thetvdb.services.TheTvdbSeries; import com.uwetrottmann.thetvdb.services.TheTvdbUpdated; import com.uwetrottmann.thetvdb.services.TheTvdbUser; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import javax.annotation.Nullable;
package com.uwetrottmann.thetvdb; @SuppressWarnings("WeakerAccess") public class TheTvdb { public static final String API_HOST = "api.thetvdb.com"; public static final String API_URL = "https://" + API_HOST + "/"; public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language"; public static final String HEADER_AUTHORIZATION = "Authorization"; @Nullable private OkHttpClient okHttpClient; @Nullable private Retrofit retrofit; private String apiKey; @Nullable private String currentJsonWebToken; /** * Create a new manager instance. */ public TheTvdb(String apiKey) { this.apiKey = apiKey; } public String apiKey() { return apiKey; } public void apiKey(String apiKey) { this.apiKey = apiKey; } @Nullable public String jsonWebToken() { return currentJsonWebToken; } public void jsonWebToken(@Nullable String value) { this.currentJsonWebToken = value; } /** * Creates a {@link Retrofit.Builder} that sets the base URL, adds a Gson converter and sets {@link * #okHttpClient()} as its client. * * @see #okHttpClient() */ protected Retrofit.Builder retrofitBuilder() { return new Retrofit.Builder() .baseUrl(API_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient()); } /** * Returns the default OkHttp client instance. It is strongly recommended to override this and use your app * instance. * * @see #setOkHttpClientDefaults(OkHttpClient.Builder) */ protected synchronized OkHttpClient okHttpClient() { if (okHttpClient == null) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); setOkHttpClientDefaults(builder); okHttpClient = builder.build(); } return okHttpClient; } /** * Adds a network interceptor to add version and auth headers and * an authenticator to automatically login using the API key. */ protected void setOkHttpClientDefaults(OkHttpClient.Builder builder) { builder.addNetworkInterceptor(new TheTvdbInterceptor(this)) .authenticator(new TheTvdbAuthenticator(this)); } /** * Return the {@link Retrofit} instance. If called for the first time builds the instance. */ protected Retrofit getRetrofit() { if (retrofit == null) { retrofit = retrofitBuilder().build(); } return retrofit; } /** * Obtaining and refreshing your JWT token. */ public TheTvdbAuthentication authentication() { return getRetrofit().create(TheTvdbAuthentication.class); } /** * Information about a specific episode. */ public TheTvdbEpisodes episodes() { return getRetrofit().create(TheTvdbEpisodes.class); } /** * Available languages and information. */ public TheTvdbLanguages languages() { return getRetrofit().create(TheTvdbLanguages.class); } /** * Information about a specific series. */ public TheTvdbSeries series() { return getRetrofit().create(TheTvdbSeries.class); } /** * Search for a particular series. */ public TheTvdbSearch search() { return getRetrofit().create(TheTvdbSearch.class); } /** * Retrieve series which were recently updated. */ public TheTvdbUpdated updated() { return getRetrofit().create(TheTvdbUpdated.class); } /** * Routes for handling user data. */
public TheTvdbUser user() {
6
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/ThompsonAutomatonBuilder.java
[ "public interface TokenType {\n\n\tboolean error();\n\tboolean accept();\n\n}", "static class EpsilonTransition extends BasicTransition implements EventlessTransition {\n\n\tpublic EpsilonTransition(State target) {\n\t\tsuper(target);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn new StringBuilder().append(\" -> \").append(getTarget().getId()).toString();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn 31 * super.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\treturn super.equals(obj);\n\t}\n\n}", "static class ExactTransition extends BasicTransition implements EventTransition {\n\n\tprivate char value;\n\n\tpublic ExactTransition(char value, State target) {\n\t\tsuper(target);\n\t\tthis.value = value;\n\t}\n\n\tpublic char getValue() {\n\t\treturn value;\n\t}\n\n\t@Override\n\tpublic char getFrom() {\n\t\treturn value;\n\t}\n\n\t@Override\n\tpublic char getTo() {\n\t\treturn value;\n\t}\n\n\t@Override\n\tpublic boolean matches(char ch) {\n\t\treturn value == ch;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn new StringBuilder().append(\" -<\").append(charToString(value)).append(\">-> \").append(getTarget().getId()).toString();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn super.hashCode() + 17 * Character.valueOf(value);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (!super.equals(obj)) {\n\t\t\treturn false;\n\t\t}\n\t\tExactTransition other = (ExactTransition) obj;\n\t\treturn this.value == other.value;\n\t}\n\n\t@Override\n\tpublic ExactTransition clone() {\n\t\tExactTransition transition = (ExactTransition) super.clone();\n\t\ttransition.value = value;\n\t\treturn transition;\n\t}\n\n}", "static class RangeTransition extends BasicTransition implements EventTransition {\n\n\tprivate char from;\n\tprivate char to;\n\n\tpublic RangeTransition(char from, char to, State target) {\n\t\tsuper(target);\n\t\tthis.from = from;\n\t\tthis.to = to;\n\t}\n\n\t@Override\n\tpublic char getFrom() {\n\t\treturn from;\n\t}\n\n\t@Override\n\tpublic char getTo() {\n\t\treturn to;\n\t}\n\n\t@Override\n\tpublic boolean matches(char ch) {\n\t\treturn ch >= from && ch <= to;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn new StringBuilder().append(\" -<\").append(charToString(from)).append(\"..\").append(charToString(to)).append(\">-> \").append(getTarget().getId()).toString();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn super.hashCode() + 13 * Character.valueOf(from).hashCode() + 31 * Character.valueOf(to);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (!super.equals(obj)) {\n\t\t\treturn false;\n\t\t}\n\t\tRangeTransition other = (RangeTransition) obj;\n\t\treturn this.from == other.from && this.to == other.to;\n\t}\n\n\t@Override\n\tpublic RangeTransition clone() {\n\t\tRangeTransition transition = (RangeTransition) super.clone();\n\t\ttransition.from = from;\n\t\ttransition.to = to;\n\t\treturn transition;\n\t}\n\n}", "public static class State implements Cloneable {\n\n\tprivate TokenType type;\n\tprivate List<Transition> transitions;\n\tprivate List<State> closure;\n\tprivate List<EventTransition> nextclosure;\n\n\tpublic State() {\n\t\tthis.transitions = new ArrayList<Transition>();\n\t}\n\n\tpublic State(TokenType type) {\n\t\tthis.type = type;\n\t\tthis.transitions = new ArrayList<Transition>();\n\t}\n\n\tpublic boolean accept() {\n\t\treturn type != null && type.accept();\n\t}\n\n\tpublic boolean error() {\n\t\treturn type != null && type.error();\n\t}\n\n\tpublic boolean acceptClosure() {\n\t\tif (accept()) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\tfor (State state : getClosure()) {\n\t\t\t\tif (state.accept()) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic String getId() {\n\t\treturn String.valueOf(System.identityHashCode(this));\n\t}\n\n\tpublic void setType(TokenType type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic TokenType getType() {\n\t\treturn type;\n\t}\n\n\tpublic void addTransition(Transition transition) {\n\t\tif (!transitions.contains(transition)) {\n\t\t\tthis.transitions.add(transition);\n\t\t\tclearCaches();\n\t\t}\n\t}\n\n\tpublic int removeTransition(Transition transition) {\n\t\tint pos = transitions.indexOf(transition);\n\t\ttransitions.remove(pos);\n\t\twhile (pos > -1) {\n\t\t\tclearCaches();\n\t\t\tpos = transitions.indexOf(transition);\n\t\t}\n\t\treturn pos;\n\t}\n\n\tpublic void addTransitions(List<Transition> transitions) {\n\t\tfor (Transition transition : transitions) {\n\t\t\taddTransition(transition);\n\t\t}\n\t}\n\n\tpublic void replaceTransition(Transition transition, Transition replacetransition) {\n\t\tint pos = transitions.indexOf(transition);\n\t\twhile (pos > -1) {\n\t\t\ttransitions.remove(pos);\n\t\t\ttransitions.add(pos, replacetransition);\n\t\t\tclearCaches();\n\t\t\tpos = transitions.indexOf(transition);\n\t\t}\n\t}\n\n\tpublic void replaceTransition(Transition transition, List<Transition> replacetransitions) {\n\t\tint pos = transitions.indexOf(transition);\n\t\twhile (pos > -1) {\n\t\t\ttransitions.remove(pos);\n\t\t\ttransitions.addAll(pos, replacetransitions);\n\t\t\tclearCaches();\n\t\t\tpos = transitions.indexOf(transition);\n\t\t}\n\t}\n\n\tpublic List<Transition> getTransitions() {\n\t\treturn transitions;\n\t}\n\n\tpublic void setTransitions(List<Transition> transitions) {\n\t\tthis.transitions = transitions;\n\t\tclearCaches();\n\t}\n\n\tSortedSet<EventTransition> computeSortedEventTransitions() {\n\t\tSortedSet<EventTransition> sortedTransitions = new TreeSet<EventTransition>(new Comparator<EventTransition>() {\n\n\t\t\t@Override\n\t\t\tpublic int compare(EventTransition o1, EventTransition o2) {\n\t\t\t\tint result = o1.getFrom() - o2.getFrom();\n\t\t\t\tif (result == 0) {\n\t\t\t\t\tresult = o1.getTo() - o2.getTo();\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t});\n\t\tsortedTransitions.addAll(getEventTransitions());\n\t\treturn sortedTransitions;\n\t}\n\n\tList<EventTransition> getEventTransitions() {\n\t\tList<EventTransition> eventTransitions = new ArrayList<EventTransition>();\n\t\tfor (Transition transition : transitions) {\n\t\t\tif (transition instanceof EventTransition) {\n\t\t\t\teventTransitions.add((EventTransition) transition);\n\t\t\t}\n\t\t}\n\t\treturn eventTransitions;\n\t}\n\n\tpublic boolean inlineEpsilons(TokenTypeFactory tokenTypes) {\n\t\tboolean changed = false;\n\t\tfor (int i = 0; i < transitions.size(); i++) {\n\t\t\tTransition transition = transitions.get(i);\n\t\t\tif (transition instanceof EpsilonTransition) {\n\t\t\t\tState target = transition.getTarget();\n\t\t\t\ttype = tokenTypes.union(target.getType(), type);\n\t\t\t\ttransitions.remove(i);\n\t\t\t\tfor (Transition t : target.getTransitions()) {\n\t\t\t\t\tif (!transitions.contains(t)) {\n\t\t\t\t\t\ttransitions.add(i, t);\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ti--;\n\t\t\t\tchanged = true;\n\t\t\t}\n\t\t}\n\t\tif (changed) {\n\t\t\tclearCaches();\n\t\t}\n\t\treturn changed;\n\t}\n\n\tpublic void eliminateDuplicateTransitions() {\n\t\tint oldsize = transitions.size();\n\t\tSet<Transition> found = new HashSet<Transition>();\n\t\tIterator<Transition> transitionIterator = transitions.iterator();\n\t\twhile (transitionIterator.hasNext()) {\n\t\t\tTransition transition = transitionIterator.next();\n\t\t\tboolean success = found.add(transition);\n\t\t\tif (!success) {\n\t\t\t\ttransitionIterator.remove();\n\t\t\t}\n\t\t}\n\t\tif (oldsize != transitions.size()) {\n\t\t\tclearCaches();\n\t\t}\n\t}\n\n\tpublic void eliminateErrorTransitions() {\n\t\tint oldsize = transitions.size();\n\t\tIterator<Transition> transitionIterator = transitions.iterator();\n\t\twhile (transitionIterator.hasNext()) {\n\t\t\tTransition transition = transitionIterator.next();\n\t\t\tif (transition.getTarget().error()) {\n\t\t\t\ttransitionIterator.remove();\n\t\t\t}\n\t\t}\n\t\tif (oldsize != transitions.size()) {\n\t\t\tclearCaches();\n\t\t}\n\t}\n\n\tvoid mergeAdjacentTransitions() {\n\t\tSortedSet<EventTransition> sortedTransitions = computeSortedEventTransitions();\n\t\tLinkedList<EventTransition> mergedTransitions = new LinkedList<EventTransition>();\n\n\t\tfor (EventTransition transition : sortedTransitions) {\n\t\t\tif (mergedTransitions.isEmpty()) {\n\t\t\t\tmergedTransitions.add(transition);\n\t\t\t} else {\n\t\t\t\tEventTransition last = mergedTransitions.getLast();\n\t\t\t\tchar lastFrom = last.getFrom();\n\t\t\t\tchar lastTo = last.getTo();\n\t\t\t\tchar nextFrom = transition.getFrom();\n\t\t\t\tchar nextTo = transition.getTo();\n\t\t\t\tif (lastTo + 1 >= nextFrom && last.getTarget() == transition.getTarget()) {\n\t\t\t\t\tmergedTransitions.removeLast();\n\t\t\t\t\tchar from = lastFrom < nextFrom ? lastFrom : nextFrom;\n\t\t\t\t\tchar to = lastTo < nextTo ? nextTo : lastTo;\n\t\t\t\t\tmergedTransitions.add(new RangeTransition(from, to, last.getTarget()));\n\t\t\t\t} else {\n\t\t\t\t\tmergedTransitions.add(transition);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.transitions = new ArrayList<Transition>(mergedTransitions);\n\t}\n\n\tpublic SortedSet<Character> getRelevantCharacters() {\n\t\tSortedSet<Character> relevant = new TreeSet<Character>();\n\t\trelevant.add(Character.MIN_VALUE);\n\t\tfor (EventTransition transition : getSortedNextClosure()) {\n\t\t\tchar from = ((EventTransition) transition).getFrom();\n\t\t\trelevant.add(from);\n\n\t\t\tchar to = ((EventTransition) transition).getTo();\n\t\t\tif (to < Character.MAX_VALUE) {\n\t\t\t\trelevant.add(after(to));\n\t\t\t}\n\t\t}\n\t\treturn relevant;\n\t}\n\n\tprivate void clearCaches() {\n\t\tthis.closure = null;\n\t\tthis.nextclosure = null;\n\t}\n\n\tpublic List<State> getClosure() {\n\t\tif (closure == null) {\n\t\t\tclosure = computeClosure();\n\t\t}\n\t\treturn closure;\n\t}\n\n\tprivate List<State> computeClosure() {\n\t\tSet<State> closure = new LinkedHashSet<State>();\n\t\tList<State> todo = Lists.of(this);\n\t\twhile (!todo.isEmpty()) {\n\t\t\tState state = todo.remove(0);\n\t\t\tif (!closure.contains(state)) {\n\t\t\t\tclosure.add(state);\n\t\t\t\tfor (Transition transition : state.getTransitions()) {\n\t\t\t\t\tif (transition instanceof EpsilonTransition) {\n\t\t\t\t\t\ttodo.add(transition.getTarget());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn new ArrayList<State>(closure);\n\t}\n\n\tpublic List<EventTransition> getNextClosure() {\n\t\tif (nextclosure == null) {\n\t\t\tnextclosure = computeNextClosure();\n\t\t}\n\t\treturn nextclosure;\n\t}\n\n\tprivate List<EventTransition> computeNextClosure() {\n\t\tList<EventTransition> nexts = new ArrayList<EventTransition>();\n\t\tfor (State state : getClosure()) {\n\t\t\tfor (Transition transition : state.getTransitions()) {\n\t\t\t\tif (transition instanceof EventTransition) {\n\t\t\t\t\tnexts.add((EventTransition) transition);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nexts;\n\t}\n\n\tpublic Set<TokenType> getTypeClosure() {\n\t\tSet<TokenType> types = new HashSet<TokenType>();\n\t\tfor (State state : getClosure()) {\n\t\t\tTokenType stateType = state.getType();\n\t\t\tif (stateType != null) {\n\t\t\t\ttypes.add(stateType);\n\t\t\t}\n\t\t}\n\t\treturn types;\n\t}\n\n\tpublic List<EventTransition> getSortedNextClosure() {\n\t\tList<EventTransition> closure = new ArrayList<EventTransition>(getNextClosure());\n\t\tCollections.sort(closure, new TransitionComparator());\n\t\treturn closure;\n\t}\n\n\tpublic Set<State> getConnectedStates() {\n\t\tSet<State> reachable = new LinkedHashSet<State>();\n\t\tfor (Transition transition : transitions) {\n\t\t\treachable.add(transition.getTarget());\n\t\t}\n\t\treturn reachable;\n\t}\n\n\tpublic List<EventTransition> nexts(char ch) {\n\t\tList<EventTransition> nexts = new LinkedList<EventTransition>();\n\t\tfor (EventTransition transition : getNextClosure()) {\n\t\t\tif (transition.matches(ch)) {\n\t\t\t\tnexts.add(transition);\n\t\t\t}\n\t\t}\n\t\treturn nexts;\n\t}\n\n\t@Override\n\tpublic State clone() {\n\t\ttry {\n\t\t\tState clone = (State) super.clone();\n\t\t\tclone.type = type;\n\t\t\tclone.transitions = new ArrayList<Transition>(transitions.size());\n\t\t\treturn clone;\n\t\t} catch (CloneNotSupportedException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic <T> T apply(StateVisitor<T> visitor) {\n\t\treturn visitor.visitState(this);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder buffer = new StringBuilder(\"state(\").append(getId()).append(\")\\n\");\n\t\tfor (Transition transition : transitions) {\n\t\t\tbuffer.append('\\t').append(transition.toString()).append('\\n');\n\t\t}\n\t\treturn buffer.toString();\n\t}\n\n\tpublic void addErrorTransitions(State error) {\n\t\tchar min = Character.MAX_VALUE;\n\t\tchar max = Character.MIN_VALUE;\n\n\t\tchar current = Character.MIN_VALUE;\n\t\tfor (EventTransition transition : getSortedNextClosure()) {\n\t\t\tchar from = transition.getFrom();\n\t\t\tif (from < min) {\n\t\t\t\tmin = from;\n\t\t\t}\n\t\t\tchar to = transition.getTo();\n\t\t\tif (to > max) {\n\t\t\t\tmax = to;\n\t\t\t}\n\n\t\t\tif (from == current + 1) {\n\t\t\t\ttransitions.add(new ExactTransition(current, error));\n\t\t\t} else if (from > current) {\n\t\t\t\ttransitions.add(new RangeTransition(current, before(from), error));\n\t\t\t}\n\t\t\tcurrent = after(to);\n\t\t}\n\t\tif (max == Character.MAX_VALUE) {\n\t\t\t// MAX_VALUE already handled\n\t\t} else if (current == Character.MAX_VALUE) {\n\t\t\ttransitions.add(new ExactTransition(Character.MAX_VALUE, error));\n\t\t} else {// current < Character.MAX_VALUE\n\t\t\ttransitions.add(new RangeTransition(current, Character.MAX_VALUE, error));\n\t\t}\n\t\tclearCaches();\n\t}\n\n\tpublic State cloneTree() {\n\t\treturn new Clone(this).apply().start();\n\t}\n\n\tpublic Set<State> findAcceptStates() {\n\t\treturn new FindStates(this, new Predicate<State>() {\n\t\t\t@Override\n\t\t\tpublic boolean evaluate(State object) {\n\t\t\t\treturn object.accept();\n\t\t\t}\n\t\t}).apply().states();\n\t}\n\n\tpublic Set<State> findReachableStates() {\n\t\treturn new FindStates(this).apply().states();\n\t}\n\n\tpublic Set<State> findLiveStates() {\n\t\tSet<State> states = findReachableStates();\n\t\tMap<State, Set<State>> map = new HashMap<State, Set<State>>();\n\t\tfor (State s : states) {\n\t\t\tmap.put(s, new HashSet<State>());\n\t\t}\n\t\tfor (State s : states) {\n\t\t\tfor (Transition transition : s.getTransitions()) {\n\t\t\t\tmap.get(transition.getTarget()).add(s);\n\t\t\t}\n\t\t}\n\t\tSet<State> live = new HashSet<State>(findAcceptStates());\n\t\tLinkedList<State> worklist = new LinkedList<State>(live);\n\t\twhile (!worklist.isEmpty()) {\n\t\t\tState current = worklist.removeFirst();\n\t\t\tfor (State previous : map.get(current)) {\n\t\t\t\tif (!live.contains(previous)) {\n\t\t\t\t\tlive.add(previous);\n\t\t\t\t\tworklist.add(previous);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn live;\n\t}\n\n}", "public static class ThompsonAutomaton implements Cloneable {\n\tpublic GenericAutomaton automaton;\n\tpublic State start;\n\tpublic State end;\n\n\tpublic ThompsonAutomaton(GenericAutomaton automaton, State start, State end) {\n\t\tthis.automaton = automaton;\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t}\n\n\t@Override\n\tprotected ThompsonAutomaton clone() {\n\t\ttry {\n\t\t\tThompsonAutomaton clone = (ThompsonAutomaton) super.clone();\n\t\t\tTokenType oldTokenType = end.getType();\n\t\t\tend.setType(ThompsonToken.ACCEPT);\n\t\t\tclone.automaton = automaton.clone();\n\t\t\tclone.start = clone.automaton.getStart();\n\t\t\tclone.end = clone.automaton.findAcceptStates().iterator().next();\n\t\t\tend.setType(oldTokenType);\n\t\t\tclone.end.setType(oldTokenType);\n\t\t\treturn clone;\n\t\t} catch (CloneNotSupportedException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n}" ]
import static com.almondtools.rexlex.pattern.DefaultTokenType.ACCEPT; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ListIterator; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.automaton.GenericAutomaton.EpsilonTransition; import com.almondtools.rexlex.automaton.GenericAutomaton.ExactTransition; import com.almondtools.rexlex.automaton.GenericAutomaton.RangeTransition; import com.almondtools.rexlex.automaton.GenericAutomaton.State; import com.almondtools.rexlex.automaton.ThompsonAutomatonBuilder.ThompsonAutomaton; import net.amygdalum.regexparser.AlternativesNode; import net.amygdalum.regexparser.AnyCharNode; import net.amygdalum.regexparser.BoundedLoopNode; import net.amygdalum.regexparser.CharClassNode; import net.amygdalum.regexparser.CompClassNode; import net.amygdalum.regexparser.ConcatNode; import net.amygdalum.regexparser.EmptyNode; import net.amygdalum.regexparser.GroupNode; import net.amygdalum.regexparser.OptionalNode; import net.amygdalum.regexparser.RangeCharNode; import net.amygdalum.regexparser.RegexNode; import net.amygdalum.regexparser.RegexNodeVisitor; import net.amygdalum.regexparser.SingleCharNode; import net.amygdalum.regexparser.SpecialCharClassNode; import net.amygdalum.regexparser.StringNode; import net.amygdalum.regexparser.UnboundedLoopNode;
package com.almondtools.rexlex.automaton; public class ThompsonAutomatonBuilder implements RegexNodeVisitor<ThompsonAutomaton>, AutomatonBuilder { public ThompsonAutomatonBuilder() { } public static ThompsonAutomaton match(char value) { GenericAutomaton automaton = new GenericAutomaton();
State s = new State();
4
jaredrummler/TrueTypeParser
lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/complexscripts/scripts/ScriptProcessor.java
[ "public class GlyphSubstitutionTable extends GlyphTable {\n\n /** single substitution subtable type */\n public static final int GSUB_LOOKUP_TYPE_SINGLE = 1;\n /** multiple substitution subtable type */\n public static final int GSUB_LOOKUP_TYPE_MULTIPLE = 2;\n /** alternate substitution subtable type */\n public static final int GSUB_LOOKUP_TYPE_ALTERNATE = 3;\n /** ligature substitution subtable type */\n public static final int GSUB_LOOKUP_TYPE_LIGATURE = 4;\n /** contextual substitution subtable type */\n public static final int GSUB_LOOKUP_TYPE_CONTEXTUAL = 5;\n /** chained contextual substitution subtable type */\n public static final int GSUB_LOOKUP_TYPE_CHAINED_CONTEXTUAL = 6;\n /** extension substitution substitution subtable type */\n public static final int GSUB_LOOKUP_TYPE_EXTENSION_SUBSTITUTION = 7;\n /** reverse chained contextual single substitution subtable type */\n public static final int GSUB_LOOKUP_TYPE_REVERSE_CHAINED_SINGLE = 8;\n\n /**\n * Instantiate a <code>GlyphSubstitutionTable</code> object using the specified lookups\n * and subtables.\n *\n * @param gdef\n * glyph definition table that applies\n * @param lookups\n * a map of lookup specifications to subtable identifier strings\n * @param subtables\n * a list of identified subtables\n */\n public GlyphSubstitutionTable(GlyphDefinitionTable gdef, Map lookups, List subtables) {\n super(gdef, lookups);\n if ((subtables == null) || (subtables.size() == 0)) {\n throw new AdvancedTypographicTableFormatException(\"subtables must be non-empty\");\n } else {\n for (Iterator it = subtables.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (o instanceof GlyphSubstitutionSubtable) {\n addSubtable((GlyphSubtable) o);\n } else {\n throw new AdvancedTypographicTableFormatException(\"subtable must be a glyph substitution subtable\");\n }\n }\n freezeSubtables();\n }\n }\n\n /**\n * Perform substitution processing using all matching lookups.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @return the substituted (output) glyph sequence\n */\n public GlyphSequence substitute(GlyphSequence gs, String script, String language) {\n GlyphSequence ogs;\n Map/*<LookupSpec,List<LookupTable>>*/ lookups = matchLookups(script, language, \"*\");\n if ((lookups != null) && (lookups.size() > 0)) {\n ScriptProcessor sp = ScriptProcessor.getInstance(script);\n ogs = sp.substitute(this, gs, script, language, lookups);\n } else {\n ogs = gs;\n }\n return ogs;\n }\n\n /**\n * Map a lookup type name to its constant (integer) value.\n *\n * @param name\n * lookup type name\n * @return lookup type\n */\n public static int getLookupTypeFromName(String name) {\n int t;\n String s = name.toLowerCase();\n if (\"single\".equals(s)) {\n t = GSUB_LOOKUP_TYPE_SINGLE;\n } else if (\"multiple\".equals(s)) {\n t = GSUB_LOOKUP_TYPE_MULTIPLE;\n } else if (\"alternate\".equals(s)) {\n t = GSUB_LOOKUP_TYPE_ALTERNATE;\n } else if (\"ligature\".equals(s)) {\n t = GSUB_LOOKUP_TYPE_LIGATURE;\n } else if (\"contextual\".equals(s)) {\n t = GSUB_LOOKUP_TYPE_CONTEXTUAL;\n } else if (\"chainedcontextual\".equals(s)) {\n t = GSUB_LOOKUP_TYPE_CHAINED_CONTEXTUAL;\n } else if (\"extensionsubstitution\".equals(s)) {\n t = GSUB_LOOKUP_TYPE_EXTENSION_SUBSTITUTION;\n } else if (\"reversechainiingcontextualsingle\".equals(s)) {\n t = GSUB_LOOKUP_TYPE_REVERSE_CHAINED_SINGLE;\n } else {\n t = -1;\n }\n return t;\n }\n\n /**\n * Map a lookup type constant (integer) value to its name.\n *\n * @param type\n * lookup type\n * @return lookup type name\n */\n public static String getLookupTypeName(int type) {\n String tn = null;\n switch (type) {\n case GSUB_LOOKUP_TYPE_SINGLE:\n tn = \"single\";\n break;\n case GSUB_LOOKUP_TYPE_MULTIPLE:\n tn = \"multiple\";\n break;\n case GSUB_LOOKUP_TYPE_ALTERNATE:\n tn = \"alternate\";\n break;\n case GSUB_LOOKUP_TYPE_LIGATURE:\n tn = \"ligature\";\n break;\n case GSUB_LOOKUP_TYPE_CONTEXTUAL:\n tn = \"contextual\";\n break;\n case GSUB_LOOKUP_TYPE_CHAINED_CONTEXTUAL:\n tn = \"chainedcontextual\";\n break;\n case GSUB_LOOKUP_TYPE_EXTENSION_SUBSTITUTION:\n tn = \"extensionsubstitution\";\n break;\n case GSUB_LOOKUP_TYPE_REVERSE_CHAINED_SINGLE:\n tn = \"reversechainiingcontextualsingle\";\n break;\n default:\n tn = \"unknown\";\n break;\n }\n return tn;\n }\n\n /**\n * Create a substitution subtable according to the specified arguments.\n *\n * @param type\n * subtable type\n * @param id\n * subtable identifier\n * @param sequence\n * subtable sequence\n * @param flags\n * subtable flags\n * @param format\n * subtable format\n * @param coverage\n * subtable coverage table\n * @param entries\n * subtable entries\n * @return a glyph subtable instance\n */\n public static GlyphSubtable createSubtable(int type, String id, int sequence, int flags, int format,\n GlyphCoverageTable coverage, List entries) {\n GlyphSubtable st = null;\n switch (type) {\n case GSUB_LOOKUP_TYPE_SINGLE:\n st = SingleSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GSUB_LOOKUP_TYPE_MULTIPLE:\n st = MultipleSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GSUB_LOOKUP_TYPE_ALTERNATE:\n st = AlternateSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GSUB_LOOKUP_TYPE_LIGATURE:\n st = LigatureSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GSUB_LOOKUP_TYPE_CONTEXTUAL:\n st = ContextualSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GSUB_LOOKUP_TYPE_CHAINED_CONTEXTUAL:\n st = ChainedContextualSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GSUB_LOOKUP_TYPE_REVERSE_CHAINED_SINGLE:\n st = ReverseChainedSingleSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n default:\n break;\n }\n return st;\n }\n\n /**\n * Create a substitution subtable according to the specified arguments.\n *\n * @param type\n * subtable type\n * @param id\n * subtable identifier\n * @param sequence\n * subtable sequence\n * @param flags\n * subtable flags\n * @param format\n * subtable format\n * @param coverage\n * list of coverage table entries\n * @param entries\n * subtable entries\n * @return a glyph subtable instance\n */\n public static GlyphSubtable createSubtable(int type, String id, int sequence, int flags, int format, List coverage,\n List entries) {\n return createSubtable(type, id, sequence, flags, format, GlyphCoverageTable.createCoverageTable(coverage), entries);\n }\n\n private abstract static class SingleSubtable extends GlyphSubstitutionSubtable {\n\n SingleSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GSUB_LOOKUP_TYPE_SINGLE;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof SingleSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean substitute(GlyphSubstitutionState ss) {\n int gi = ss.getGlyph();\n int ci;\n if ((ci = getCoverageIndex(gi)) < 0) {\n return false;\n } else {\n int go = getGlyphForCoverageIndex(ci, gi);\n if ((go < 0) || (go > 65535)) {\n go = 65535;\n }\n ss.putGlyph(go, ss.getAssociation(), Boolean.TRUE);\n ss.consume(1);\n return true;\n }\n }\n\n /**\n * Obtain glyph for coverage index.\n *\n * @param ci\n * coverage index\n * @param gi\n * original glyph index\n * @return substituted glyph value\n * @throws IllegalArgumentException\n * if coverage index is not valid\n */\n public abstract int getGlyphForCoverageIndex(int ci, int gi) throws IllegalArgumentException;\n\n static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new SingleSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else if (format == 2) {\n return new SingleSubtableFormat2(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class SingleSubtableFormat1 extends SingleSubtable {\n\n private int delta;\n private int ciMax;\n\n SingleSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n List entries = new ArrayList(1);\n entries.add(Integer.valueOf(delta));\n return entries;\n }\n\n /** {@inheritDoc} */\n public int getGlyphForCoverageIndex(int ci, int gi) throws IllegalArgumentException {\n if (ci <= ciMax) {\n return gi + delta;\n } else {\n throw new IllegalArgumentException(\n \"coverage index \" + ci + \" out of range, maximum coverage index is \" + ciMax);\n }\n }\n\n private void populate(List entries) {\n if ((entries == null) || (entries.size() != 1)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, must be non-null and contain exactly one entry\");\n } else {\n Object o = entries.get(0);\n int delta = 0;\n if (o instanceof Integer) {\n delta = ((Integer) o).intValue();\n } else {\n throw new AdvancedTypographicTableFormatException(\"illegal entries entry, must be Integer, but is: \" + o);\n }\n this.delta = delta;\n this.ciMax = getCoverageSize() - 1;\n }\n }\n }\n\n private static class SingleSubtableFormat2 extends SingleSubtable {\n\n private int[] glyphs;\n\n SingleSubtableFormat2(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n List entries = new ArrayList(glyphs.length);\n for (int i = 0, n = glyphs.length; i < n; i++) {\n entries.add(Integer.valueOf(glyphs[i]));\n }\n return entries;\n }\n\n /** {@inheritDoc} */\n public int getGlyphForCoverageIndex(int ci, int gi) throws IllegalArgumentException {\n if (glyphs == null) {\n return -1;\n } else if (ci >= glyphs.length) {\n throw new IllegalArgumentException(\n \"coverage index \" + ci + \" out of range, maximum coverage index is \" + glyphs.length);\n } else {\n return glyphs[ci];\n }\n }\n\n private void populate(List entries) {\n int i = 0;\n int n = entries.size();\n int[] glyphs = new int[n];\n for (Iterator it = entries.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (o instanceof Integer) {\n int gid = ((Integer) o).intValue();\n if ((gid >= 0) && (gid < 65536)) {\n glyphs[i++] = gid;\n } else {\n throw new AdvancedTypographicTableFormatException(\"illegal glyph index: \" + gid);\n }\n } else {\n throw new AdvancedTypographicTableFormatException(\"illegal entries entry, must be Integer: \" + o);\n }\n }\n assert i == n;\n assert this.glyphs == null;\n this.glyphs = glyphs;\n }\n }\n\n private abstract static class MultipleSubtable extends GlyphSubstitutionSubtable {\n\n public MultipleSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GSUB_LOOKUP_TYPE_MULTIPLE;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof MultipleSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean substitute(GlyphSubstitutionState ss) {\n int gi = ss.getGlyph();\n int ci;\n if ((ci = getCoverageIndex(gi)) < 0) {\n return false;\n } else {\n int[] ga = getGlyphsForCoverageIndex(ci, gi);\n if (ga != null) {\n ss.putGlyphs(ga, CharAssociation.replicate(ss.getAssociation(), ga.length), Boolean.TRUE);\n ss.consume(1);\n }\n return true;\n }\n }\n\n /**\n * Obtain glyph sequence for coverage index.\n *\n * @param ci\n * coverage index\n * @param gi\n * original glyph index\n * @return sequence of glyphs to substitute for input glyph\n * @throws IllegalArgumentException\n * if coverage index is not valid\n */\n public abstract int[] getGlyphsForCoverageIndex(int ci, int gi) throws IllegalArgumentException;\n\n static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new MultipleSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class MultipleSubtableFormat1 extends MultipleSubtable {\n\n private int[][] gsa; // glyph sequence array, ordered by coverage index\n\n MultipleSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (gsa != null) {\n List entries = new ArrayList(1);\n entries.add(gsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public int[] getGlyphsForCoverageIndex(int ci, int gi) throws IllegalArgumentException {\n if (gsa == null) {\n return null;\n } else if (ci >= gsa.length) {\n throw new IllegalArgumentException(\n \"coverage index \" + ci + \" out of range, maximum coverage index is \" + gsa.length);\n } else {\n return gsa[ci];\n }\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof int[][])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an int[][], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n gsa = (int[][]) o;\n }\n }\n }\n }\n\n private abstract static class AlternateSubtable extends GlyphSubstitutionSubtable {\n\n public AlternateSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GSUB_LOOKUP_TYPE_ALTERNATE;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof AlternateSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean substitute(GlyphSubstitutionState ss) {\n int gi = ss.getGlyph();\n int ci;\n if ((ci = getCoverageIndex(gi)) < 0) {\n return false;\n } else {\n int[] ga = getAlternatesForCoverageIndex(ci, gi);\n int ai = ss.getAlternatesIndex(ci);\n int go;\n if ((ai < 0) || (ai >= ga.length)) {\n go = gi;\n } else {\n go = ga[ai];\n }\n if ((go < 0) || (go > 65535)) {\n go = 65535;\n }\n ss.putGlyph(go, ss.getAssociation(), Boolean.TRUE);\n ss.consume(1);\n return true;\n }\n }\n\n /**\n * Obtain glyph alternates for coverage index.\n *\n * @param ci\n * coverage index\n * @param gi\n * original glyph index\n * @return sequence of glyphs to substitute for input glyph\n * @throws IllegalArgumentException\n * if coverage index is not valid\n */\n public abstract int[] getAlternatesForCoverageIndex(int ci, int gi) throws IllegalArgumentException;\n\n static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new AlternateSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class AlternateSubtableFormat1 extends AlternateSubtable {\n\n private int[][] gaa; // glyph alternates array, ordered by coverage index\n\n AlternateSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n List entries = new ArrayList(gaa.length);\n for (int i = 0, n = gaa.length; i < n; i++) {\n entries.add(gaa[i]);\n }\n return entries;\n }\n\n /** {@inheritDoc} */\n public int[] getAlternatesForCoverageIndex(int ci, int gi) throws IllegalArgumentException {\n if (gaa == null) {\n return null;\n } else if (ci >= gaa.length) {\n throw new IllegalArgumentException(\n \"coverage index \" + ci + \" out of range, maximum coverage index is \" + gaa.length);\n } else {\n return gaa[ci];\n }\n }\n\n private void populate(List entries) {\n int i = 0;\n int n = entries.size();\n int[][] gaa = new int[n][];\n for (Iterator it = entries.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (o instanceof int[]) {\n gaa[i++] = (int[]) o;\n } else {\n throw new AdvancedTypographicTableFormatException(\"illegal entries entry, must be int[]: \" + o);\n }\n }\n assert i == n;\n assert this.gaa == null;\n this.gaa = gaa;\n }\n }\n\n private abstract static class LigatureSubtable extends GlyphSubstitutionSubtable {\n\n public LigatureSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GSUB_LOOKUP_TYPE_LIGATURE;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof LigatureSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean substitute(GlyphSubstitutionState ss) {\n int gi = ss.getGlyph();\n int ci;\n if ((ci = getCoverageIndex(gi)) < 0) {\n return false;\n } else {\n LigatureSet ls = getLigatureSetForCoverageIndex(ci, gi);\n if (ls != null) {\n boolean reverse = false;\n GlyphTester ignores = ss.getIgnoreDefault();\n int[] counts = ss.getGlyphsAvailable(0, reverse, ignores);\n int nga = counts[0];\n int ngi;\n if (nga > 1) {\n int[] iga = ss.getGlyphs(0, nga, reverse, ignores, null, counts);\n Ligature l = findLigature(ls, iga);\n if (l != null) {\n int go = l.getLigature();\n if ((go < 0) || (go > 65535)) {\n go = 65535;\n }\n int nmg = 1 + l.getNumComponents();\n // fetch matched number of component glyphs to determine matched and ignored count\n ss.getGlyphs(0, nmg, reverse, ignores, null, counts);\n nga = counts[0];\n ngi = counts[1];\n // fetch associations of matched component glyphs\n CharAssociation[] laa = ss.getAssociations(0, nga);\n // output ligature glyph and its association\n ss.putGlyph(go, CharAssociation.join(laa), Boolean.TRUE);\n // fetch and output ignored glyphs (if necessary)\n if (ngi > 0) {\n ss.putGlyphs(ss.getIgnoredGlyphs(0, ngi), ss.getIgnoredAssociations(0, ngi), null);\n }\n ss.consume(nga + ngi);\n }\n }\n }\n return true;\n }\n }\n\n private Ligature findLigature(LigatureSet ls, int[] glyphs) {\n Ligature[] la = ls.getLigatures();\n int k = -1;\n int maxComponents = -1;\n for (int i = 0, n = la.length; i < n; i++) {\n Ligature l = la[i];\n if (l.matchesComponents(glyphs)) {\n int nc = l.getNumComponents();\n if (nc > maxComponents) {\n maxComponents = nc;\n k = i;\n }\n }\n }\n if (k >= 0) {\n return la[k];\n } else {\n return null;\n }\n }\n\n /**\n * Obtain ligature set for coverage index.\n *\n * @param ci\n * coverage index\n * @param gi\n * original glyph index\n * @return ligature set (or null if none defined)\n * @throws IllegalArgumentException\n * if coverage index is not valid\n */\n public abstract LigatureSet getLigatureSetForCoverageIndex(int ci, int gi) throws IllegalArgumentException;\n\n static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new LigatureSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class LigatureSubtableFormat1 extends LigatureSubtable {\n\n private LigatureSet[] ligatureSets;\n\n public LigatureSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n List entries = new ArrayList(ligatureSets.length);\n for (int i = 0, n = ligatureSets.length; i < n; i++) {\n entries.add(ligatureSets[i]);\n }\n return entries;\n }\n\n /** {@inheritDoc} */\n public LigatureSet getLigatureSetForCoverageIndex(int ci, int gi) throws IllegalArgumentException {\n if (ligatureSets == null) {\n return null;\n } else if (ci >= ligatureSets.length) {\n throw new IllegalArgumentException(\n \"coverage index \" + ci + \" out of range, maximum coverage index is \" + ligatureSets.length);\n } else {\n return ligatureSets[ci];\n }\n }\n\n private void populate(List entries) {\n int i = 0;\n int n = entries.size();\n LigatureSet[] ligatureSets = new LigatureSet[n];\n for (Iterator it = entries.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (o instanceof LigatureSet) {\n ligatureSets[i++] = (LigatureSet) o;\n } else {\n throw new AdvancedTypographicTableFormatException(\"illegal ligatures entry, must be LigatureSet: \" + o);\n }\n }\n assert i == n;\n assert this.ligatureSets == null;\n this.ligatureSets = ligatureSets;\n }\n }\n\n private abstract static class ContextualSubtable extends GlyphSubstitutionSubtable {\n\n public ContextualSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GSUB_LOOKUP_TYPE_CONTEXTUAL;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof ContextualSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean substitute(GlyphSubstitutionState ss) {\n int gi = ss.getGlyph();\n int ci;\n if ((ci = getCoverageIndex(gi)) < 0) {\n return false;\n } else {\n int[] rv = new int[1];\n RuleLookup[] la = getLookups(ci, gi, ss, rv);\n if (la != null) {\n ss.apply(la, rv[0]);\n }\n return true;\n }\n }\n\n /**\n * Obtain rule lookups set associated current input glyph context.\n *\n * @param ci\n * coverage index of glyph at current position\n * @param gi\n * glyph index of glyph at current position\n * @param ss\n * glyph substitution state\n * @param rv\n * array of ints used to receive multiple return values, must be of length 1 or greater,\n * where the first entry is used to return the input sequence length of the matched rule\n * @return array of rule lookups or null if none applies\n */\n public abstract RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv);\n\n static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new ContextualSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else if (format == 2) {\n return new ContextualSubtableFormat2(id, sequence, flags, format, coverage, entries);\n } else if (format == 3) {\n return new ContextualSubtableFormat3(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class ContextualSubtableFormat1 extends ContextualSubtable {\n\n private RuleSet[] rsa; // rule set array, ordered by glyph coverage index\n\n ContextualSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(1);\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {\n assert ss != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedGlyphSequenceRule)) {\n ChainedGlyphSequenceRule cr = (ChainedGlyphSequenceRule) r;\n int[] iga = cr.getGlyphs(gi);\n if (matches(ss, iga, 0, rv)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n return null;\n }\n\n static boolean matches(GlyphSubstitutionState ss, int[] glyphs, int offset, int[] rv) {\n if ((glyphs == null) || (glyphs.length == 0)) {\n return true; // match null or empty glyph sequence\n } else {\n boolean reverse = offset < 0;\n GlyphTester ignores = ss.getIgnoreDefault();\n int[] counts = ss.getGlyphsAvailable(offset, reverse, ignores);\n int nga = counts[0];\n int ngm = glyphs.length;\n if (nga < ngm) {\n return false; // insufficient glyphs available to match\n } else {\n int[] ga = ss.getGlyphs(offset, ngm, reverse, ignores, null, counts);\n for (int k = 0; k < ngm; k++) {\n if (ga[k] != glyphs[k]) {\n return false; // match fails at ga [ k ]\n }\n }\n if (rv != null) {\n rv[0] = counts[0] + counts[1];\n }\n return true; // all glyphs match\n }\n }\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n }\n }\n }\n }\n\n private static class ContextualSubtableFormat2 extends ContextualSubtable {\n\n private GlyphClassTable cdt; // class def table\n private int ngc; // class set count\n private RuleSet[] rsa; // rule set array, ordered by class number [0...ngc - 1]\n\n ContextualSubtableFormat2(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(3);\n entries.add(cdt);\n entries.add(Integer.valueOf(ngc));\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {\n assert ss != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedClassSequenceRule)) {\n ChainedClassSequenceRule cr = (ChainedClassSequenceRule) r;\n int[] ca = cr.getClasses(cdt.getClassIndex(gi, ss.getClassMatchSet(gi)));\n if (matches(ss, cdt, ca, 0, rv)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n return null;\n }\n\n static boolean matches(GlyphSubstitutionState ss, GlyphClassTable cdt, int[] classes, int offset, int[] rv) {\n if ((cdt == null) || (classes == null) || (classes.length == 0)) {\n return true; // match null class definitions, null or empty class sequence\n } else {\n boolean reverse = offset < 0;\n GlyphTester ignores = ss.getIgnoreDefault();\n int[] counts = ss.getGlyphsAvailable(offset, reverse, ignores);\n int nga = counts[0];\n int ngm = classes.length;\n if (nga < ngm) {\n return false; // insufficient glyphs available to match\n } else {\n int[] ga = ss.getGlyphs(offset, ngm, reverse, ignores, null, counts);\n for (int k = 0; k < ngm; k++) {\n int gi = ga[k];\n int ms = ss.getClassMatchSet(gi);\n int gc = cdt.getClassIndex(gi, ms);\n if ((gc < 0) || (gc >= cdt.getClassSize(ms))) {\n return false; // none or invalid class fails mat ch\n } else if (gc != classes[k]) {\n return false; // match fails at ga [ k ]\n }\n }\n if (rv != null) {\n rv[0] = counts[0] + counts[1];\n }\n return true; // all glyphs match\n }\n }\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 3) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 3 entries\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an GlyphClassTable, but is: \" +\n ((o != null) ? o.getClass() : null));\n } else {\n cdt = (GlyphClassTable) o;\n }\n if (((o = entries.get(1)) == null) || !(o instanceof Integer)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, second entry must be an Integer, but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n ngc = ((Integer) (o)).intValue();\n }\n if (((o = entries.get(2)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, third entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n if (rsa.length != ngc) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, RuleSet[] length is \" + rsa.length + \", but expected \" + ngc + \" glyph classes\");\n }\n }\n }\n }\n }\n\n private static class ContextualSubtableFormat3 extends ContextualSubtable {\n\n private RuleSet[] rsa; // rule set array, containing a single rule set\n\n ContextualSubtableFormat3(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(1);\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {\n assert ss != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedCoverageSequenceRule)) {\n ChainedCoverageSequenceRule cr = (ChainedCoverageSequenceRule) r;\n GlyphCoverageTable[] gca = cr.getCoverages();\n if (matches(ss, gca, 0, rv)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n return null;\n }\n\n static boolean matches(GlyphSubstitutionState ss, GlyphCoverageTable[] gca, int offset, int[] rv) {\n if ((gca == null) || (gca.length == 0)) {\n return true; // match null or empty coverage array\n } else {\n boolean reverse = offset < 0;\n GlyphTester ignores = ss.getIgnoreDefault();\n int[] counts = ss.getGlyphsAvailable(offset, reverse, ignores);\n int nga = counts[0];\n int ngm = gca.length;\n if (nga < ngm) {\n return false; // insufficient glyphs available to match\n } else {\n int[] ga = ss.getGlyphs(offset, ngm, reverse, ignores, null, counts);\n for (int k = 0; k < ngm; k++) {\n GlyphCoverageTable ct = gca[k];\n if (ct != null) {\n if (ct.getCoverageIndex(ga[k]) < 0) {\n return false; // match fails at ga [ k ]\n }\n }\n }\n if (rv != null) {\n rv[0] = counts[0] + counts[1];\n }\n return true; // all glyphs match\n }\n }\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n }\n }\n }\n }\n\n private abstract static class ChainedContextualSubtable extends GlyphSubstitutionSubtable {\n\n public ChainedContextualSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GSUB_LOOKUP_TYPE_CHAINED_CONTEXTUAL;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof ChainedContextualSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean substitute(GlyphSubstitutionState ss) {\n int gi = ss.getGlyph();\n int ci;\n if ((ci = getCoverageIndex(gi)) < 0) {\n return false;\n } else {\n int[] rv = new int[1];\n RuleLookup[] la = getLookups(ci, gi, ss, rv);\n if (la != null) {\n ss.apply(la, rv[0]);\n return true;\n } else {\n return false;\n }\n }\n }\n\n /**\n * Obtain rule lookups set associated current input glyph context.\n *\n * @param ci\n * coverage index of glyph at current position\n * @param gi\n * glyph index of glyph at current position\n * @param ss\n * glyph substitution state\n * @param rv\n * array of ints used to receive multiple return values, must be of length 1 or greater\n * @return array of rule lookups or null if none applies\n */\n public abstract RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv);\n\n static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new ChainedContextualSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else if (format == 2) {\n return new ChainedContextualSubtableFormat2(id, sequence, flags, format, coverage, entries);\n } else if (format == 3) {\n return new ChainedContextualSubtableFormat3(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class ChainedContextualSubtableFormat1 extends ChainedContextualSubtable {\n\n private RuleSet[] rsa; // rule set array, ordered by glyph coverage index\n\n ChainedContextualSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(1);\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {\n assert ss != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedGlyphSequenceRule)) {\n ChainedGlyphSequenceRule cr = (ChainedGlyphSequenceRule) r;\n int[] iga = cr.getGlyphs(gi);\n if (matches(ss, iga, 0, rv)) {\n int[] bga = cr.getBacktrackGlyphs();\n if (matches(ss, bga, -1, null)) {\n int[] lga = cr.getLookaheadGlyphs();\n if (matches(ss, lga, rv[0], null)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n }\n }\n return null;\n }\n\n private boolean matches(GlyphSubstitutionState ss, int[] glyphs, int offset, int[] rv) {\n return ContextualSubtableFormat1.matches(ss, glyphs, offset, rv);\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n }\n }\n }\n }\n\n private static class ChainedContextualSubtableFormat2 extends ChainedContextualSubtable {\n\n private GlyphClassTable icdt; // input class def table\n private GlyphClassTable bcdt; // backtrack class def table\n private GlyphClassTable lcdt; // lookahead class def table\n private int ngc; // class set count\n private RuleSet[] rsa; // rule set array, ordered by class number [0...ngc - 1]\n\n ChainedContextualSubtableFormat2(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(5);\n entries.add(icdt);\n entries.add(bcdt);\n entries.add(lcdt);\n entries.add(Integer.valueOf(ngc));\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {\n assert ss != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedClassSequenceRule)) {\n ChainedClassSequenceRule cr = (ChainedClassSequenceRule) r;\n int[] ica = cr.getClasses(icdt.getClassIndex(gi, ss.getClassMatchSet(gi)));\n if (matches(ss, icdt, ica, 0, rv)) {\n int[] bca = cr.getBacktrackClasses();\n if (matches(ss, bcdt, bca, -1, null)) {\n int[] lca = cr.getLookaheadClasses();\n if (matches(ss, lcdt, lca, rv[0], null)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n }\n }\n return null;\n }\n\n private boolean matches(GlyphSubstitutionState ss, GlyphClassTable cdt, int[] classes, int offset, int[] rv) {\n return ContextualSubtableFormat2.matches(ss, cdt, classes, offset, rv);\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 5) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 5 entries\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an GlyphClassTable, but is: \" +\n ((o != null) ? o.getClass() : null));\n } else {\n icdt = (GlyphClassTable) o;\n }\n if (((o = entries.get(1)) != null) && !(o instanceof GlyphClassTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, second entry must be an GlyphClassTable, but is: \" + o.getClass());\n } else {\n bcdt = (GlyphClassTable) o;\n }\n if (((o = entries.get(2)) != null) && !(o instanceof GlyphClassTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, third entry must be an GlyphClassTable, but is: \" + o.getClass());\n } else {\n lcdt = (GlyphClassTable) o;\n }\n if (((o = entries.get(3)) == null) || !(o instanceof Integer)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, fourth entry must be an Integer, but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n ngc = ((Integer) (o)).intValue();\n }\n if (((o = entries.get(4)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, fifth entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n if (rsa.length != ngc) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, RuleSet[] length is \" + rsa.length + \", but expected \" + ngc + \" glyph classes\");\n }\n }\n }\n }\n }\n\n private static class ChainedContextualSubtableFormat3 extends ChainedContextualSubtable {\n\n private RuleSet[] rsa; // rule set array, containing a single rule set\n\n ChainedContextualSubtableFormat3(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(1);\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphSubstitutionState ss, int[] rv) {\n assert ss != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedCoverageSequenceRule)) {\n ChainedCoverageSequenceRule cr = (ChainedCoverageSequenceRule) r;\n GlyphCoverageTable[] igca = cr.getCoverages();\n if (matches(ss, igca, 0, rv)) {\n GlyphCoverageTable[] bgca = cr.getBacktrackCoverages();\n if (matches(ss, bgca, -1, null)) {\n GlyphCoverageTable[] lgca = cr.getLookaheadCoverages();\n if (matches(ss, lgca, rv[0], null)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n }\n }\n return null;\n }\n\n private boolean matches(GlyphSubstitutionState ss, GlyphCoverageTable[] gca, int offset, int[] rv) {\n return ContextualSubtableFormat3.matches(ss, gca, offset, rv);\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n }\n }\n }\n }\n\n private abstract static class ReverseChainedSingleSubtable extends GlyphSubstitutionSubtable {\n\n public ReverseChainedSingleSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GSUB_LOOKUP_TYPE_REVERSE_CHAINED_SINGLE;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof ReverseChainedSingleSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean usesReverseScan() {\n return true;\n }\n\n static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new ReverseChainedSingleSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class ReverseChainedSingleSubtableFormat1 extends ReverseChainedSingleSubtable {\n\n ReverseChainedSingleSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n return null;\n }\n\n private void populate(List entries) {\n }\n }\n\n /**\n * The <code>Ligature</code> class implements a ligature lookup result in terms of\n * a ligature glyph (code) and the <emph>N+1...</emph> components that comprise the ligature,\n * where the <emph>Nth</emph> component was consumed in the coverage table lookup mapping to\n * this ligature instance.\n */\n public static class Ligature {\n\n private final int ligature; // (resulting) ligature glyph\n private final int[] components; // component glyph codes (note that first component is implied)\n\n /**\n * Instantiate a ligature.\n *\n * @param ligature\n * glyph id\n * @param components\n * sequence of <emph>N+1...</emph> component glyph (or character) identifiers\n */\n public Ligature(int ligature, int[] components) {\n if ((ligature < 0) || (ligature > 65535)) {\n throw new AdvancedTypographicTableFormatException(\"invalid ligature glyph index: \" + ligature);\n } else if (components == null) {\n throw new AdvancedTypographicTableFormatException(\"invalid ligature components, must be non-null array\");\n } else {\n for (int i = 0, n = components.length; i < n; i++) {\n int gc = components[i];\n if ((gc < 0) || (gc > 65535)) {\n throw new AdvancedTypographicTableFormatException(\"invalid component glyph index: \" + gc);\n }\n }\n this.ligature = ligature;\n this.components = components;\n }\n }\n\n /** @return ligature glyph id */\n public int getLigature() {\n return ligature;\n }\n\n /** @return array of <emph>N+1...</emph> components */\n public int[] getComponents() {\n return components;\n }\n\n /** @return components count */\n public int getNumComponents() {\n return components.length;\n }\n\n /**\n * Determine if input sequence at offset matches ligature's components.\n *\n * @param glyphs\n * array of glyph components to match (including first, implied glyph)\n * @return true if matches\n */\n public boolean matchesComponents(int[] glyphs) {\n if (glyphs.length < (components.length + 1)) {\n return false;\n } else {\n for (int i = 0, n = components.length; i < n; i++) {\n if (glyphs[i + 1] != components[i]) {\n return false;\n }\n }\n return true;\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{components={\");\n for (int i = 0, n = components.length; i < n; i++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(Integer.toString(components[i]));\n }\n sb.append(\"},ligature=\");\n sb.append(Integer.toString(ligature));\n sb.append(\"}\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>LigatureSet</code> class implements a set of ligatures.\n */\n public static class LigatureSet {\n\n private final Ligature[] ligatures;\n // set of ligatures all of which share the first (implied) component\n private final int maxComponents; // maximum number of components (including first)\n\n /**\n * Instantiate a set of ligatures.\n *\n * @param ligatures\n * collection of ligatures\n */\n public LigatureSet(List ligatures) {\n this((Ligature[]) ligatures.toArray(new Ligature[ligatures.size()]));\n }\n\n /**\n * Instantiate a set of ligatures.\n *\n * @param ligatures\n * array of ligatures\n */\n public LigatureSet(Ligature[] ligatures) {\n if (ligatures == null) {\n throw new AdvancedTypographicTableFormatException(\"invalid ligatures, must be non-null array\");\n } else {\n this.ligatures = ligatures;\n int ncMax = -1;\n for (int i = 0, n = ligatures.length; i < n; i++) {\n Ligature l = ligatures[i];\n int nc = l.getNumComponents() + 1;\n if (nc > ncMax) {\n ncMax = nc;\n }\n }\n maxComponents = ncMax;\n }\n }\n\n /** @return array of ligatures in this ligature set */\n public Ligature[] getLigatures() {\n return ligatures;\n }\n\n /** @return count of ligatures in this ligature set */\n public int getNumLigatures() {\n return ligatures.length;\n }\n\n /** @return maximum number of components in one ligature (including first component) */\n public int getMaxComponents() {\n return maxComponents;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ligs={\");\n for (int i = 0, n = ligatures.length; i < n; i++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(ligatures[i]);\n }\n sb.append(\"}}\");\n return sb.toString();\n }\n\n }\n\n}", "public class GlyphTable {\n\n /** substitution glyph table type */\n public static final int GLYPH_TABLE_TYPE_SUBSTITUTION = 1;\n /** positioning glyph table type */\n public static final int GLYPH_TABLE_TYPE_POSITIONING = 2;\n /** justification glyph table type */\n public static final int GLYPH_TABLE_TYPE_JUSTIFICATION = 3;\n /** baseline glyph table type */\n public static final int GLYPH_TABLE_TYPE_BASELINE = 4;\n /** definition glyph table type */\n public static final int GLYPH_TABLE_TYPE_DEFINITION = 5;\n\n // (optional) glyph definition table in table types other than glyph definition table\n private GlyphTable gdef;\n\n // map from lookup specs to lists of strings, each of which identifies a lookup table (consisting of one or more subtables)\n private Map<LookupSpec, List<String>> lookups;\n\n // map from lookup identifiers to lookup tables\n private Map<String, LookupTable> lookupTables;\n\n // cache for lookups matching\n private Map<LookupSpec, Map<LookupSpec, List<LookupTable>>> matchedLookups;\n\n // if true, then prevent further subtable addition\n private boolean frozen;\n\n /**\n * Instantiate glyph table with specified lookups.\n *\n * @param gdef\n * glyph definition table that applies\n * @param lookups\n * map from lookup specs to lookup tables\n */\n public GlyphTable(GlyphTable gdef, Map<LookupSpec, List<String>> lookups) {\n if ((gdef != null) && !(gdef instanceof GlyphDefinitionTable)) {\n throw new AdvancedTypographicTableFormatException(\"bad glyph definition table\");\n } else if (lookups == null) {\n throw new AdvancedTypographicTableFormatException(\"lookups must be non-null map\");\n } else {\n this.gdef = gdef;\n this.lookups = lookups;\n this.lookupTables = new LinkedHashMap<>();\n this.matchedLookups = new HashMap<>();\n }\n }\n\n /**\n * Obtain glyph definition table.\n *\n * @return (possibly null) glyph definition table\n */\n public GlyphDefinitionTable getGlyphDefinitions() {\n return (GlyphDefinitionTable) gdef;\n }\n\n /**\n * Obtain list of all lookup specifications.\n *\n * @return (possibly empty) list of all lookup specifications\n */\n public List<LookupSpec> getLookups() {\n return matchLookupSpecs(\"*\", \"*\", \"*\");\n }\n\n /**\n * Obtain ordered list of all lookup tables, where order is by lookup identifier, which\n * lexicographic ordering follows the lookup list order.\n *\n * @return (possibly empty) ordered list of all lookup tables\n */\n public List<LookupTable> getLookupTables() {\n TreeSet<String> lids = new TreeSet<>(lookupTables.keySet());\n List<LookupTable> ltl = new ArrayList<>(lids.size());\n for (String lid : lids) {\n ltl.add(lookupTables.get(lid));\n }\n return ltl;\n }\n\n /**\n * Obtain lookup table by lookup id. This method is used by test code, and provides\n * access to embedded lookups not normally accessed by {script, language, feature} lookup spec.\n *\n * @param lid\n * lookup id\n * @return table associated with lookup id or null if none\n */\n public LookupTable getLookupTable(String lid) {\n return lookupTables.get(lid);\n }\n\n /**\n * Add a subtable.\n *\n * @param subtable\n * a (non-null) glyph subtable\n */\n protected void addSubtable(GlyphSubtable subtable) {\n // ensure table is not frozen\n if (frozen) {\n throw new IllegalStateException(\"glyph table is frozen, subtable addition prohibited\");\n }\n // set subtable's table reference to this table\n subtable.setTable(this);\n // add subtable to this table's subtable collection\n String lid = subtable.getLookupId();\n if (lookupTables.containsKey(lid)) {\n LookupTable lt = lookupTables.get(lid);\n lt.addSubtable(subtable);\n } else {\n LookupTable lt = new LookupTable(lid, subtable);\n lookupTables.put(lid, lt);\n }\n }\n\n /**\n * Freeze subtables, i.e., do not allow further subtable addition, and\n * create resulting cached state.\n */\n protected void freezeSubtables() {\n if (!frozen) {\n for (LookupTable lt : lookupTables.values()) {\n lt.freezeSubtables(lookupTables);\n }\n frozen = true;\n }\n }\n\n /**\n * Match lookup specifications according to <script,language,feature> tuple, where\n * '*' is a wildcard for a tuple component.\n *\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n * @return a (possibly empty) array of matching lookup specifications\n */\n public List<LookupSpec> matchLookupSpecs(String script, String language, String feature) {\n Set<LookupSpec> keys = lookups.keySet();\n List<LookupSpec> matches = new ArrayList<>();\n for (LookupSpec ls : keys) {\n if (!\"*\".equals(script)) {\n if (!ls.getScript().equals(script)) {\n continue;\n }\n }\n if (!\"*\".equals(language)) {\n if (!ls.getLanguage().equals(language)) {\n continue;\n }\n }\n if (!\"*\".equals(feature)) {\n if (!ls.getFeature().equals(feature)) {\n continue;\n }\n }\n matches.add(ls);\n }\n return matches;\n }\n\n /**\n * Match lookup specifications according to <script,language,feature> tuple, where\n * '*' is a wildcard for a tuple component.\n *\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n * @return a (possibly empty) map from matching lookup specifications to lists of corresponding lookup tables\n */\n public Map<LookupSpec, List<LookupTable>> matchLookups(String script, String language, String feature) {\n LookupSpec lsm = new LookupSpec(script, language, feature, true, true);\n Map<LookupSpec, List<LookupTable>> lm = matchedLookups.get(lsm);\n if (lm == null) {\n lm = new LinkedHashMap<>();\n List<LookupSpec> lsl = matchLookupSpecs(script, language, feature);\n for (LookupSpec ls : lsl) {\n lm.put(ls, findLookupTables(ls));\n }\n matchedLookups.put(lsm, lm);\n }\n if (lm.isEmpty() && !OTFScript.isDefault(script) && !OTFScript.isWildCard(script)) {\n return matchLookups(OTFScript.DEFAULT, OTFLanguage.DEFAULT, feature);\n } else {\n return lm;\n }\n }\n\n /**\n * Obtain ordered list of glyph lookup tables that match a specific lookup specification.\n *\n * @param ls\n * a (non-null) lookup specification\n * @return a (possibly empty) ordered list of lookup tables whose corresponding lookup specifications match the\n * specified lookup spec\n */\n public List<LookupTable> findLookupTables(LookupSpec ls) {\n TreeSet<LookupTable> lts = new TreeSet<>();\n List<String> ids;\n if ((ids = lookups.get(ls)) != null) {\n for (String lid : ids) {\n LookupTable lt;\n if ((lt = lookupTables.get(lid)) != null) {\n lts.add(lt);\n }\n }\n }\n return new ArrayList<>(lts);\n }\n\n /**\n * Assemble ordered array of lookup table use specifications according to the specified features and candidate\n * lookups,\n * where the order of the array is in accordance to the order of the applicable lookup list.\n *\n * @param features\n * array of feature identifiers to apply\n * @param lookups\n * a mapping from lookup specifications to lists of look tables from which to select lookup tables according to\n * the specified features\n * @return ordered array of assembled lookup table use specifications\n */\n public UseSpec[] assembleLookups(String[] features, Map<LookupSpec, List<LookupTable>> lookups) {\n TreeSet<UseSpec> uss = new TreeSet<UseSpec>();\n for (String feature : features) {\n for (Map.Entry<LookupSpec, List<LookupTable>> e : lookups.entrySet()) {\n LookupSpec ls = e.getKey();\n if (ls.getFeature().equals(feature)) {\n List<LookupTable> ltl = e.getValue();\n if (ltl != null) {\n for (LookupTable lt : ltl) {\n uss.add(new UseSpec(lt, feature));\n }\n }\n }\n }\n }\n return uss.toArray(new UseSpec[uss.size()]);\n }\n\n /**\n * Determine if table supports specific feature, i.e., supports at least one lookup.\n *\n * @param script\n * to qualify feature lookup\n * @param language\n * to qualify feature lookup\n * @param feature\n * to test\n * @return true if feature supported (has at least one lookup)\n */\n public boolean hasFeature(String script, String language, String feature) {\n UseSpec[] usa = assembleLookups(new String[]{feature}, matchLookups(script, language, feature));\n return usa.length > 0;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer(super.toString());\n sb.append(\"{\");\n sb.append(\"lookups={\");\n sb.append(lookups.toString());\n sb.append(\"},lookupTables={\");\n sb.append(lookupTables.toString());\n sb.append(\"}}\");\n return sb.toString();\n }\n\n /**\n * Obtain glyph table type from name.\n *\n * @param name\n * of table type to map to type value\n * @return glyph table type (as an integer constant)\n */\n public static int getTableTypeFromName(String name) {\n int t;\n String s = name.toLowerCase();\n if (\"gsub\".equals(s)) {\n t = GLYPH_TABLE_TYPE_SUBSTITUTION;\n } else if (\"gpos\".equals(s)) {\n t = GLYPH_TABLE_TYPE_POSITIONING;\n } else if (\"jstf\".equals(s)) {\n t = GLYPH_TABLE_TYPE_JUSTIFICATION;\n } else if (\"base\".equals(s)) {\n t = GLYPH_TABLE_TYPE_BASELINE;\n } else if (\"gdef\".equals(s)) {\n t = GLYPH_TABLE_TYPE_DEFINITION;\n } else {\n t = -1;\n }\n return t;\n }\n\n /**\n * Resolve references to lookup tables in a collection of rules sets.\n *\n * @param rsa\n * array of rule sets\n * @param lookupTables\n * map from lookup table identifers, e.g. \"lu4\", to lookup tables\n */\n public static void resolveLookupReferences(RuleSet[] rsa, Map<String, LookupTable> lookupTables) {\n if ((rsa != null) && (lookupTables != null)) {\n for (RuleSet rs : rsa) {\n if (rs != null) {\n rs.resolveLookupReferences(lookupTables);\n }\n }\n }\n }\n\n /**\n * A structure class encapsulating a lookup specification as a <script,language,feature> tuple.\n */\n public static class LookupSpec implements Comparable {\n\n private final String script;\n private final String language;\n private final String feature;\n\n /**\n * Instantiate lookup spec.\n *\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n */\n public LookupSpec(String script, String language, String feature) {\n this(script, language, feature, false, false);\n }\n\n /**\n * Instantiate lookup spec.\n *\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n * @param permitEmpty\n * if true then permit empty script, language, or feature\n * @param permitWildcard\n * if true then permit wildcard script, language, or feature\n */\n LookupSpec(String script, String language, String feature, boolean permitEmpty, boolean permitWildcard) {\n if ((script == null) || (!permitEmpty && (script.length() == 0))) {\n throw new AdvancedTypographicTableFormatException(\"script must be non-empty string\");\n } else if ((language == null) || (!permitEmpty && (language.length() == 0))) {\n throw new AdvancedTypographicTableFormatException(\"language must be non-empty string\");\n } else if ((feature == null) || (!permitEmpty && (feature.length() == 0))) {\n throw new AdvancedTypographicTableFormatException(\"feature must be non-empty string\");\n } else if (!permitWildcard && script.equals(\"*\")) {\n throw new AdvancedTypographicTableFormatException(\"script must not be wildcard\");\n } else if (!permitWildcard && language.equals(\"*\")) {\n throw new AdvancedTypographicTableFormatException(\"language must not be wildcard\");\n } else if (!permitWildcard && feature.equals(\"*\")) {\n throw new AdvancedTypographicTableFormatException(\"feature must not be wildcard\");\n }\n this.script = script.trim();\n this.language = language.trim();\n this.feature = feature.trim();\n }\n\n /** @return script identifier */\n public String getScript() {\n return script;\n }\n\n /** @return language identifier */\n public String getLanguage() {\n return language;\n }\n\n /** @return feature identifier */\n public String getFeature() {\n return feature;\n }\n\n /** {@inheritDoc} */\n public int hashCode() {\n int hc = 0;\n hc = 7 * hc + (hc ^ script.hashCode());\n hc = 11 * hc + (hc ^ language.hashCode());\n hc = 17 * hc + (hc ^ feature.hashCode());\n return hc;\n }\n\n /** {@inheritDoc} */\n public boolean equals(Object o) {\n if (o instanceof LookupSpec) {\n LookupSpec l = (LookupSpec) o;\n if (!l.script.equals(script)) {\n return false;\n } else if (!l.language.equals(language)) {\n return false;\n } else {\n return l.feature.equals(feature);\n }\n } else {\n return false;\n }\n }\n\n /** {@inheritDoc} */\n public int compareTo(Object o) {\n int d;\n if (o instanceof LookupSpec) {\n LookupSpec ls = (LookupSpec) o;\n if ((d = script.compareTo(ls.script)) == 0) {\n if ((d = language.compareTo(ls.language)) == 0) {\n if ((d = feature.compareTo(ls.feature)) == 0) {\n d = 0;\n }\n }\n }\n } else {\n d = -1;\n }\n return d;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer(super.toString());\n sb.append(\"{\");\n sb.append(\"<'\" + script + \"'\");\n sb.append(\",'\" + language + \"'\");\n sb.append(\",'\" + feature + \"'\");\n sb.append(\">}\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>LookupTable</code> class comprising an identifier and an ordered list\n * of glyph subtables, each of which employ the same lookup identifier.\n */\n public static class LookupTable implements Comparable {\n\n private final String id; // lookup identifier\n private final int idOrdinal; // parsed lookup identifier ordinal\n private final List<GlyphSubtable> subtables; // list of subtables\n private boolean doesSub; // performs substitutions\n private boolean doesPos; // performs positioning\n private boolean frozen; // if true, then don't permit further subtable additions\n // frozen state\n private GlyphSubtable[] subtablesArray;\n private static GlyphSubtable[] subtablesArrayEmpty = new GlyphSubtable[0];\n\n /**\n * Instantiate a LookupTable.\n *\n * @param id\n * the lookup table's identifier\n * @param subtable\n * an initial subtable (or null)\n */\n public LookupTable(String id, GlyphSubtable subtable) {\n this(id, makeSingleton(subtable));\n }\n\n /**\n * Instantiate a LookupTable.\n *\n * @param id\n * the lookup table's identifier\n * @param subtables\n * a pre-poplated list of subtables or null\n */\n public LookupTable(String id, List<GlyphSubtable> subtables) {\n this.id = id;\n this.idOrdinal = Integer.parseInt(id.substring(2));\n this.subtables = new LinkedList<GlyphSubtable>();\n if (subtables != null) {\n for (GlyphSubtable st : subtables) {\n addSubtable(st);\n }\n }\n }\n\n /** @return the subtables as an array */\n public GlyphSubtable[] getSubtables() {\n if (frozen) {\n return (subtablesArray != null) ? subtablesArray : subtablesArrayEmpty;\n } else {\n if (doesSub) {\n return subtables.toArray(new GlyphSubstitutionSubtable[subtables.size()]);\n } else if (doesPos) {\n return subtables.toArray(new GlyphPositioningSubtable[subtables.size()]);\n } else {\n return null;\n }\n }\n }\n\n /**\n * Add a subtable into this lookup table's collecion of subtables according to its\n * natural order.\n *\n * @param subtable\n * to add\n * @return true if subtable was not already present, otherwise false\n */\n public boolean addSubtable(GlyphSubtable subtable) {\n boolean added = false;\n // ensure table is not frozen\n if (frozen) {\n throw new IllegalStateException(\"glyph table is frozen, subtable addition prohibited\");\n }\n // validate subtable to ensure consistency with current subtables\n validateSubtable(subtable);\n // insert subtable into ordered list\n for (ListIterator<GlyphSubtable> lit = subtables.listIterator(0); lit.hasNext(); ) {\n GlyphSubtable st = lit.next();\n int d;\n if ((d = subtable.compareTo(st)) < 0) {\n // insert within list\n lit.set(subtable);\n lit.add(st);\n added = true;\n } else if (d == 0) {\n // duplicate entry is ignored\n added = false;\n subtable = null;\n }\n }\n // append at end of list\n if (!added && (subtable != null)) {\n subtables.add(subtable);\n added = true;\n }\n return added;\n }\n\n private void validateSubtable(GlyphSubtable subtable) {\n if (subtable == null) {\n throw new AdvancedTypographicTableFormatException(\"subtable must be non-null\");\n }\n if (subtable instanceof GlyphSubstitutionSubtable) {\n if (doesPos) {\n throw new AdvancedTypographicTableFormatException(\n \"subtable must be positioning subtable, but is: \" + subtable);\n } else {\n doesSub = true;\n }\n }\n if (subtable instanceof GlyphPositioningSubtable) {\n if (doesSub) {\n throw new AdvancedTypographicTableFormatException(\n \"subtable must be substitution subtable, but is: \" + subtable);\n } else {\n doesPos = true;\n }\n }\n if (subtables.size() > 0) {\n GlyphSubtable st = subtables.get(0);\n if (!st.isCompatible(subtable)) {\n throw new AdvancedTypographicTableFormatException(\n \"subtable \" + subtable + \" is not compatible with subtable \" + st);\n }\n }\n }\n\n /**\n * Freeze subtables, i.e., do not allow further subtable addition, and\n * create resulting cached state. In addition, resolve any references to\n * lookup tables that appear in this lookup table's subtables.\n *\n * @param lookupTables\n * map from lookup table identifers, e.g. \"lu4\", to lookup tables\n */\n public void freezeSubtables(Map<String, LookupTable> lookupTables) {\n if (!frozen) {\n GlyphSubtable[] sta = getSubtables();\n resolveLookupReferences(sta, lookupTables);\n this.subtablesArray = sta;\n this.frozen = true;\n }\n }\n\n private void resolveLookupReferences(GlyphSubtable[] subtables, Map<String, LookupTable> lookupTables) {\n if (subtables != null) {\n for (GlyphSubtable st : subtables) {\n if (st != null) {\n st.resolveLookupReferences(lookupTables);\n }\n }\n }\n }\n\n /**\n * Determine if this glyph table performs substitution.\n *\n * @return true if it performs substitution\n */\n public boolean performsSubstitution() {\n return doesSub;\n }\n\n /**\n * Perform substitution processing using this lookup table's subtables.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n * @param sct\n * a script specific context tester (or null)\n * @return the substituted (output) glyph sequence\n */\n public GlyphSequence substitute(GlyphSequence gs, String script, String language, String feature,\n ScriptContextTester sct) {\n if (performsSubstitution()) {\n return GlyphSubstitutionSubtable\n .substitute(gs, script, language, feature, (GlyphSubstitutionSubtable[]) subtablesArray, sct);\n } else {\n return gs;\n }\n }\n\n /**\n * Perform substitution processing on an existing glyph substitution state object using this lookup table's\n * subtables.\n *\n * @param ss\n * a glyph substitution state object\n * @param sequenceIndex\n * if non negative, then apply subtables only at specified sequence index\n * @return the substituted (output) glyph sequence\n */\n public GlyphSequence substitute(GlyphSubstitutionState ss, int sequenceIndex) {\n if (performsSubstitution()) {\n return GlyphSubstitutionSubtable.substitute(ss, (GlyphSubstitutionSubtable[]) subtablesArray, sequenceIndex);\n } else {\n return ss.getInput();\n }\n }\n\n /**\n * Determine if this glyph table performs positioning.\n *\n * @return true if it performs positioning\n */\n public boolean performsPositioning() {\n return doesPos;\n }\n\n /**\n * Perform positioning processing using this lookup table's subtables.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param feature\n * a feature identifier\n * @param fontSize\n * size in device units\n * @param widths\n * array of default advancements for each glyph in font\n * @param adjustments\n * accumulated adjustments array (sequence) of 4-tuples of placement [PX,PY] and advance [AX,AY] adjustments,\n * in\n * that order,\n * with one 4-tuple for each element of glyph sequence\n * @param sct\n * a script specific context tester (or null)\n * @return true if some adjustment is not zero; otherwise, false\n */\n public boolean position(GlyphSequence gs, String script, String language, String feature, int fontSize,\n int[] widths, int[][] adjustments, ScriptContextTester sct) {\n return performsPositioning() && GlyphPositioningSubtable.position(gs, script, language, feature,\n fontSize, (GlyphPositioningSubtable[]) subtablesArray, widths, adjustments, sct);\n }\n\n /**\n * Perform positioning processing on an existing glyph positioning state object using this lookup table's\n * subtables.\n *\n * @param ps\n * a glyph positioning state object\n * @param sequenceIndex\n * if non negative, then apply subtables only at specified sequence index\n * @return true if some adjustment is not zero; otherwise, false\n */\n public boolean position(GlyphPositioningState ps, int sequenceIndex) {\n return performsPositioning() &&\n GlyphPositioningSubtable.position(ps, (GlyphPositioningSubtable[]) subtablesArray, sequenceIndex);\n }\n\n /** {@inheritDoc} */\n public int hashCode() {\n return idOrdinal;\n }\n\n /**\n * {@inheritDoc}\n *\n * @return true if identifier of the specified lookup table is the same\n * as the identifier of this lookup table\n */\n public boolean equals(Object o) {\n if (o instanceof LookupTable) {\n LookupTable lt = (LookupTable) o;\n return idOrdinal == lt.idOrdinal;\n } else {\n return false;\n }\n }\n\n /**\n * {@inheritDoc}\n *\n * @return the result of comparing the identifier of the specified lookup table with\n * the identifier of this lookup table; lookup table identifiers take the form\n * \"lu(DIGIT)+\", with comparison based on numerical ordering of numbers expressed by\n * (DIGIT)+.\n */\n public int compareTo(Object o) {\n if (o instanceof LookupTable) {\n LookupTable lt = (LookupTable) o;\n int i = idOrdinal;\n int j = lt.idOrdinal;\n if (i < j) {\n return -1;\n } else if (i > j) {\n return 1;\n } else {\n return 0;\n }\n } else {\n return -1;\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"id = \" + id);\n sb.append(\", subtables = \" + subtables);\n sb.append(\" }\");\n return sb.toString();\n }\n\n private static List<GlyphSubtable> makeSingleton(GlyphSubtable subtable) {\n if (subtable == null) {\n return null;\n } else {\n List<GlyphSubtable> stl = new ArrayList<GlyphSubtable>(1);\n stl.add(subtable);\n return stl;\n }\n }\n\n }\n\n /**\n * The <code>UseSpec</code> class comprises a lookup table reference\n * and the feature that selected the lookup table.\n */\n public static class UseSpec implements Comparable {\n\n /** lookup table to apply */\n private final LookupTable lookupTable;\n /** feature that caused selection of the lookup table */\n private final String feature;\n\n /**\n * Construct a glyph lookup table use specification.\n *\n * @param lookupTable\n * a glyph lookup table\n * @param feature\n * a feature that caused lookup table selection\n */\n public UseSpec(LookupTable lookupTable, String feature) {\n this.lookupTable = lookupTable;\n this.feature = feature;\n }\n\n /** @return the lookup table */\n public LookupTable getLookupTable() {\n return lookupTable;\n }\n\n /** @return the feature that selected this lookup table */\n public String getFeature() {\n return feature;\n }\n\n /**\n * Perform substitution processing using this use specification's lookup table.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param sct\n * a script specific context tester (or null)\n * @return the substituted (output) glyph sequence\n */\n public GlyphSequence substitute(GlyphSequence gs, String script, String language, ScriptContextTester sct) {\n return lookupTable.substitute(gs, script, language, feature, sct);\n }\n\n /**\n * Perform positioning processing using this use specification's lookup table.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param fontSize\n * size in device units\n * @param widths\n * array of default advancements for each glyph in font\n * @param adjustments\n * accumulated adjustments array (sequence) of 4-tuples of placement [PX,PY] and advance [AX,AY] adjustments,\n * in\n * that order,\n * with one 4-tuple for each element of glyph sequence\n * @param sct\n * a script specific context tester (or null)\n * @return true if some adjustment is not zero; otherwise, false\n */\n public boolean position(GlyphSequence gs, String script, String language, int fontSize, int[] widths,\n int[][] adjustments, ScriptContextTester sct) {\n return lookupTable.position(gs, script, language, feature, fontSize, widths, adjustments, sct);\n }\n\n /** {@inheritDoc} */\n public int hashCode() {\n return lookupTable.hashCode();\n }\n\n /** {@inheritDoc} */\n public boolean equals(Object o) {\n if (o instanceof UseSpec) {\n UseSpec u = (UseSpec) o;\n return lookupTable.equals(u.lookupTable);\n } else {\n return false;\n }\n }\n\n /** {@inheritDoc} */\n public int compareTo(Object o) {\n if (o instanceof UseSpec) {\n UseSpec u = (UseSpec) o;\n return lookupTable.compareTo(u.lookupTable);\n } else {\n return -1;\n }\n }\n\n }\n\n /**\n * The <code>RuleLookup</code> class implements a rule lookup record, comprising\n * a glyph sequence index and a lookup table index (in an applicable lookup list).\n */\n public static class RuleLookup {\n\n private final int sequenceIndex; // index into input glyph sequence\n private final int lookupIndex; // lookup list index\n private LookupTable lookup; // resolved lookup table\n\n /**\n * Instantiate a RuleLookup.\n *\n * @param sequenceIndex\n * the index into the input sequence\n * @param lookupIndex\n * the lookup table index\n */\n public RuleLookup(int sequenceIndex, int lookupIndex) {\n this.sequenceIndex = sequenceIndex;\n this.lookupIndex = lookupIndex;\n this.lookup = null;\n }\n\n /** @return the sequence index */\n public int getSequenceIndex() {\n return sequenceIndex;\n }\n\n /** @return the lookup index */\n public int getLookupIndex() {\n return lookupIndex;\n }\n\n /** @return the lookup table */\n public LookupTable getLookup() {\n return lookup;\n }\n\n /**\n * Resolve references to lookup tables.\n *\n * @param lookupTables\n * map from lookup table identifers, e.g. \"lu4\", to lookup tables\n */\n public void resolveLookupReferences(Map<String, LookupTable> lookupTables) {\n if (lookupTables != null) {\n String lid = \"lu\" + Integer.toString(lookupIndex);\n LookupTable lt = (LookupTable) lookupTables.get(lid);\n if (lt != null) {\n this.lookup = lt;\n }\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n return \"{ sequenceIndex = \" + sequenceIndex + \", lookupIndex = \" + lookupIndex + \" }\";\n }\n\n }\n\n /**\n * The <code>Rule</code> class implements an array of rule lookup records.\n */\n public abstract static class Rule {\n\n private final RuleLookup[] lookups; // rule lookups\n private final int inputSequenceLength; // input sequence length\n\n /**\n * Instantiate a Rule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * the number of glyphs in the input sequence for this rule\n */\n protected Rule(RuleLookup[] lookups, int inputSequenceLength) {\n assert lookups != null;\n this.lookups = lookups;\n this.inputSequenceLength = inputSequenceLength;\n }\n\n /** @return the lookups */\n public RuleLookup[] getLookups() {\n return lookups;\n }\n\n /** @return the input sequence length */\n public int getInputSequenceLength() {\n return inputSequenceLength;\n }\n\n /**\n * Resolve references to lookup tables, e.g., in RuleLookup, to the lookup tables themselves.\n *\n * @param lookupTables\n * map from lookup table identifers, e.g. \"lu4\", to lookup tables\n */\n public void resolveLookupReferences(Map<String, LookupTable> lookupTables) {\n if (lookups != null) {\n for (RuleLookup l : lookups) {\n if (l != null) {\n l.resolveLookupReferences(lookupTables);\n }\n }\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n return \"{ lookups = \" + Arrays.toString(lookups) + \", inputSequenceLength = \" + inputSequenceLength + \" }\";\n }\n\n }\n\n /**\n * The <code>GlyphSequenceRule</code> class implements a subclass of <code>Rule</code>\n * that supports matching on a specific glyph sequence.\n */\n public static class GlyphSequenceRule extends Rule {\n\n private final int[] glyphs; // glyphs\n\n /**\n * Instantiate a GlyphSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param glyphs\n * the rule's glyph sequence to match, starting with second glyph in sequence\n */\n public GlyphSequenceRule(RuleLookup[] lookups, int inputSequenceLength, int[] glyphs) {\n super(lookups, inputSequenceLength);\n assert glyphs != null;\n this.glyphs = glyphs;\n }\n\n /**\n * Obtain glyphs. N.B. that this array starts with the second\n * glyph of the input sequence.\n *\n * @return the glyphs\n */\n public int[] getGlyphs() {\n return glyphs;\n }\n\n /**\n * Obtain glyphs augmented by specified first glyph entry.\n *\n * @param firstGlyph\n * to fill in first glyph entry\n * @return the glyphs augmented by first glyph\n */\n public int[] getGlyphs(int firstGlyph) {\n int[] ga = new int[glyphs.length + 1];\n ga[0] = firstGlyph;\n System.arraycopy(glyphs, 0, ga, 1, glyphs.length);\n return ga;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", glyphs = \" + Arrays.toString(glyphs));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>ClassSequenceRule</code> class implements a subclass of <code>Rule</code>\n * that supports matching on a specific glyph class sequence.\n */\n public static class ClassSequenceRule extends Rule {\n\n private final int[] classes; // glyph classes\n\n /**\n * Instantiate a ClassSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param classes\n * the rule's glyph class sequence to match, starting with second glyph in sequence\n */\n public ClassSequenceRule(RuleLookup[] lookups, int inputSequenceLength, int[] classes) {\n super(lookups, inputSequenceLength);\n assert classes != null;\n this.classes = classes;\n }\n\n /**\n * Obtain glyph classes. N.B. that this array starts with the class of the second\n * glyph of the input sequence.\n *\n * @return the classes\n */\n public int[] getClasses() {\n return classes;\n }\n\n /**\n * Obtain glyph classes augmented by specified first class entry.\n *\n * @param firstClass\n * to fill in first class entry\n * @return the classes augmented by first class\n */\n public int[] getClasses(int firstClass) {\n int[] ca = new int[classes.length + 1];\n ca[0] = firstClass;\n System.arraycopy(classes, 0, ca, 1, classes.length);\n return ca;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", classes = \" + Arrays.toString(classes));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>CoverageSequenceRule</code> class implements a subclass of <code>Rule</code>\n * that supports matching on a specific glyph coverage sequence.\n */\n public static class CoverageSequenceRule extends Rule {\n\n private final GlyphCoverageTable[] coverages; // glyph coverages\n\n /**\n * Instantiate a ClassSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param coverages\n * the rule's glyph coverage sequence to match, starting with first glyph in sequence\n */\n public CoverageSequenceRule(RuleLookup[] lookups, int inputSequenceLength, GlyphCoverageTable[] coverages) {\n super(lookups, inputSequenceLength);\n assert coverages != null;\n this.coverages = coverages;\n }\n\n /** @return the coverages */\n public GlyphCoverageTable[] getCoverages() {\n return coverages;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", coverages = \" + Arrays.toString(coverages));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>ChainedGlyphSequenceRule</code> class implements a subclass of <code>GlyphSequenceRule</code>\n * that supports matching on a specific glyph sequence in a specific chained contextual.\n */\n public static class ChainedGlyphSequenceRule extends GlyphSequenceRule {\n\n private final int[] backtrackGlyphs; // backtrack glyphs\n private final int[] lookaheadGlyphs; // lookahead glyphs\n\n /**\n * Instantiate a ChainedGlyphSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param glyphs\n * the rule's input glyph sequence to match, starting with second glyph in sequence\n * @param backtrackGlyphs\n * the rule's backtrack glyph sequence to match, starting with first glyph in sequence\n * @param lookaheadGlyphs\n * the rule's lookahead glyph sequence to match, starting with first glyph in sequence\n */\n public ChainedGlyphSequenceRule(RuleLookup[] lookups, int inputSequenceLength, int[] glyphs, int[] backtrackGlyphs,\n int[] lookaheadGlyphs) {\n super(lookups, inputSequenceLength, glyphs);\n assert backtrackGlyphs != null;\n assert lookaheadGlyphs != null;\n this.backtrackGlyphs = backtrackGlyphs;\n this.lookaheadGlyphs = lookaheadGlyphs;\n }\n\n /** @return the backtrack glyphs */\n public int[] getBacktrackGlyphs() {\n return backtrackGlyphs;\n }\n\n /** @return the lookahead glyphs */\n public int[] getLookaheadGlyphs() {\n return lookaheadGlyphs;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", glyphs = \" + Arrays.toString(getGlyphs()));\n sb.append(\", backtrackGlyphs = \" + Arrays.toString(backtrackGlyphs));\n sb.append(\", lookaheadGlyphs = \" + Arrays.toString(lookaheadGlyphs));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>ChainedClassSequenceRule</code> class implements a subclass of <code>ClassSequenceRule</code>\n * that supports matching on a specific glyph class sequence in a specific chained contextual.\n */\n public static class ChainedClassSequenceRule extends ClassSequenceRule {\n\n private final int[] backtrackClasses; // backtrack classes\n private final int[] lookaheadClasses; // lookahead classes\n\n /**\n * Instantiate a ChainedClassSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param classes\n * the rule's input glyph class sequence to match, starting with second glyph in sequence\n * @param backtrackClasses\n * the rule's backtrack glyph class sequence to match, starting with first glyph in sequence\n * @param lookaheadClasses\n * the rule's lookahead glyph class sequence to match, starting with first glyph in sequence\n */\n public ChainedClassSequenceRule(RuleLookup[] lookups, int inputSequenceLength, int[] classes,\n int[] backtrackClasses, int[] lookaheadClasses) {\n super(lookups, inputSequenceLength, classes);\n assert backtrackClasses != null;\n assert lookaheadClasses != null;\n this.backtrackClasses = backtrackClasses;\n this.lookaheadClasses = lookaheadClasses;\n }\n\n /** @return the backtrack classes */\n public int[] getBacktrackClasses() {\n return backtrackClasses;\n }\n\n /** @return the lookahead classes */\n public int[] getLookaheadClasses() {\n return lookaheadClasses;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", classes = \" + Arrays.toString(getClasses()));\n sb.append(\", backtrackClasses = \" + Arrays.toString(backtrackClasses));\n sb.append(\", lookaheadClasses = \" + Arrays.toString(lookaheadClasses));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>ChainedCoverageSequenceRule</code> class implements a subclass of <code>CoverageSequenceRule</code>\n * that supports matching on a specific glyph class sequence in a specific chained contextual.\n */\n public static class ChainedCoverageSequenceRule extends CoverageSequenceRule {\n\n private final GlyphCoverageTable[] backtrackCoverages; // backtrack coverages\n private final GlyphCoverageTable[] lookaheadCoverages; // lookahead coverages\n\n /**\n * Instantiate a ChainedCoverageSequenceRule.\n *\n * @param lookups\n * the rule's lookups\n * @param inputSequenceLength\n * number of glyphs constituting input sequence (to be consumed)\n * @param coverages\n * the rule's input glyph class sequence to match, starting with first glyph in sequence\n * @param backtrackCoverages\n * the rule's backtrack glyph class sequence to match, starting with first glyph in sequence\n * @param lookaheadCoverages\n * the rule's lookahead glyph class sequence to match, starting with first glyph in sequence\n */\n public ChainedCoverageSequenceRule(RuleLookup[] lookups, int inputSequenceLength, GlyphCoverageTable[] coverages,\n GlyphCoverageTable[] backtrackCoverages,\n GlyphCoverageTable[] lookaheadCoverages) {\n super(lookups, inputSequenceLength, coverages);\n assert backtrackCoverages != null;\n assert lookaheadCoverages != null;\n this.backtrackCoverages = backtrackCoverages;\n this.lookaheadCoverages = lookaheadCoverages;\n }\n\n /** @return the backtrack coverages */\n public GlyphCoverageTable[] getBacktrackCoverages() {\n return backtrackCoverages;\n }\n\n /** @return the lookahead coverages */\n public GlyphCoverageTable[] getLookaheadCoverages() {\n return lookaheadCoverages;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ \");\n sb.append(\"lookups = \" + Arrays.toString(getLookups()));\n sb.append(\", coverages = \" + Arrays.toString(getCoverages()));\n sb.append(\", backtrackCoverages = \" + Arrays.toString(backtrackCoverages));\n sb.append(\", lookaheadCoverages = \" + Arrays.toString(lookaheadCoverages));\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>RuleSet</code> class implements a collection of rules, which\n * may or may not be the same rule type.\n */\n public static class RuleSet {\n\n private final Rule[] rules; // set of rules\n\n /**\n * Instantiate a Rule Set.\n *\n * @param rules\n * the rules\n * @throws AdvancedTypographicTableFormatException\n * if rules or some element of rules is null\n */\n public RuleSet(Rule[] rules) throws AdvancedTypographicTableFormatException {\n // enforce rules array instance\n if (rules == null) {\n throw new AdvancedTypographicTableFormatException(\"rules[] is null\");\n }\n this.rules = rules;\n }\n\n /** @return the rules */\n public Rule[] getRules() {\n return rules;\n }\n\n /**\n * Resolve references to lookup tables, e.g., in RuleLookup, to the lookup tables themselves.\n *\n * @param lookupTables\n * map from lookup table identifers, e.g. \"lu4\", to lookup tables\n */\n public void resolveLookupReferences(Map<String, LookupTable> lookupTables) {\n if (rules != null) {\n for (Rule r : rules) {\n if (r != null) {\n r.resolveLookupReferences(lookupTables);\n }\n }\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n return \"{ rules = \" + Arrays.toString(rules) + \" }\";\n }\n\n }\n\n /**\n * The <code>HomogenousRuleSet</code> class implements a collection of rules, which\n * must be the same rule type (i.e., same concrete rule class) or null.\n */\n public static class HomogeneousRuleSet extends RuleSet {\n\n /**\n * Instantiate a Homogeneous Rule Set.\n *\n * @param rules\n * the rules\n * @throws AdvancedTypographicTableFormatException\n * if some rule[i] is not an instance of rule[0]\n */\n public HomogeneousRuleSet(Rule[] rules) throws AdvancedTypographicTableFormatException {\n super(rules);\n // find first non-null rule\n Rule r0 = null;\n for (int i = 1, n = rules.length; (r0 == null) && (i < n); i++) {\n if (rules[i] != null) {\n r0 = rules[i];\n }\n }\n // enforce rule instance homogeneity\n if (r0 != null) {\n Class c = r0.getClass();\n for (int i = 1, n = rules.length; i < n; i++) {\n Rule r = rules[i];\n if ((r != null) && !c.isInstance(r)) {\n throw new AdvancedTypographicTableFormatException(\"rules[\" + i + \"] is not an instance of \" + c.getName());\n }\n }\n }\n\n }\n\n }\n\n}", "public class GlyphDefinitionTable extends GlyphTable {\n\n /** glyph class subtable type */\n public static final int GDEF_LOOKUP_TYPE_GLYPH_CLASS = 1;\n /** attachment point subtable type */\n public static final int GDEF_LOOKUP_TYPE_ATTACHMENT_POINT = 2;\n /** ligature caret subtable type */\n public static final int GDEF_LOOKUP_TYPE_LIGATURE_CARET = 3;\n /** mark attachment subtable type */\n public static final int GDEF_LOOKUP_TYPE_MARK_ATTACHMENT = 4;\n\n /** pre-defined glyph class - base glyph */\n public static final int GLYPH_CLASS_BASE = 1;\n /** pre-defined glyph class - ligature glyph */\n public static final int GLYPH_CLASS_LIGATURE = 2;\n /** pre-defined glyph class - mark glyph */\n public static final int GLYPH_CLASS_MARK = 3;\n /** pre-defined glyph class - component glyph */\n public static final int GLYPH_CLASS_COMPONENT = 4;\n\n /** singleton glyph class table */\n private GlyphClassSubtable gct;\n /** singleton attachment point table */\n // private AttachmentPointSubtable apt; // NOT YET USED\n /** singleton ligature caret table */\n // private LigatureCaretSubtable lct; // NOT YET USED\n /** singleton mark attachment table */\n private MarkAttachmentSubtable mat;\n\n /**\n * Instantiate a <code>GlyphDefinitionTable</code> object using the specified subtables.\n *\n * @param subtables\n * a list of identified subtables\n */\n public GlyphDefinitionTable(List subtables) {\n super(null, new HashMap(0));\n if ((subtables == null) || (subtables.size() == 0)) {\n throw new AdvancedTypographicTableFormatException(\"subtables must be non-empty\");\n } else {\n for (Iterator it = subtables.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (o instanceof GlyphDefinitionSubtable) {\n addSubtable((GlyphSubtable) o);\n } else {\n throw new AdvancedTypographicTableFormatException(\"subtable must be a glyph definition subtable\");\n }\n }\n freezeSubtables();\n }\n }\n\n /**\n * Reorder combining marks in glyph sequence so that they precede (within the sequence) the base\n * character to which they are applied. N.B. In the case of LTR segments, marks are not reordered by this,\n * method since when the segment is reversed by BIDI processing, marks are automatically reordered to precede\n * their base glyph.\n *\n * @param gs\n * an input glyph sequence\n * @param widths\n * associated advance widths (also reordered)\n * @param gpa\n * associated glyph position adjustments (also reordered)\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @return the reordered (output) glyph sequence\n */\n public GlyphSequence reorderCombiningMarks(GlyphSequence gs, int[] widths, int[][] gpa, String script,\n String language) {\n ScriptProcessor sp = ScriptProcessor.getInstance(script);\n return sp.reorderCombiningMarks(this, gs, widths, gpa, script, language);\n }\n\n /** {@inheritDoc} */\n protected void addSubtable(GlyphSubtable subtable) {\n if (subtable instanceof GlyphClassSubtable) {\n this.gct = (GlyphClassSubtable) subtable;\n } else if (subtable instanceof AttachmentPointSubtable) {\n // TODO - not yet used\n // this.apt = (AttachmentPointSubtable) subtable;\n } else if (subtable instanceof LigatureCaretSubtable) {\n // TODO - not yet used\n // this.lct = (LigatureCaretSubtable) subtable;\n } else if (subtable instanceof MarkAttachmentSubtable) {\n this.mat = (MarkAttachmentSubtable) subtable;\n } else {\n throw new UnsupportedOperationException(\"unsupported glyph definition subtable type: \" + subtable);\n }\n }\n\n /**\n * Determine if glyph belongs to pre-defined glyph class.\n *\n * @param gid\n * a glyph identifier (index)\n * @param gc\n * a pre-defined glyph class (GLYPH_CLASS_BASE|GLYPH_CLASS_LIGATURE|GLYPH_CLASS_MARK|GLYPH_CLASS_COMPONENT).\n * @return true if glyph belongs to specified glyph class\n */\n public boolean isGlyphClass(int gid, int gc) {\n if (gct != null) {\n return gct.isGlyphClass(gid, gc);\n } else {\n return false;\n }\n }\n\n /**\n * Determine glyph class.\n *\n * @param gid\n * a glyph identifier (index)\n * @return a pre-defined glyph class (GLYPH_CLASS_BASE|GLYPH_CLASS_LIGATURE|GLYPH_CLASS_MARK|GLYPH_CLASS_COMPONENT).\n */\n public int getGlyphClass(int gid) {\n if (gct != null) {\n return gct.getGlyphClass(gid);\n } else {\n return -1;\n }\n }\n\n /**\n * Determine if glyph belongs to (font specific) mark attachment class.\n *\n * @param gid\n * a glyph identifier (index)\n * @param mac\n * a (font specific) mark attachment class\n * @return true if glyph belongs to specified mark attachment class\n */\n public boolean isMarkAttachClass(int gid, int mac) {\n if (mat != null) {\n return mat.isMarkAttachClass(gid, mac);\n } else {\n return false;\n }\n }\n\n /**\n * Determine mark attachment class.\n *\n * @param gid\n * a glyph identifier (index)\n * @return a non-negative mark attachment class, or -1 if no class defined\n */\n public int getMarkAttachClass(int gid) {\n if (mat != null) {\n return mat.getMarkAttachClass(gid);\n } else {\n return -1;\n }\n }\n\n /**\n * Map a lookup type name to its constant (integer) value.\n *\n * @param name\n * lookup type name\n * @return lookup type\n */\n public static int getLookupTypeFromName(String name) {\n int t;\n String s = name.toLowerCase();\n if (\"glyphclass\".equals(s)) {\n t = GDEF_LOOKUP_TYPE_GLYPH_CLASS;\n } else if (\"attachmentpoint\".equals(s)) {\n t = GDEF_LOOKUP_TYPE_ATTACHMENT_POINT;\n } else if (\"ligaturecaret\".equals(s)) {\n t = GDEF_LOOKUP_TYPE_LIGATURE_CARET;\n } else if (\"markattachment\".equals(s)) {\n t = GDEF_LOOKUP_TYPE_MARK_ATTACHMENT;\n } else {\n t = -1;\n }\n return t;\n }\n\n /**\n * Map a lookup type constant (integer) value to its name.\n *\n * @param type\n * lookup type\n * @return lookup type name\n */\n public static String getLookupTypeName(int type) {\n String tn = null;\n switch (type) {\n case GDEF_LOOKUP_TYPE_GLYPH_CLASS:\n tn = \"glyphclass\";\n break;\n case GDEF_LOOKUP_TYPE_ATTACHMENT_POINT:\n tn = \"attachmentpoint\";\n break;\n case GDEF_LOOKUP_TYPE_LIGATURE_CARET:\n tn = \"ligaturecaret\";\n break;\n case GDEF_LOOKUP_TYPE_MARK_ATTACHMENT:\n tn = \"markattachment\";\n break;\n default:\n tn = \"unknown\";\n break;\n }\n return tn;\n }\n\n /**\n * Create a definition subtable according to the specified arguments.\n *\n * @param type\n * subtable type\n * @param id\n * subtable identifier\n * @param sequence\n * subtable sequence\n * @param flags\n * subtable flags (must be zero)\n * @param format\n * subtable format\n * @param mapping\n * subtable mapping table\n * @param entries\n * subtable entries\n * @return a glyph subtable instance\n */\n public static GlyphSubtable createSubtable(int type, String id, int sequence, int flags, int format,\n GlyphMappingTable mapping, List entries) {\n GlyphSubtable st = null;\n switch (type) {\n case GDEF_LOOKUP_TYPE_GLYPH_CLASS:\n st = GlyphClassSubtable.create(id, sequence, flags, format, mapping, entries);\n break;\n case GDEF_LOOKUP_TYPE_ATTACHMENT_POINT:\n st = AttachmentPointSubtable.create(id, sequence, flags, format, mapping, entries);\n break;\n case GDEF_LOOKUP_TYPE_LIGATURE_CARET:\n st = LigatureCaretSubtable.create(id, sequence, flags, format, mapping, entries);\n break;\n case GDEF_LOOKUP_TYPE_MARK_ATTACHMENT:\n st = MarkAttachmentSubtable.create(id, sequence, flags, format, mapping, entries);\n break;\n default:\n break;\n }\n return st;\n }\n\n private abstract static class GlyphClassSubtable extends GlyphDefinitionSubtable {\n\n GlyphClassSubtable(String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries) {\n super(id, sequence, flags, format, mapping);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GDEF_LOOKUP_TYPE_GLYPH_CLASS;\n }\n\n /**\n * Determine if glyph belongs to pre-defined glyph class.\n *\n * @param gid\n * a glyph identifier (index)\n * @param gc\n * a pre-defined glyph class (GLYPH_CLASS_BASE|GLYPH_CLASS_LIGATURE|GLYPH_CLASS_MARK|GLYPH_CLASS_COMPONENT).\n * @return true if glyph belongs to specified glyph class\n */\n public abstract boolean isGlyphClass(int gid, int gc);\n\n /**\n * Determine glyph class.\n *\n * @param gid\n * a glyph identifier (index)\n * @return a pre-defined glyph class (GLYPH_CLASS_BASE|GLYPH_CLASS_LIGATURE|GLYPH_CLASS_MARK|GLYPH_CLASS_COMPONENT).\n */\n public abstract int getGlyphClass(int gid);\n\n static GlyphDefinitionSubtable create(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n if (format == 1) {\n return new GlyphClassSubtableFormat1(id, sequence, flags, format, mapping, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class GlyphClassSubtableFormat1 extends GlyphClassSubtable {\n\n GlyphClassSubtableFormat1(String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries) {\n super(id, sequence, flags, format, mapping, entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n return null;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof GlyphClassSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean isGlyphClass(int gid, int gc) {\n GlyphClassMapping cm = getClasses();\n if (cm != null) {\n return cm.getClassIndex(gid, 0) == gc;\n } else {\n return false;\n }\n }\n\n /** {@inheritDoc} */\n public int getGlyphClass(int gid) {\n GlyphClassMapping cm = getClasses();\n if (cm != null) {\n return cm.getClassIndex(gid, 0);\n } else {\n return -1;\n }\n }\n }\n\n private abstract static class AttachmentPointSubtable extends GlyphDefinitionSubtable {\n\n AttachmentPointSubtable(String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries) {\n super(id, sequence, flags, format, mapping);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GDEF_LOOKUP_TYPE_ATTACHMENT_POINT;\n }\n\n static GlyphDefinitionSubtable create(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n if (format == 1) {\n return new AttachmentPointSubtableFormat1(id, sequence, flags, format, mapping, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class AttachmentPointSubtableFormat1 extends AttachmentPointSubtable {\n\n AttachmentPointSubtableFormat1(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n super(id, sequence, flags, format, mapping, entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n return null;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof AttachmentPointSubtable;\n }\n }\n\n private abstract static class LigatureCaretSubtable extends GlyphDefinitionSubtable {\n\n LigatureCaretSubtable(String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries) {\n super(id, sequence, flags, format, mapping);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GDEF_LOOKUP_TYPE_LIGATURE_CARET;\n }\n\n static GlyphDefinitionSubtable create(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n if (format == 1) {\n return new LigatureCaretSubtableFormat1(id, sequence, flags, format, mapping, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class LigatureCaretSubtableFormat1 extends LigatureCaretSubtable {\n\n LigatureCaretSubtableFormat1(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n super(id, sequence, flags, format, mapping, entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n return null;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof LigatureCaretSubtable;\n }\n }\n\n private abstract static class MarkAttachmentSubtable extends GlyphDefinitionSubtable {\n\n MarkAttachmentSubtable(String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries) {\n super(id, sequence, flags, format, mapping);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GDEF_LOOKUP_TYPE_MARK_ATTACHMENT;\n }\n\n /**\n * Determine if glyph belongs to (font specific) mark attachment class.\n *\n * @param gid\n * a glyph identifier (index)\n * @param mac\n * a (font specific) mark attachment class\n * @return true if glyph belongs to specified mark attachment class\n */\n public abstract boolean isMarkAttachClass(int gid, int mac);\n\n /**\n * Determine mark attachment class.\n *\n * @param gid\n * a glyph identifier (index)\n * @return a non-negative mark attachment class, or -1 if no class defined\n */\n public abstract int getMarkAttachClass(int gid);\n\n static GlyphDefinitionSubtable create(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n if (format == 1) {\n return new MarkAttachmentSubtableFormat1(id, sequence, flags, format, mapping, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class MarkAttachmentSubtableFormat1 extends MarkAttachmentSubtable {\n\n MarkAttachmentSubtableFormat1(String id, int sequence, int flags, int format, GlyphMappingTable mapping,\n List entries) {\n super(id, sequence, flags, format, mapping, entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n return null;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof MarkAttachmentSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean isMarkAttachClass(int gid, int mac) {\n GlyphClassMapping cm = getClasses();\n if (cm != null) {\n return cm.getClassIndex(gid, 0) == mac;\n } else {\n return false;\n }\n }\n\n /** {@inheritDoc} */\n public int getMarkAttachClass(int gid) {\n GlyphClassMapping cm = getClasses();\n if (cm != null) {\n return cm.getClassIndex(gid, 0);\n } else {\n return -1;\n }\n }\n }\n\n}", "public class GlyphPositioningTable extends GlyphTable {\n\n /** single positioning subtable type */\n public static final int GPOS_LOOKUP_TYPE_SINGLE = 1;\n /** multiple positioning subtable type */\n public static final int GPOS_LOOKUP_TYPE_PAIR = 2;\n /** cursive positioning subtable type */\n public static final int GPOS_LOOKUP_TYPE_CURSIVE = 3;\n /** mark to base positioning subtable type */\n public static final int GPOS_LOOKUP_TYPE_MARK_TO_BASE = 4;\n /** mark to ligature positioning subtable type */\n public static final int GPOS_LOOKUP_TYPE_MARK_TO_LIGATURE = 5;\n /** mark to mark positioning subtable type */\n public static final int GPOS_LOOKUP_TYPE_MARK_TO_MARK = 6;\n /** contextual positioning subtable type */\n public static final int GPOS_LOOKUP_TYPE_CONTEXTUAL = 7;\n /** chained contextual positioning subtable type */\n public static final int GPOS_LOOKUP_TYPE_CHAINED_CONTEXTUAL = 8;\n /** extension positioning subtable type */\n public static final int GPOS_LOOKUP_TYPE_EXTENSION_POSITIONING = 9;\n\n /**\n * Instantiate a <code>GlyphPositioningTable</code> object using the specified lookups\n * and subtables.\n *\n * @param gdef\n * glyph definition table that applies\n * @param lookups\n * a map of lookup specifications to subtable identifier strings\n * @param subtables\n * a list of identified subtables\n */\n public GlyphPositioningTable(GlyphDefinitionTable gdef, Map lookups, List subtables) {\n super(gdef, lookups);\n if ((subtables == null) || (subtables.size() == 0)) {\n throw new AdvancedTypographicTableFormatException(\"subtables must be non-empty\");\n } else {\n for (Iterator it = subtables.iterator(); it.hasNext(); ) {\n Object o = it.next();\n if (o instanceof GlyphPositioningSubtable) {\n addSubtable((GlyphSubtable) o);\n } else {\n throw new AdvancedTypographicTableFormatException(\"subtable must be a glyph positioning subtable\");\n }\n }\n freezeSubtables();\n }\n }\n\n /**\n * Map a lookup type name to its constant (integer) value.\n *\n * @param name\n * lookup type name\n * @return lookup type\n */\n public static int getLookupTypeFromName(String name) {\n int t;\n String s = name.toLowerCase();\n if (\"single\".equals(s)) {\n t = GPOS_LOOKUP_TYPE_SINGLE;\n } else if (\"pair\".equals(s)) {\n t = GPOS_LOOKUP_TYPE_PAIR;\n } else if (\"cursive\".equals(s)) {\n t = GPOS_LOOKUP_TYPE_CURSIVE;\n } else if (\"marktobase\".equals(s)) {\n t = GPOS_LOOKUP_TYPE_MARK_TO_BASE;\n } else if (\"marktoligature\".equals(s)) {\n t = GPOS_LOOKUP_TYPE_MARK_TO_LIGATURE;\n } else if (\"marktomark\".equals(s)) {\n t = GPOS_LOOKUP_TYPE_MARK_TO_MARK;\n } else if (\"contextual\".equals(s)) {\n t = GPOS_LOOKUP_TYPE_CONTEXTUAL;\n } else if (\"chainedcontextual\".equals(s)) {\n t = GPOS_LOOKUP_TYPE_CHAINED_CONTEXTUAL;\n } else if (\"extensionpositioning\".equals(s)) {\n t = GPOS_LOOKUP_TYPE_EXTENSION_POSITIONING;\n } else {\n t = -1;\n }\n return t;\n }\n\n /**\n * Map a lookup type constant (integer) value to its name.\n *\n * @param type\n * lookup type\n * @return lookup type name\n */\n public static String getLookupTypeName(int type) {\n String tn;\n switch (type) {\n case GPOS_LOOKUP_TYPE_SINGLE:\n tn = \"single\";\n break;\n case GPOS_LOOKUP_TYPE_PAIR:\n tn = \"pair\";\n break;\n case GPOS_LOOKUP_TYPE_CURSIVE:\n tn = \"cursive\";\n break;\n case GPOS_LOOKUP_TYPE_MARK_TO_BASE:\n tn = \"marktobase\";\n break;\n case GPOS_LOOKUP_TYPE_MARK_TO_LIGATURE:\n tn = \"marktoligature\";\n break;\n case GPOS_LOOKUP_TYPE_MARK_TO_MARK:\n tn = \"marktomark\";\n break;\n case GPOS_LOOKUP_TYPE_CONTEXTUAL:\n tn = \"contextual\";\n break;\n case GPOS_LOOKUP_TYPE_CHAINED_CONTEXTUAL:\n tn = \"chainedcontextual\";\n break;\n case GPOS_LOOKUP_TYPE_EXTENSION_POSITIONING:\n tn = \"extensionpositioning\";\n break;\n default:\n tn = \"unknown\";\n break;\n }\n return tn;\n }\n\n /**\n * Create a positioning subtable according to the specified arguments.\n *\n * @param type\n * subtable type\n * @param id\n * subtable identifier\n * @param sequence\n * subtable sequence\n * @param flags\n * subtable flags\n * @param format\n * subtable format\n * @param coverage\n * subtable coverage table\n * @param entries\n * subtable entries\n * @return a glyph subtable instance\n */\n public static GlyphSubtable createSubtable(int type, String id, int sequence, int flags, int format,\n GlyphCoverageTable coverage, List entries) {\n GlyphSubtable st = null;\n switch (type) {\n case GPOS_LOOKUP_TYPE_SINGLE:\n st = SingleSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GPOS_LOOKUP_TYPE_PAIR:\n st = PairSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GPOS_LOOKUP_TYPE_CURSIVE:\n st = CursiveSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GPOS_LOOKUP_TYPE_MARK_TO_BASE:\n st = MarkToBaseSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GPOS_LOOKUP_TYPE_MARK_TO_LIGATURE:\n st = MarkToLigatureSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GPOS_LOOKUP_TYPE_MARK_TO_MARK:\n st = MarkToMarkSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GPOS_LOOKUP_TYPE_CONTEXTUAL:\n st = ContextualSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n case GPOS_LOOKUP_TYPE_CHAINED_CONTEXTUAL:\n st = ChainedContextualSubtable.create(id, sequence, flags, format, coverage, entries);\n break;\n default:\n break;\n }\n return st;\n }\n\n /**\n * Create a positioning subtable according to the specified arguments.\n *\n * @param type\n * subtable type\n * @param id\n * subtable identifier\n * @param sequence\n * subtable sequence\n * @param flags\n * subtable flags\n * @param format\n * subtable format\n * @param coverage\n * list of coverage table entries\n * @param entries\n * subtable entries\n * @return a glyph subtable instance\n */\n public static GlyphSubtable createSubtable(int type, String id, int sequence, int flags, int format, List coverage,\n List entries) {\n return createSubtable(type, id, sequence, flags, format, GlyphCoverageTable.createCoverageTable(coverage), entries);\n }\n\n /**\n * Perform positioning processing using all matching lookups.\n *\n * @param gs\n * an input glyph sequence\n * @param script\n * a script identifier\n * @param language\n * a language identifier\n * @param fontSize\n * size in device units\n * @param widths\n * array of default advancements for each glyph\n * @param adjustments\n * accumulated adjustments array (sequence) of 4-tuples of placement [PX,PY] and advance [AX,AY] adjustments, in\n * that order,\n * with one 4-tuple for each element of glyph sequence\n * @return true if some adjustment is not zero; otherwise, false\n */\n public boolean position(GlyphSequence gs, String script, String language, int fontSize, int[] widths,\n int[][] adjustments) {\n Map/*<LookupSpec,List<LookupTable>>*/ lookups = matchLookups(script, language, \"*\");\n if ((lookups != null) && (lookups.size() > 0)) {\n ScriptProcessor sp = ScriptProcessor.getInstance(script);\n return sp.position(this, gs, script, language, fontSize, lookups, widths, adjustments);\n } else {\n return false;\n }\n }\n\n private abstract static class SingleSubtable extends GlyphPositioningSubtable {\n\n SingleSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GPOS_LOOKUP_TYPE_SINGLE;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof SingleSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean position(GlyphPositioningState ps) {\n int gi = ps.getGlyph();\n int ci;\n if ((ci = getCoverageIndex(gi)) < 0) {\n return false;\n } else {\n Value v = getValue(ci, gi);\n if (v != null) {\n if (ps.adjust(v)) {\n ps.setAdjusted(true);\n }\n ps.consume(1);\n }\n return true;\n }\n }\n\n /**\n * Obtain positioning value for coverage index.\n *\n * @param ci\n * coverage index\n * @param gi\n * input glyph index\n * @return positioning value or null if none applies\n */\n public abstract Value getValue(int ci, int gi);\n\n static GlyphPositioningSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new SingleSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else if (format == 2) {\n return new SingleSubtableFormat2(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class SingleSubtableFormat1 extends SingleSubtable {\n\n private Value value;\n private int ciMax;\n\n SingleSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (value != null) {\n List entries = new ArrayList(1);\n entries.add(value);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public Value getValue(int ci, int gi) {\n if ((value != null) && (ci <= ciMax)) {\n return value;\n } else {\n return null;\n }\n }\n\n private void populate(List entries) {\n if ((entries == null) || (entries.size() != 1)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, must be non-null and contain exactly one entry\");\n } else {\n Value v;\n Object o = entries.get(0);\n if (o instanceof Value) {\n v = (Value) o;\n } else {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries entry, must be Value, but is: \" + ((o != null) ? o.getClass() : null));\n }\n assert this.value == null;\n this.value = v;\n this.ciMax = getCoverageSize() - 1;\n }\n }\n }\n\n private static class SingleSubtableFormat2 extends SingleSubtable {\n\n private Value[] values;\n\n SingleSubtableFormat2(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (values != null) {\n List entries = new ArrayList(values.length);\n for (int i = 0, n = values.length; i < n; i++) {\n entries.add(values[i]);\n }\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public Value getValue(int ci, int gi) {\n if ((values != null) && (ci < values.length)) {\n return values[ci];\n } else {\n return null;\n }\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof Value[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, single entry must be a Value[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n Value[] va = (Value[]) o;\n if (va.length != getCoverageSize()) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal values array, \" + entries.size() + \" values present, but requires \" + getCoverageSize() +\n \" values\");\n } else {\n assert this.values == null;\n this.values = va;\n }\n }\n }\n }\n }\n\n private abstract static class PairSubtable extends GlyphPositioningSubtable {\n\n PairSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GPOS_LOOKUP_TYPE_PAIR;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof PairSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean position(GlyphPositioningState ps) {\n boolean applied = false;\n int gi = ps.getGlyph(0);\n int ci;\n if ((ci = getCoverageIndex(gi)) >= 0) {\n int[] counts = ps.getGlyphsAvailable(0);\n int nga = counts[0];\n if (nga > 1) {\n int[] iga = ps.getGlyphs(0, 2, null, counts);\n if ((iga != null) && (iga.length == 2)) {\n PairValues pv = getPairValues(ci, iga[0], iga[1]);\n if (pv != null) {\n int offset = 0;\n int offsetLast = counts[0] + counts[1];\n // skip any ignored glyphs prior to first non-ignored glyph\n for (; offset < offsetLast; ++offset) {\n if (!ps.isIgnoredGlyph(offset)) {\n break;\n } else {\n ps.consume(1);\n }\n }\n // adjust first non-ignored glyph if first value isn't null\n Value v1 = pv.getValue1();\n if (v1 != null) {\n if (ps.adjust(v1, offset)) {\n ps.setAdjusted(true);\n }\n ps.consume(1); // consume first non-ignored glyph\n ++offset;\n }\n // skip any ignored glyphs prior to second non-ignored glyph\n for (; offset < offsetLast; ++offset) {\n if (!ps.isIgnoredGlyph(offset)) {\n break;\n } else {\n ps.consume(1);\n }\n }\n // adjust second non-ignored glyph if second value isn't null\n Value v2 = pv.getValue2();\n if (v2 != null) {\n if (ps.adjust(v2, offset)) {\n ps.setAdjusted(true);\n }\n ps.consume(1); // consume second non-ignored glyph\n ++offset;\n }\n applied = true;\n }\n }\n }\n }\n return applied;\n }\n\n /**\n * Obtain associated pair values.\n *\n * @param ci\n * coverage index\n * @param gi1\n * first input glyph index\n * @param gi2\n * second input glyph index\n * @return pair values or null if none applies\n */\n public abstract PairValues getPairValues(int ci, int gi1, int gi2);\n\n static GlyphPositioningSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new PairSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else if (format == 2) {\n return new PairSubtableFormat2(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class PairSubtableFormat1 extends PairSubtable {\n\n private PairValues[][] pvm; // pair values matrix\n\n PairSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (pvm != null) {\n List entries = new ArrayList(1);\n entries.add(pvm);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public PairValues getPairValues(int ci, int gi1, int gi2) {\n if ((pvm != null) && (ci < pvm.length)) {\n PairValues[] pvt = pvm[ci];\n for (int i = 0, n = pvt.length; i < n; i++) {\n PairValues pv = pvt[i];\n if (pv != null) {\n int g = pv.getGlyph();\n if (g < gi2) {\n continue;\n } else if (g == gi2) {\n return pv;\n } else {\n break;\n }\n }\n }\n }\n return null;\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof PairValues[][])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first (and only) entry must be a PairValues[][], but is: \" +\n ((o != null) ? o.getClass() : null));\n } else {\n pvm = (PairValues[][]) o;\n }\n }\n }\n }\n\n private static class PairSubtableFormat2 extends PairSubtable {\n\n private GlyphClassTable cdt1; // class def table 1\n private GlyphClassTable cdt2; // class def table 2\n private int nc1; // class 1 count\n private int nc2; // class 2 count\n private PairValues[][] pvm; // pair values matrix\n\n PairSubtableFormat2(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (pvm != null) {\n List entries = new ArrayList(5);\n entries.add(cdt1);\n entries.add(cdt2);\n entries.add(Integer.valueOf(nc1));\n entries.add(Integer.valueOf(nc2));\n entries.add(pvm);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public PairValues getPairValues(int ci, int gi1, int gi2) {\n if (pvm != null) {\n int c1 = cdt1.getClassIndex(gi1, 0);\n if ((c1 >= 0) && (c1 < nc1) && (c1 < pvm.length)) {\n PairValues[] pvt = pvm[c1];\n if (pvt != null) {\n int c2 = cdt2.getClassIndex(gi2, 0);\n if ((c2 >= 0) && (c2 < nc2) && (c2 < pvt.length)) {\n return pvt[c2];\n }\n }\n }\n }\n return null;\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 5) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 5 entries\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an GlyphClassTable, but is: \" +\n ((o != null) ? o.getClass() : null));\n } else {\n cdt1 = (GlyphClassTable) o;\n }\n if (((o = entries.get(1)) == null) || !(o instanceof GlyphClassTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, second entry must be an GlyphClassTable, but is: \" +\n ((o != null) ? o.getClass() : null));\n } else {\n cdt2 = (GlyphClassTable) o;\n }\n if (((o = entries.get(2)) == null) || !(o instanceof Integer)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, third entry must be an Integer, but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n nc1 = ((Integer) (o)).intValue();\n }\n if (((o = entries.get(3)) == null) || !(o instanceof Integer)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, fourth entry must be an Integer, but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n nc2 = ((Integer) (o)).intValue();\n }\n if (((o = entries.get(4)) == null) || !(o instanceof PairValues[][])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, fifth entry must be a PairValues[][], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n pvm = (PairValues[][]) o;\n }\n }\n }\n }\n\n private abstract static class CursiveSubtable extends GlyphPositioningSubtable {\n\n CursiveSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GPOS_LOOKUP_TYPE_CURSIVE;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof CursiveSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean position(GlyphPositioningState ps) {\n boolean applied = false;\n int gi = ps.getGlyph(0);\n int ci;\n if ((ci = getCoverageIndex(gi)) >= 0) {\n int[] counts = ps.getGlyphsAvailable(0);\n int nga = counts[0];\n if (nga > 1) {\n int[] iga = ps.getGlyphs(0, 2, null, counts);\n if ((iga != null) && (iga.length == 2)) {\n // int gi1 = gi;\n int ci1 = ci;\n int gi2 = iga[1];\n int ci2 = getCoverageIndex(gi2);\n Anchor[] aa = getExitEntryAnchors(ci1, ci2);\n if (aa != null) {\n Anchor exa = aa[0];\n Anchor ena = aa[1];\n // int exw = ps.getWidth ( gi1 );\n int enw = ps.getWidth(gi2);\n if ((exa != null) && (ena != null)) {\n Value v = ena.getAlignmentAdjustment(exa);\n v.adjust(-enw, 0, 0, 0);\n if (ps.adjust(v)) {\n ps.setAdjusted(true);\n }\n }\n // consume only first glyph of exit/entry glyph pair\n ps.consume(1);\n applied = true;\n }\n }\n }\n }\n return applied;\n }\n\n /**\n * Obtain exit anchor for first glyph with coverage index <code>ci1</code> and entry anchor for second\n * glyph with coverage index <code>ci2</code>.\n *\n * @param ci1\n * coverage index of first glyph (may be negative)\n * @param ci2\n * coverage index of second glyph (may be negative)\n * @return array of two anchors or null if either coverage index is negative or corresponding anchor is\n * missing, where the first entry is the exit anchor of the first glyph and the second entry is the\n * entry anchor of the second glyph\n */\n public abstract Anchor[] getExitEntryAnchors(int ci1, int ci2);\n\n static GlyphPositioningSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new CursiveSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class CursiveSubtableFormat1 extends CursiveSubtable {\n\n private Anchor[] aa;\n // anchor array, where even entries are entry anchors, and odd entries are exit anchors\n\n CursiveSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (aa != null) {\n List entries = new ArrayList(1);\n entries.add(aa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public Anchor[] getExitEntryAnchors(int ci1, int ci2) {\n if ((ci1 >= 0) && (ci2 >= 0)) {\n int ai1 = (ci1 * 2) + 1; // ci1 denotes glyph with exit anchor\n int ai2 = (ci2 * 2) + 0; // ci2 denotes glyph with entry anchor\n if ((aa != null) && (ai1 < aa.length) && (ai2 < aa.length)) {\n Anchor exa = aa[ai1];\n Anchor ena = aa[ai2];\n if ((exa != null) && (ena != null)) {\n return new Anchor[]{exa, ena};\n }\n }\n }\n return null;\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof Anchor[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first (and only) entry must be a Anchor[], but is: \" +\n ((o != null) ? o.getClass() : null));\n } else if ((((Anchor[]) o).length % 2) != 0) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, Anchor[] array must have an even number of entries, but has: \" + ((Anchor[]) o).length);\n } else {\n aa = (Anchor[]) o;\n }\n }\n }\n }\n\n private abstract static class MarkToBaseSubtable extends GlyphPositioningSubtable {\n\n MarkToBaseSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GPOS_LOOKUP_TYPE_MARK_TO_BASE;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof MarkToBaseSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean position(GlyphPositioningState ps) {\n boolean applied = false;\n int giMark = ps.getGlyph();\n int ciMark;\n if ((ciMark = getCoverageIndex(giMark)) >= 0) {\n MarkAnchor ma = getMarkAnchor(ciMark, giMark);\n if (ma != null) {\n for (int i = 0, n = ps.getPosition(); i < n; i++) {\n int gi = ps.getGlyph(-(i + 1));\n if (ps.isMark(gi)) {\n continue;\n } else {\n Anchor a = getBaseAnchor(gi, ma.getMarkClass());\n if (a != null) {\n Value v = a.getAlignmentAdjustment(ma);\n // start experimental fix for END OF AYAH in Lateef/Scheherazade\n int[] aa = ps.getAdjustment();\n if (aa[2] == 0) {\n v.adjust(0, 0, -ps.getWidth(giMark), 0);\n }\n // end experimental fix for END OF AYAH in Lateef/Scheherazade\n if (ps.adjust(v)) {\n ps.setAdjusted(true);\n }\n }\n ps.consume(1);\n applied = true;\n break;\n }\n }\n }\n }\n return applied;\n }\n\n /**\n * Obtain mark anchor associated with mark coverage index.\n *\n * @param ciMark\n * coverage index\n * @param giMark\n * input glyph index of mark glyph\n * @return mark anchor or null if none applies\n */\n public abstract MarkAnchor getMarkAnchor(int ciMark, int giMark);\n\n /**\n * Obtain anchor associated with base glyph index and mark class.\n *\n * @param giBase\n * input glyph index of base glyph\n * @param markClass\n * class number of mark glyph\n * @return anchor or null if none applies\n */\n public abstract Anchor getBaseAnchor(int giBase, int markClass);\n\n static GlyphPositioningSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new MarkToBaseSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class MarkToBaseSubtableFormat1 extends MarkToBaseSubtable {\n\n private GlyphCoverageTable bct; // base coverage table\n private int nmc; // mark class count\n private MarkAnchor[] maa; // mark anchor array, ordered by mark coverage index\n private Anchor[][] bam;\n // base anchor matrix, ordered by base coverage index, then by mark class\n\n MarkToBaseSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if ((bct != null) && (maa != null) && (nmc > 0) && (bam != null)) {\n List entries = new ArrayList(4);\n entries.add(bct);\n entries.add(Integer.valueOf(nmc));\n entries.add(maa);\n entries.add(bam);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public MarkAnchor getMarkAnchor(int ciMark, int giMark) {\n if ((maa != null) && (ciMark < maa.length)) {\n return maa[ciMark];\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public Anchor getBaseAnchor(int giBase, int markClass) {\n int ciBase;\n if ((bct != null) && ((ciBase = bct.getCoverageIndex(giBase)) >= 0)) {\n if ((bam != null) && (ciBase < bam.length)) {\n Anchor[] ba = bam[ciBase];\n if ((ba != null) && (markClass < ba.length)) {\n return ba[markClass];\n }\n }\n }\n return null;\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 4) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 4 entries\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof GlyphCoverageTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an GlyphCoverageTable, but is: \" +\n ((o != null) ? o.getClass() : null));\n } else {\n bct = (GlyphCoverageTable) o;\n }\n if (((o = entries.get(1)) == null) || !(o instanceof Integer)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, second entry must be an Integer, but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n nmc = ((Integer) (o)).intValue();\n }\n if (((o = entries.get(2)) == null) || !(o instanceof MarkAnchor[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, third entry must be a MarkAnchor[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n maa = (MarkAnchor[]) o;\n }\n if (((o = entries.get(3)) == null) || !(o instanceof Anchor[][])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, fourth entry must be a Anchor[][], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n bam = (Anchor[][]) o;\n }\n }\n }\n }\n\n private abstract static class MarkToLigatureSubtable extends GlyphPositioningSubtable {\n\n MarkToLigatureSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GPOS_LOOKUP_TYPE_MARK_TO_LIGATURE;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof MarkToLigatureSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean position(GlyphPositioningState ps) {\n boolean applied = false;\n int giMark = ps.getGlyph();\n int ciMark;\n if ((ciMark = getCoverageIndex(giMark)) >= 0) {\n MarkAnchor ma = getMarkAnchor(ciMark, giMark);\n int mxc = getMaxComponentCount();\n if (ma != null) {\n for (int i = 0, n = ps.getPosition(); i < n; i++) {\n int gi = ps.getGlyph(-(i + 1));\n if (ps.isMark(gi)) {\n continue;\n } else {\n Anchor a = getLigatureAnchor(gi, mxc, i, ma.getMarkClass());\n if (a != null) {\n if (ps.adjust(a.getAlignmentAdjustment(ma))) {\n ps.setAdjusted(true);\n }\n }\n ps.consume(1);\n applied = true;\n break;\n }\n }\n }\n }\n return applied;\n }\n\n /**\n * Obtain mark anchor associated with mark coverage index.\n *\n * @param ciMark\n * coverage index\n * @param giMark\n * input glyph index of mark glyph\n * @return mark anchor or null if none applies\n */\n public abstract MarkAnchor getMarkAnchor(int ciMark, int giMark);\n\n /**\n * Obtain maximum component count.\n *\n * @return maximum component count (>=0)\n */\n public abstract int getMaxComponentCount();\n\n /**\n * Obtain anchor associated with ligature glyph index and mark class.\n *\n * @param giLig\n * input glyph index of ligature glyph\n * @param maxComponents\n * maximum component count\n * @param component\n * component number (0...maxComponents-1)\n * @param markClass\n * class number of mark glyph\n * @return anchor or null if none applies\n */\n public abstract Anchor getLigatureAnchor(int giLig, int maxComponents, int component, int markClass);\n\n static GlyphPositioningSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new MarkToLigatureSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class MarkToLigatureSubtableFormat1 extends MarkToLigatureSubtable {\n\n private GlyphCoverageTable lct; // ligature coverage table\n private int nmc; // mark class count\n private int mxc; // maximum ligature component count\n private MarkAnchor[] maa; // mark anchor array, ordered by mark coverage index\n private Anchor[][][] lam;\n // ligature anchor matrix, ordered by ligature coverage index, then ligature component, then mark class\n\n MarkToLigatureSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (lam != null) {\n List entries = new ArrayList(5);\n entries.add(lct);\n entries.add(Integer.valueOf(nmc));\n entries.add(Integer.valueOf(mxc));\n entries.add(maa);\n entries.add(lam);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public MarkAnchor getMarkAnchor(int ciMark, int giMark) {\n if ((maa != null) && (ciMark < maa.length)) {\n return maa[ciMark];\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public int getMaxComponentCount() {\n return mxc;\n }\n\n /** {@inheritDoc} */\n public Anchor getLigatureAnchor(int giLig, int maxComponents, int component, int markClass) {\n int ciLig;\n if ((lct != null) && ((ciLig = lct.getCoverageIndex(giLig)) >= 0)) {\n if ((lam != null) && (ciLig < lam.length)) {\n Anchor[][] lcm = lam[ciLig];\n if (component < maxComponents) {\n Anchor[] la = lcm[component];\n if ((la != null) && (markClass < la.length)) {\n return la[markClass];\n }\n }\n }\n }\n return null;\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 5) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 5 entries\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof GlyphCoverageTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an GlyphCoverageTable, but is: \" +\n ((o != null) ? o.getClass() : null));\n } else {\n lct = (GlyphCoverageTable) o;\n }\n if (((o = entries.get(1)) == null) || !(o instanceof Integer)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, second entry must be an Integer, but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n nmc = ((Integer) (o)).intValue();\n }\n if (((o = entries.get(2)) == null) || !(o instanceof Integer)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, third entry must be an Integer, but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n mxc = ((Integer) (o)).intValue();\n }\n if (((o = entries.get(3)) == null) || !(o instanceof MarkAnchor[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, fourth entry must be a MarkAnchor[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n maa = (MarkAnchor[]) o;\n }\n if (((o = entries.get(4)) == null) || !(o instanceof Anchor[][][])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, fifth entry must be a Anchor[][][], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n lam = (Anchor[][][]) o;\n }\n }\n }\n }\n\n private abstract static class MarkToMarkSubtable extends GlyphPositioningSubtable {\n\n MarkToMarkSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GPOS_LOOKUP_TYPE_MARK_TO_MARK;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof MarkToMarkSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean position(GlyphPositioningState ps) {\n boolean applied = false;\n int giMark1 = ps.getGlyph();\n int ciMark1;\n if ((ciMark1 = getCoverageIndex(giMark1)) >= 0) {\n MarkAnchor ma = getMark1Anchor(ciMark1, giMark1);\n if (ma != null) {\n if (ps.hasPrev()) {\n Anchor a = getMark2Anchor(ps.getGlyph(-1), ma.getMarkClass());\n if (a != null) {\n if (ps.adjust(a.getAlignmentAdjustment(ma))) {\n ps.setAdjusted(true);\n }\n }\n ps.consume(1);\n applied = true;\n }\n }\n }\n return applied;\n }\n\n /**\n * Obtain mark 1 anchor associated with mark 1 coverage index.\n *\n * @param ciMark1\n * mark 1 coverage index\n * @param giMark1\n * input glyph index of mark 1 glyph\n * @return mark 1 anchor or null if none applies\n */\n public abstract MarkAnchor getMark1Anchor(int ciMark1, int giMark1);\n\n /**\n * Obtain anchor associated with mark 2 glyph index and mark 1 class.\n *\n * @param giBase\n * input glyph index of mark 2 glyph\n * @param markClass\n * class number of mark 1 glyph\n * @return anchor or null if none applies\n */\n public abstract Anchor getMark2Anchor(int giBase, int markClass);\n\n static GlyphPositioningSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new MarkToMarkSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class MarkToMarkSubtableFormat1 extends MarkToMarkSubtable {\n\n private GlyphCoverageTable mct2; // mark 2 coverage table\n private int nmc; // mark class count\n private MarkAnchor[] maa; // mark1 anchor array, ordered by mark1 coverage index\n private Anchor[][] mam;\n // mark2 anchor matrix, ordered by mark2 coverage index, then by mark1 class\n\n MarkToMarkSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if ((mct2 != null) && (maa != null) && (nmc > 0) && (mam != null)) {\n List entries = new ArrayList(4);\n entries.add(mct2);\n entries.add(Integer.valueOf(nmc));\n entries.add(maa);\n entries.add(mam);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public MarkAnchor getMark1Anchor(int ciMark1, int giMark1) {\n if ((maa != null) && (ciMark1 < maa.length)) {\n return maa[ciMark1];\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public Anchor getMark2Anchor(int giMark2, int markClass) {\n int ciMark2;\n if ((mct2 != null) && ((ciMark2 = mct2.getCoverageIndex(giMark2)) >= 0)) {\n if ((mam != null) && (ciMark2 < mam.length)) {\n Anchor[] ma = mam[ciMark2];\n if ((ma != null) && (markClass < ma.length)) {\n return ma[markClass];\n }\n }\n }\n return null;\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 4) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 4 entries\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof GlyphCoverageTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an GlyphCoverageTable, but is: \" +\n ((o != null) ? o.getClass() : null));\n } else {\n mct2 = (GlyphCoverageTable) o;\n }\n if (((o = entries.get(1)) == null) || !(o instanceof Integer)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, second entry must be an Integer, but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n nmc = ((Integer) (o)).intValue();\n }\n if (((o = entries.get(2)) == null) || !(o instanceof MarkAnchor[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, third entry must be a MarkAnchor[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n maa = (MarkAnchor[]) o;\n }\n if (((o = entries.get(3)) == null) || !(o instanceof Anchor[][])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, fourth entry must be a Anchor[][], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n mam = (Anchor[][]) o;\n }\n }\n }\n }\n\n private abstract static class ContextualSubtable extends GlyphPositioningSubtable {\n\n ContextualSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GPOS_LOOKUP_TYPE_CONTEXTUAL;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof ContextualSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean position(GlyphPositioningState ps) {\n boolean applied = false;\n int gi = ps.getGlyph();\n int ci;\n if ((ci = getCoverageIndex(gi)) >= 0) {\n int[] rv = new int[1];\n RuleLookup[] la = getLookups(ci, gi, ps, rv);\n if (la != null) {\n ps.apply(la, rv[0]);\n applied = true;\n }\n }\n return applied;\n }\n\n /**\n * Obtain rule lookups set associated current input glyph context.\n *\n * @param ci\n * coverage index of glyph at current position\n * @param gi\n * glyph index of glyph at current position\n * @param ps\n * glyph positioning state\n * @param rv\n * array of ints used to receive multiple return values, must be of length 1 or greater,\n * where the first entry is used to return the input sequence length of the matched rule\n * @return array of rule lookups or null if none applies\n */\n public abstract RuleLookup[] getLookups(int ci, int gi, GlyphPositioningState ps, int[] rv);\n\n static GlyphPositioningSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new ContextualSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else if (format == 2) {\n return new ContextualSubtableFormat2(id, sequence, flags, format, coverage, entries);\n } else if (format == 3) {\n return new ContextualSubtableFormat3(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class ContextualSubtableFormat1 extends ContextualSubtable {\n\n private RuleSet[] rsa; // rule set array, ordered by glyph coverage index\n\n ContextualSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(1);\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphPositioningState ps, int[] rv) {\n assert ps != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedGlyphSequenceRule)) {\n ChainedGlyphSequenceRule cr = (ChainedGlyphSequenceRule) r;\n int[] iga = cr.getGlyphs(gi);\n if (matches(ps, iga, 0, rv)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n return null;\n }\n\n static boolean matches(GlyphPositioningState ps, int[] glyphs, int offset, int[] rv) {\n if ((glyphs == null) || (glyphs.length == 0)) {\n return true; // match null or empty glyph sequence\n } else {\n boolean reverse = offset < 0;\n GlyphTester ignores = ps.getIgnoreDefault();\n int[] counts = ps.getGlyphsAvailable(offset, reverse, ignores);\n int nga = counts[0];\n int ngm = glyphs.length;\n if (nga < ngm) {\n return false; // insufficient glyphs available to match\n } else {\n int[] ga = ps.getGlyphs(offset, ngm, reverse, ignores, null, counts);\n for (int k = 0; k < ngm; k++) {\n if (ga[k] != glyphs[k]) {\n return false; // match fails at ga [ k ]\n }\n }\n if (rv != null) {\n rv[0] = counts[0] + counts[1];\n }\n return true; // all glyphs match\n }\n }\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n }\n }\n }\n }\n\n private static class ContextualSubtableFormat2 extends ContextualSubtable {\n\n private GlyphClassTable cdt; // class def table\n private int ngc; // class set count\n private RuleSet[] rsa; // rule set array, ordered by class number [0...ngc - 1]\n\n ContextualSubtableFormat2(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(3);\n entries.add(cdt);\n entries.add(Integer.valueOf(ngc));\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphPositioningState ps, int[] rv) {\n assert ps != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedClassSequenceRule)) {\n ChainedClassSequenceRule cr = (ChainedClassSequenceRule) r;\n int[] ca = cr.getClasses(cdt.getClassIndex(gi, ps.getClassMatchSet(gi)));\n if (matches(ps, cdt, ca, 0, rv)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n return null;\n }\n\n static boolean matches(GlyphPositioningState ps, GlyphClassTable cdt, int[] classes, int offset, int[] rv) {\n if ((cdt == null) || (classes == null) || (classes.length == 0)) {\n return true; // match null class definitions, null or empty class sequence\n } else {\n boolean reverse = offset < 0;\n GlyphTester ignores = ps.getIgnoreDefault();\n int[] counts = ps.getGlyphsAvailable(offset, reverse, ignores);\n int nga = counts[0];\n int ngm = classes.length;\n if (nga < ngm) {\n return false; // insufficient glyphs available to match\n } else {\n int[] ga = ps.getGlyphs(offset, ngm, reverse, ignores, null, counts);\n for (int k = 0; k < ngm; k++) {\n int gi = ga[k];\n int ms = ps.getClassMatchSet(gi);\n int gc = cdt.getClassIndex(gi, ms);\n if ((gc < 0) || (gc >= cdt.getClassSize(ms))) {\n return false; // none or invalid class fails mat ch\n } else if (gc != classes[k]) {\n return false; // match fails at ga [ k ]\n }\n }\n if (rv != null) {\n rv[0] = counts[0] + counts[1];\n }\n return true; // all glyphs match\n }\n }\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 3) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 3 entries\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an GlyphClassTable, but is: \" +\n ((o != null) ? o.getClass() : null));\n } else {\n cdt = (GlyphClassTable) o;\n }\n if (((o = entries.get(1)) == null) || !(o instanceof Integer)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, second entry must be an Integer, but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n ngc = ((Integer) (o)).intValue();\n }\n if (((o = entries.get(2)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, third entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n if (rsa.length != ngc) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, RuleSet[] length is \" + rsa.length + \", but expected \" + ngc + \" glyph classes\");\n }\n }\n }\n }\n }\n\n private static class ContextualSubtableFormat3 extends ContextualSubtable {\n\n private RuleSet[] rsa; // rule set array, containing a single rule set\n\n ContextualSubtableFormat3(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(1);\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphPositioningState ps, int[] rv) {\n assert ps != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedCoverageSequenceRule)) {\n ChainedCoverageSequenceRule cr = (ChainedCoverageSequenceRule) r;\n GlyphCoverageTable[] gca = cr.getCoverages();\n if (matches(ps, gca, 0, rv)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n return null;\n }\n\n static boolean matches(GlyphPositioningState ps, GlyphCoverageTable[] gca, int offset, int[] rv) {\n if ((gca == null) || (gca.length == 0)) {\n return true; // match null or empty coverage array\n } else {\n boolean reverse = offset < 0;\n GlyphTester ignores = ps.getIgnoreDefault();\n int[] counts = ps.getGlyphsAvailable(offset, reverse, ignores);\n int nga = counts[0];\n int ngm = gca.length;\n if (nga < ngm) {\n return false; // insufficient glyphs available to match\n } else {\n int[] ga = ps.getGlyphs(offset, ngm, reverse, ignores, null, counts);\n for (int k = 0; k < ngm; k++) {\n GlyphCoverageTable ct = gca[k];\n if (ct != null) {\n if (ct.getCoverageIndex(ga[k]) < 0) {\n return false; // match fails at ga [ k ]\n }\n }\n }\n if (rv != null) {\n rv[0] = counts[0] + counts[1];\n }\n return true; // all glyphs match\n }\n }\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n }\n }\n }\n }\n\n private abstract static class ChainedContextualSubtable extends GlyphPositioningSubtable {\n\n ChainedContextualSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage);\n }\n\n /** {@inheritDoc} */\n public int getType() {\n return GPOS_LOOKUP_TYPE_CHAINED_CONTEXTUAL;\n }\n\n /** {@inheritDoc} */\n public boolean isCompatible(GlyphSubtable subtable) {\n return subtable instanceof ChainedContextualSubtable;\n }\n\n /** {@inheritDoc} */\n public boolean position(GlyphPositioningState ps) {\n boolean applied = false;\n int gi = ps.getGlyph();\n int ci;\n if ((ci = getCoverageIndex(gi)) >= 0) {\n int[] rv = new int[1];\n RuleLookup[] la = getLookups(ci, gi, ps, rv);\n if (la != null) {\n ps.apply(la, rv[0]);\n applied = true;\n }\n }\n return applied;\n }\n\n /**\n * Obtain rule lookups set associated current input glyph context.\n *\n * @param ci\n * coverage index of glyph at current position\n * @param gi\n * glyph index of glyph at current position\n * @param ps\n * glyph positioning state\n * @param rv\n * array of ints used to receive multiple return values, must be of length 1 or greater,\n * where the first entry is used to return the input sequence length of the matched rule\n * @return array of rule lookups or null if none applies\n */\n public abstract RuleLookup[] getLookups(int ci, int gi, GlyphPositioningState ps, int[] rv);\n\n static GlyphPositioningSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n if (format == 1) {\n return new ChainedContextualSubtableFormat1(id, sequence, flags, format, coverage, entries);\n } else if (format == 2) {\n return new ChainedContextualSubtableFormat2(id, sequence, flags, format, coverage, entries);\n } else if (format == 3) {\n return new ChainedContextualSubtableFormat3(id, sequence, flags, format, coverage, entries);\n } else {\n throw new UnsupportedOperationException();\n }\n }\n }\n\n private static class ChainedContextualSubtableFormat1 extends ChainedContextualSubtable {\n\n private RuleSet[] rsa; // rule set array, ordered by glyph coverage index\n\n ChainedContextualSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(1);\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphPositioningState ps, int[] rv) {\n assert ps != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedGlyphSequenceRule)) {\n ChainedGlyphSequenceRule cr = (ChainedGlyphSequenceRule) r;\n int[] iga = cr.getGlyphs(gi);\n if (matches(ps, iga, 0, rv)) {\n int[] bga = cr.getBacktrackGlyphs();\n if (matches(ps, bga, -1, null)) {\n int[] lga = cr.getLookaheadGlyphs();\n if (matches(ps, lga, rv[0], null)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n }\n }\n return null;\n }\n\n private boolean matches(GlyphPositioningState ps, int[] glyphs, int offset, int[] rv) {\n return ContextualSubtableFormat1.matches(ps, glyphs, offset, rv);\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n }\n }\n }\n }\n\n private static class ChainedContextualSubtableFormat2 extends ChainedContextualSubtable {\n\n private GlyphClassTable icdt; // input class def table\n private GlyphClassTable bcdt; // backtrack class def table\n private GlyphClassTable lcdt; // lookahead class def table\n private int ngc; // class set count\n private RuleSet[] rsa; // rule set array, ordered by class number [0...ngc - 1]\n\n ChainedContextualSubtableFormat2(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(5);\n entries.add(icdt);\n entries.add(bcdt);\n entries.add(lcdt);\n entries.add(Integer.valueOf(ngc));\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphPositioningState ps, int[] rv) {\n assert ps != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedClassSequenceRule)) {\n ChainedClassSequenceRule cr = (ChainedClassSequenceRule) r;\n int[] ica = cr.getClasses(icdt.getClassIndex(gi, ps.getClassMatchSet(gi)));\n if (matches(ps, icdt, ica, 0, rv)) {\n int[] bca = cr.getBacktrackClasses();\n if (matches(ps, bcdt, bca, -1, null)) {\n int[] lca = cr.getLookaheadClasses();\n if (matches(ps, lcdt, lca, rv[0], null)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n }\n }\n return null;\n }\n\n private boolean matches(GlyphPositioningState ps, GlyphClassTable cdt, int[] classes, int offset, int[] rv) {\n return ContextualSubtableFormat2.matches(ps, cdt, classes, offset, rv);\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 5) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 5 entries\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an GlyphClassTable, but is: \" +\n ((o != null) ? o.getClass() : null));\n } else {\n icdt = (GlyphClassTable) o;\n }\n if (((o = entries.get(1)) != null) && !(o instanceof GlyphClassTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, second entry must be an GlyphClassTable, but is: \" + o.getClass());\n } else {\n bcdt = (GlyphClassTable) o;\n }\n if (((o = entries.get(2)) != null) && !(o instanceof GlyphClassTable)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, third entry must be an GlyphClassTable, but is: \" + o.getClass());\n } else {\n lcdt = (GlyphClassTable) o;\n }\n if (((o = entries.get(3)) == null) || !(o instanceof Integer)) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, fourth entry must be an Integer, but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n ngc = ((Integer) (o)).intValue();\n }\n if (((o = entries.get(4)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, fifth entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n if (rsa.length != ngc) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, RuleSet[] length is \" + rsa.length + \", but expected \" + ngc + \" glyph classes\");\n }\n }\n }\n }\n }\n\n private static class ChainedContextualSubtableFormat3 extends ChainedContextualSubtable {\n\n private RuleSet[] rsa; // rule set array, containing a single rule set\n\n ChainedContextualSubtableFormat3(String id, int sequence, int flags, int format, GlyphCoverageTable coverage,\n List entries) {\n super(id, sequence, flags, format, coverage, entries);\n populate(entries);\n }\n\n /** {@inheritDoc} */\n public List getEntries() {\n if (rsa != null) {\n List entries = new ArrayList(1);\n entries.add(rsa);\n return entries;\n } else {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public void resolveLookupReferences(Map/*<String,LookupTable>*/ lookupTables) {\n GlyphTable.resolveLookupReferences(rsa, lookupTables);\n }\n\n /** {@inheritDoc} */\n public RuleLookup[] getLookups(int ci, int gi, GlyphPositioningState ps, int[] rv) {\n assert ps != null;\n assert (rv != null) && (rv.length > 0);\n assert rsa != null;\n if (rsa.length > 0) {\n RuleSet rs = rsa[0];\n if (rs != null) {\n Rule[] ra = rs.getRules();\n for (int i = 0, n = ra.length; i < n; i++) {\n Rule r = ra[i];\n if ((r != null) && (r instanceof ChainedCoverageSequenceRule)) {\n ChainedCoverageSequenceRule cr = (ChainedCoverageSequenceRule) r;\n GlyphCoverageTable[] igca = cr.getCoverages();\n if (matches(ps, igca, 0, rv)) {\n GlyphCoverageTable[] bgca = cr.getBacktrackCoverages();\n if (matches(ps, bgca, -1, null)) {\n GlyphCoverageTable[] lgca = cr.getLookaheadCoverages();\n if (matches(ps, lgca, rv[0], null)) {\n return r.getLookups();\n }\n }\n }\n }\n }\n }\n }\n return null;\n }\n\n private boolean matches(GlyphPositioningState ps, GlyphCoverageTable[] gca, int offset, int[] rv) {\n return ContextualSubtableFormat3.matches(ps, gca, offset, rv);\n }\n\n private void populate(List entries) {\n if (entries == null) {\n throw new AdvancedTypographicTableFormatException(\"illegal entries, must be non-null\");\n } else if (entries.size() != 1) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, \" + entries.size() + \" entries present, but requires 1 entry\");\n } else {\n Object o;\n if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) {\n throw new AdvancedTypographicTableFormatException(\n \"illegal entries, first entry must be an RuleSet[], but is: \" + ((o != null) ? o.getClass() : null));\n } else {\n rsa = (RuleSet[]) o;\n }\n }\n }\n }\n\n /**\n * The <code>DeviceTable</code> class implements a positioning device table record, comprising\n * adjustments to be made to scaled design units according to the scaled size.\n */\n public static class DeviceTable {\n\n private final int startSize;\n private final int endSize;\n private final int[] deltas;\n\n /**\n * Instantiate a DeviceTable.\n *\n * @param startSize\n * the\n * @param endSize\n * the ending (scaled) size\n * @param deltas\n * adjustments for each scaled size\n */\n public DeviceTable(int startSize, int endSize, int[] deltas) {\n assert startSize >= 0;\n assert startSize <= endSize;\n assert deltas != null;\n assert deltas.length == (endSize - startSize) + 1;\n this.startSize = startSize;\n this.endSize = endSize;\n this.deltas = deltas;\n }\n\n /** @return the start size */\n public int getStartSize() {\n return startSize;\n }\n\n /** @return the end size */\n public int getEndSize() {\n return endSize;\n }\n\n /** @return the deltas */\n public int[] getDeltas() {\n return deltas;\n }\n\n /**\n * Find device adjustment.\n *\n * @param fontSize\n * the font size to search for\n * @return an adjustment if font size matches an entry\n */\n public int findAdjustment(int fontSize) {\n // [TODO] at present, assumes that 1 device unit equals one point\n int fs = fontSize / 1000;\n if (fs < startSize) {\n return 0;\n } else if (fs <= endSize) {\n return deltas[fs - startSize] * 1000;\n } else {\n return 0;\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n return \"{ start = \" + startSize + \", end = \" + endSize + \", deltas = \" + Arrays.toString(deltas) + \"}\";\n }\n\n }\n\n /**\n * The <code>Value</code> class implements a positioning value record, comprising placement\n * and advancement information in X and Y axes, and optionally including device data used to\n * perform device (grid-fitted) specific fine grain adjustments.\n */\n public static class Value {\n\n /** X_PLACEMENT value format flag */\n public static final int X_PLACEMENT = 0x0001;\n /** Y_PLACEMENT value format flag */\n public static final int Y_PLACEMENT = 0x0002;\n /** X_ADVANCE value format flag */\n public static final int X_ADVANCE = 0x0004;\n /** Y_ADVANCE value format flag */\n public static final int Y_ADVANCE = 0x0008;\n /** X_PLACEMENT_DEVICE value format flag */\n public static final int X_PLACEMENT_DEVICE = 0x0010;\n /** Y_PLACEMENT_DEVICE value format flag */\n public static final int Y_PLACEMENT_DEVICE = 0x0020;\n /** X_ADVANCE_DEVICE value format flag */\n public static final int X_ADVANCE_DEVICE = 0x0040;\n /** Y_ADVANCE_DEVICE value format flag */\n public static final int Y_ADVANCE_DEVICE = 0x0080;\n\n /** X_PLACEMENT value index (within adjustments arrays) */\n public static final int IDX_X_PLACEMENT = 0;\n /** Y_PLACEMENT value index (within adjustments arrays) */\n public static final int IDX_Y_PLACEMENT = 1;\n /** X_ADVANCE value index (within adjustments arrays) */\n public static final int IDX_X_ADVANCE = 2;\n /** Y_ADVANCE value index (within adjustments arrays) */\n public static final int IDX_Y_ADVANCE = 3;\n\n private int xPlacement; // x placement\n private int yPlacement; // y placement\n private int xAdvance; // x advance\n private int yAdvance; // y advance\n private final DeviceTable xPlaDevice; // x placement device table\n private final DeviceTable yPlaDevice; // y placement device table\n private final DeviceTable xAdvDevice; // x advance device table\n private final DeviceTable yAdvDevice; // x advance device table\n\n /**\n * Instantiate a Value.\n *\n * @param xPlacement\n * the x placement or zero\n * @param yPlacement\n * the y placement or zero\n * @param xAdvance\n * the x advance or zero\n * @param yAdvance\n * the y advance or zero\n * @param xPlaDevice\n * the x placement device table or null\n * @param yPlaDevice\n * the y placement device table or null\n * @param xAdvDevice\n * the x advance device table or null\n * @param yAdvDevice\n * the y advance device table or null\n */\n public Value(int xPlacement, int yPlacement, int xAdvance, int yAdvance, DeviceTable xPlaDevice,\n DeviceTable yPlaDevice, DeviceTable xAdvDevice, DeviceTable yAdvDevice) {\n this.xPlacement = xPlacement;\n this.yPlacement = yPlacement;\n this.xAdvance = xAdvance;\n this.yAdvance = yAdvance;\n this.xPlaDevice = xPlaDevice;\n this.yPlaDevice = yPlaDevice;\n this.xAdvDevice = xAdvDevice;\n this.yAdvDevice = yAdvDevice;\n }\n\n /** @return the x placement */\n public int getXPlacement() {\n return xPlacement;\n }\n\n /** @return the y placement */\n public int getYPlacement() {\n return yPlacement;\n }\n\n /** @return the x advance */\n public int getXAdvance() {\n return xAdvance;\n }\n\n /** @return the y advance */\n public int getYAdvance() {\n return yAdvance;\n }\n\n /** @return the x placement device table */\n public DeviceTable getXPlaDevice() {\n return xPlaDevice;\n }\n\n /** @return the y placement device table */\n public DeviceTable getYPlaDevice() {\n return yPlaDevice;\n }\n\n /** @return the x advance device table */\n public DeviceTable getXAdvDevice() {\n return xAdvDevice;\n }\n\n /** @return the y advance device table */\n public DeviceTable getYAdvDevice() {\n return yAdvDevice;\n }\n\n /**\n * Apply value to specific adjustments to without use of device table adjustments.\n *\n * @param xPlacement\n * the x placement or zero\n * @param yPlacement\n * the y placement or zero\n * @param xAdvance\n * the x advance or zero\n * @param yAdvance\n * the y advance or zero\n */\n public void adjust(int xPlacement, int yPlacement, int xAdvance, int yAdvance) {\n this.xPlacement += xPlacement;\n this.yPlacement += yPlacement;\n this.xAdvance += xAdvance;\n this.yAdvance += yAdvance;\n }\n\n /**\n * Apply value to adjustments using font size for device table adjustments.\n *\n * @param adjustments\n * array of four integers containing X,Y placement and X,Y advance adjustments\n * @param fontSize\n * font size for device table adjustments\n * @return true if some adjustment was made\n */\n public boolean adjust(int[] adjustments, int fontSize) {\n boolean adjust = false;\n int dv;\n if ((dv = xPlacement) != 0) {\n adjustments[IDX_X_PLACEMENT] += dv;\n adjust = true;\n }\n if ((dv = yPlacement) != 0) {\n adjustments[IDX_Y_PLACEMENT] += dv;\n adjust = true;\n }\n if ((dv = xAdvance) != 0) {\n adjustments[IDX_X_ADVANCE] += dv;\n adjust = true;\n }\n if ((dv = yAdvance) != 0) {\n adjustments[IDX_Y_ADVANCE] += dv;\n adjust = true;\n }\n if (fontSize != 0) {\n DeviceTable dt;\n if ((dt = xPlaDevice) != null) {\n if ((dv = dt.findAdjustment(fontSize)) != 0) {\n adjustments[IDX_X_PLACEMENT] += dv;\n adjust = true;\n }\n }\n if ((dt = yPlaDevice) != null) {\n if ((dv = dt.findAdjustment(fontSize)) != 0) {\n adjustments[IDX_Y_PLACEMENT] += dv;\n adjust = true;\n }\n }\n if ((dt = xAdvDevice) != null) {\n if ((dv = dt.findAdjustment(fontSize)) != 0) {\n adjustments[IDX_X_ADVANCE] += dv;\n adjust = true;\n }\n }\n if ((dt = yAdvDevice) != null) {\n if ((dv = dt.findAdjustment(fontSize)) != 0) {\n adjustments[IDX_Y_ADVANCE] += dv;\n adjust = true;\n }\n }\n }\n return adjust;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n boolean first = true;\n sb.append(\"{ \");\n if (xPlacement != 0) {\n if (!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n sb.append(\"xPlacement = \" + xPlacement);\n }\n if (yPlacement != 0) {\n if (!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n sb.append(\"yPlacement = \" + yPlacement);\n }\n if (xAdvance != 0) {\n if (!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n sb.append(\"xAdvance = \" + xAdvance);\n }\n if (yAdvance != 0) {\n if (!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n sb.append(\"yAdvance = \" + yAdvance);\n }\n if (xPlaDevice != null) {\n if (!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n sb.append(\"xPlaDevice = \" + xPlaDevice);\n }\n if (yPlaDevice != null) {\n if (!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n sb.append(\"xPlaDevice = \" + yPlaDevice);\n }\n if (xAdvDevice != null) {\n if (!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n sb.append(\"xAdvDevice = \" + xAdvDevice);\n }\n if (yAdvDevice != null) {\n if (!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n sb.append(\"xAdvDevice = \" + yAdvDevice);\n }\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>PairValues</code> class implements a pair value record, comprising a glyph id (or zero)\n * and two optional positioning values.\n */\n public static class PairValues {\n\n private final int glyph; // glyph id (or 0)\n private final Value value1; // value for first glyph in pair (or null)\n private final Value value2; // value for second glyph in pair (or null)\n\n /**\n * Instantiate a PairValues.\n *\n * @param glyph\n * the glyph id (or zero)\n * @param value1\n * the value of the first glyph in pair (or null)\n * @param value2\n * the value of the second glyph in pair (or null)\n */\n public PairValues(int glyph, Value value1, Value value2) {\n assert glyph >= 0;\n this.glyph = glyph;\n this.value1 = value1;\n this.value2 = value2;\n }\n\n /** @return the glyph id */\n public int getGlyph() {\n return glyph;\n }\n\n /** @return the first value */\n public Value getValue1() {\n return value1;\n }\n\n /** @return the second value */\n public Value getValue2() {\n return value2;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n boolean first = true;\n sb.append(\"{ \");\n if (glyph != 0) {\n if (!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n sb.append(\"glyph = \" + glyph);\n }\n if (value1 != null) {\n if (!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n sb.append(\"value1 = \" + value1);\n }\n if (value2 != null) {\n if (!first) {\n sb.append(\", \");\n } else {\n first = false;\n }\n sb.append(\"value2 = \" + value2);\n }\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>Anchor</code> class implements a anchor record, comprising an X,Y coordinate pair,\n * an optional anchor point index (or -1), and optional X or Y device tables (or null if absent).\n */\n public static class Anchor {\n\n private final int x; // xCoordinate (in design units)\n private final int y; // yCoordinate (in design units)\n private final int anchorPoint; // anchor point index (or -1)\n private final DeviceTable xDevice; // x device table\n private final DeviceTable yDevice; // y device table\n\n /**\n * Instantiate an Anchor (format 1).\n *\n * @param x\n * the x coordinate\n * @param y\n * the y coordinate\n */\n public Anchor(int x, int y) {\n this(x, y, -1, null, null);\n }\n\n /**\n * Instantiate an Anchor (format 2).\n *\n * @param x\n * the x coordinate\n * @param y\n * the y coordinate\n * @param anchorPoint\n * anchor index (or -1)\n */\n public Anchor(int x, int y, int anchorPoint) {\n this(x, y, anchorPoint, null, null);\n }\n\n /**\n * Instantiate an Anchor (format 3).\n *\n * @param x\n * the x coordinate\n * @param y\n * the y coordinate\n * @param xDevice\n * the x device table (or null if not present)\n * @param yDevice\n * the y device table (or null if not present)\n */\n public Anchor(int x, int y, DeviceTable xDevice, DeviceTable yDevice) {\n this(x, y, -1, xDevice, yDevice);\n }\n\n /**\n * Instantiate an Anchor based on an existing anchor.\n *\n * @param a\n * the existing anchor\n */\n protected Anchor(Anchor a) {\n this(a.x, a.y, a.anchorPoint, a.xDevice, a.yDevice);\n }\n\n private Anchor(int x, int y, int anchorPoint, DeviceTable xDevice, DeviceTable yDevice) {\n assert (anchorPoint >= 0) || (anchorPoint == -1);\n this.x = x;\n this.y = y;\n this.anchorPoint = anchorPoint;\n this.xDevice = xDevice;\n this.yDevice = yDevice;\n }\n\n /** @return the x coordinate */\n public int getX() {\n return x;\n }\n\n /** @return the y coordinate */\n public int getY() {\n return y;\n }\n\n /** @return the anchor point index (or -1 if not specified) */\n public int getAnchorPoint() {\n return anchorPoint;\n }\n\n /** @return the x device table (or null if not specified) */\n public DeviceTable getXDevice() {\n return xDevice;\n }\n\n /** @return the y device table (or null if not specified) */\n public DeviceTable getYDevice() {\n return yDevice;\n }\n\n /**\n * Obtain adjustment value required to align the specified anchor\n * with this anchor.\n *\n * @param a\n * the anchor to align\n * @return the adjustment value needed to effect alignment\n */\n public Value getAlignmentAdjustment(Anchor a) {\n assert a != null;\n // TODO - handle anchor point\n // TODO - handle device tables\n return new Value(x - a.x, y - a.y, 0, 0, null, null, null, null);\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append(\"{ [\" + x + \",\" + y + \"]\");\n if (anchorPoint != -1) {\n sb.append(\", anchorPoint = \" + anchorPoint);\n }\n if (xDevice != null) {\n sb.append(\", xDevice = \" + xDevice);\n }\n if (yDevice != null) {\n sb.append(\", yDevice = \" + yDevice);\n }\n sb.append(\" }\");\n return sb.toString();\n }\n\n }\n\n /**\n * The <code>MarkAnchor</code> class is a subclass of the <code>Anchor</code> class, adding a mark\n * class designation.\n */\n public static class MarkAnchor extends Anchor {\n\n private final int markClass; // mark class\n\n /**\n * Instantiate a MarkAnchor\n *\n * @param markClass\n * the mark class\n * @param a\n * the underlying anchor (whose fields are copied)\n */\n public MarkAnchor(int markClass, Anchor a) {\n super(a);\n this.markClass = markClass;\n }\n\n /** @return the mark class */\n public int getMarkClass() {\n return markClass;\n }\n\n /** {@inheritDoc} */\n public String toString() {\n return \"{ markClass = \" + markClass + \", anchor = \" + super.toString() + \" }\";\n }\n\n }\n\n}", "public final class CharScript {\n\n // CSOFF: LineLength\n\n //\n // The following script codes are based on ISO 15924. Codes less than 1000 are\n // official assignments from 15924; those equal to or greater than 1000 are FOP\n // implementation specific.\n //\n /** hebrew script constant */\n public static final int SCRIPT_HEBREW = 125; // 'hebr'\n /** mongolian script constant */\n public static final int SCRIPT_MONGOLIAN = 145; // 'mong'\n /** arabic script constant */\n public static final int SCRIPT_ARABIC = 160; // 'arab'\n /** greek script constant */\n public static final int SCRIPT_GREEK = 200; // 'grek'\n /** latin script constant */\n public static final int SCRIPT_LATIN = 215; // 'latn'\n /** cyrillic script constant */\n public static final int SCRIPT_CYRILLIC = 220; // 'cyrl'\n /** georgian script constant */\n public static final int SCRIPT_GEORGIAN = 240; // 'geor'\n /** bopomofo script constant */\n public static final int SCRIPT_BOPOMOFO = 285; // 'bopo'\n /** hangul script constant */\n public static final int SCRIPT_HANGUL = 286; // 'hang'\n /** gurmukhi script constant */\n public static final int SCRIPT_GURMUKHI = 310; // 'guru'\n /** gurmukhi 2 script constant */\n public static final int SCRIPT_GURMUKHI_2 = 1310;\n // 'gur2' -- MSFT (pseudo) script tag for variant shaping semantics\n /** devanagari script constant */\n public static final int SCRIPT_DEVANAGARI = 315; // 'deva'\n /** devanagari 2 script constant */\n public static final int SCRIPT_DEVANAGARI_2 = 1315;\n // 'dev2' -- MSFT (pseudo) script tag for variant shaping semantics\n /** gujarati script constant */\n public static final int SCRIPT_GUJARATI = 320; // 'gujr'\n /** gujarati 2 script constant */\n public static final int SCRIPT_GUJARATI_2 = 1320;\n // 'gjr2' -- MSFT (pseudo) script tag for variant shaping semantics\n /** bengali script constant */\n public static final int SCRIPT_BENGALI = 326; // 'beng'\n /** bengali 2 script constant */\n public static final int SCRIPT_BENGALI_2 = 1326;\n // 'bng2' -- MSFT (pseudo) script tag for variant shaping semantics\n /** oriya script constant */\n public static final int SCRIPT_ORIYA = 327; // 'orya'\n /** oriya 2 script constant */\n public static final int SCRIPT_ORIYA_2 = 1327;\n // 'ory2' -- MSFT (pseudo) script tag for variant shaping semantics\n /** tibetan script constant */\n public static final int SCRIPT_TIBETAN = 330; // 'tibt'\n /** telugu script constant */\n public static final int SCRIPT_TELUGU = 340; // 'telu'\n /** telugu 2 script constant */\n public static final int SCRIPT_TELUGU_2 = 1340;\n // 'tel2' -- MSFT (pseudo) script tag for variant shaping semantics\n /** kannada script constant */\n public static final int SCRIPT_KANNADA = 345; // 'knda'\n /** kannada 2 script constant */\n public static final int SCRIPT_KANNADA_2 = 1345;\n // 'knd2' -- MSFT (pseudo) script tag for variant shaping semantics\n /** tamil script constant */\n public static final int SCRIPT_TAMIL = 346; // 'taml'\n /** tamil 2 script constant */\n public static final int SCRIPT_TAMIL_2 = 1346;\n // 'tml2' -- MSFT (pseudo) script tag for variant shaping semantics\n /** malayalam script constant */\n public static final int SCRIPT_MALAYALAM = 347; // 'mlym'\n /** malayalam 2 script constant */\n public static final int SCRIPT_MALAYALAM_2 = 1347;\n // 'mlm2' -- MSFT (pseudo) script tag for variant shaping semantics\n /** sinhalese script constant */\n public static final int SCRIPT_SINHALESE = 348; // 'sinh'\n /** burmese script constant */\n public static final int SCRIPT_BURMESE = 350; // 'mymr'\n /** thai script constant */\n public static final int SCRIPT_THAI = 352; // 'thai'\n /** khmer script constant */\n public static final int SCRIPT_KHMER = 355; // 'khmr'\n /** lao script constant */\n public static final int SCRIPT_LAO = 356; // 'laoo'\n /** hiragana script constant */\n public static final int SCRIPT_HIRAGANA = 410; // 'hira'\n /** ethiopic script constant */\n public static final int SCRIPT_ETHIOPIC = 430; // 'ethi'\n /** han script constant */\n public static final int SCRIPT_HAN = 500; // 'hani'\n /** katakana script constant */\n public static final int SCRIPT_KATAKANA = 410; // 'kana'\n /** math script constant */\n public static final int SCRIPT_MATH = 995; // 'zmth'\n /** symbol script constant */\n public static final int SCRIPT_SYMBOL = 996; // 'zsym'\n /** undetermined script constant */\n public static final int SCRIPT_UNDETERMINED = 998; // 'zyyy'\n /** uncoded script constant */\n public static final int SCRIPT_UNCODED = 999; // 'zzzz'\n\n /**\n * A static (class) parameter indicating whether V2 indic shaping\n * rules apply or not, with default being <code>true</code>.\n */\n private static final boolean USE_V2_INDIC = true;\n\n private CharScript() {\n }\n\n /**\n * Determine if character c is punctuation.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character is punctuation\n */\n public static boolean isPunctuation(int c) {\n if ((c >= 0x0021) && (c <= 0x002F)) { // basic latin punctuation\n return true;\n } else if ((c >= 0x003A) && (c <= 0x0040)) { // basic latin punctuation\n return true;\n } else if ((c >= 0x005F) && (c <= 0x0060)) { // basic latin punctuation\n return true;\n } else if ((c >= 0x007E) && (c <= 0x007E)) { // basic latin punctuation\n return true;\n } else if ((c >= 0x00A1) && (c <= 0x00BF)) { // latin supplement punctuation\n return true;\n } else if ((c >= 0x00D7) && (c <= 0x00D7)) { // latin supplement punctuation\n return true;\n } else if ((c >= 0x00F7) && (c <= 0x00F7)) { // latin supplement punctuation\n return true;\n } else // general punctuation\n// [TBD] - not complete\n return (c >= 0x2000) && (c <= 0x206F);\n }\n\n /**\n * Determine if character c is a digit.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character is a digit\n */\n public static boolean isDigit(int c) {\n // basic latin digits\n// [TBD] - not complete\n return (c >= 0x0030) && (c <= 0x0039);\n }\n\n /**\n * Determine if character c belong to the hebrew script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to hebrew script\n */\n public static boolean isHebrew(int c) {\n if ((c >= 0x0590) && (c <= 0x05FF)) { // hebrew block\n return true;\n } else // hebrew presentation forms block\n return (c >= 0xFB00) && (c <= 0xFB4F);\n }\n\n /**\n * Determine if character c belong to the mongolian script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to mongolian script\n */\n public static boolean isMongolian(int c) {\n // mongolian block\n return (c >= 0x1800) && (c <= 0x18AF);\n }\n\n /**\n * Determine if character c belong to the arabic script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to arabic script\n */\n public static boolean isArabic(int c) {\n if ((c >= 0x0600) && (c <= 0x06FF)) { // arabic block\n return true;\n } else if ((c >= 0x0750) && (c <= 0x077F)) { // arabic supplement block\n return true;\n } else if ((c >= 0xFB50) && (c <= 0xFDFF)) { // arabic presentation forms a block\n return true;\n } else // arabic presentation forms b block\n return (c >= 0xFE70) && (c <= 0xFEFF);\n }\n\n /**\n * Determine if character c belong to the greek script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to greek script\n */\n public static boolean isGreek(int c) {\n if ((c >= 0x0370) && (c <= 0x03FF)) { // greek (and coptic) block\n return true;\n } else // greek extended block\n return (c >= 0x1F00) && (c <= 0x1FFF);\n }\n\n /**\n * Determine if character c belong to the latin script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to latin script\n */\n public static boolean isLatin(int c) {\n if ((c >= 0x0041) && (c <= 0x005A)) { // basic latin upper case\n return true;\n } else if ((c >= 0x0061) && (c <= 0x007A)) { // basic latin lower case\n return true;\n } else if ((c >= 0x00C0) && (c <= 0x00D6)) { // latin supplement upper case\n return true;\n } else if ((c >= 0x00D8) && (c <= 0x00DF)) { // latin supplement upper case\n return true;\n } else if ((c >= 0x00E0) && (c <= 0x00F6)) { // latin supplement lower case\n return true;\n } else if ((c >= 0x00F8) && (c <= 0x00FF)) { // latin supplement lower case\n return true;\n } else if ((c >= 0x0100) && (c <= 0x017F)) { // latin extended a\n return true;\n } else if ((c >= 0x0180) && (c <= 0x024F)) { // latin extended b\n return true;\n } else if ((c >= 0x1E00) && (c <= 0x1EFF)) { // latin extended additional\n return true;\n } else if ((c >= 0x2C60) && (c <= 0x2C7F)) { // latin extended c\n return true;\n } else if ((c >= 0xA720) && (c <= 0xA7FF)) { // latin extended d\n return true;\n } else // latin ligatures\n return (c >= 0xFB00) && (c <= 0xFB0F);\n }\n\n /**\n * Determine if character c belong to the cyrillic script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to cyrillic script\n */\n public static boolean isCyrillic(int c) {\n if ((c >= 0x0400) && (c <= 0x04FF)) { // cyrillic block\n return true;\n } else if ((c >= 0x0500) && (c <= 0x052F)) { // cyrillic supplement block\n return true;\n } else if ((c >= 0x2DE0) && (c <= 0x2DFF)) { // cyrillic extended-a block\n return true;\n } else // cyrillic extended-b block\n return (c >= 0xA640) && (c <= 0xA69F);\n }\n\n /**\n * Determine if character c belong to the georgian script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to georgian script\n */\n public static boolean isGeorgian(int c) {\n if ((c >= 0x10A0) && (c <= 0x10FF)) { // georgian block\n return true;\n } else // georgian supplement block\n return (c >= 0x2D00) && (c <= 0x2D2F);\n }\n\n /**\n * Determine if character c belong to the hangul script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to hangul script\n */\n public static boolean isHangul(int c) {\n if ((c >= 0x1100) && (c <= 0x11FF)) { // hangul jamo\n return true;\n } else if ((c >= 0x3130) && (c <= 0x318F)) { // hangul compatibility jamo\n return true;\n } else if ((c >= 0xA960) && (c <= 0xA97F)) { // hangul jamo extended a\n return true;\n } else if ((c >= 0xAC00) && (c <= 0xD7A3)) { // hangul syllables\n return true;\n } else // hangul jamo extended a\n return (c >= 0xD7B0) && (c <= 0xD7FF);\n }\n\n /**\n * Determine if character c belong to the gurmukhi script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to gurmukhi script\n */\n public static boolean isGurmukhi(int c) {\n // gurmukhi block\n return (c >= 0x0A00) && (c <= 0x0A7F);\n }\n\n /**\n * Determine if character c belong to the devanagari script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to devanagari script\n */\n public static boolean isDevanagari(int c) {\n if ((c >= 0x0900) && (c <= 0x097F)) { // devangari block\n return true;\n } else // devangari extended block\n return (c >= 0xA8E0) && (c <= 0xA8FF);\n }\n\n /**\n * Determine if character c belong to the gujarati script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to gujarati script\n */\n public static boolean isGujarati(int c) {\n // gujarati block\n return (c >= 0x0A80) && (c <= 0x0AFF);\n }\n\n /**\n * Determine if character c belong to the bengali script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to bengali script\n */\n public static boolean isBengali(int c) {\n // bengali block\n return (c >= 0x0980) && (c <= 0x09FF);\n }\n\n /**\n * Determine if character c belong to the oriya script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to oriya script\n */\n public static boolean isOriya(int c) {\n // oriya block\n return (c >= 0x0B00) && (c <= 0x0B7F);\n }\n\n /**\n * Determine if character c belong to the tibetan script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to tibetan script\n */\n public static boolean isTibetan(int c) {\n // tibetan block\n return (c >= 0x0F00) && (c <= 0x0FFF);\n }\n\n /**\n * Determine if character c belong to the telugu script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to telugu script\n */\n public static boolean isTelugu(int c) {\n // telugu block\n return (c >= 0x0C00) && (c <= 0x0C7F);\n }\n\n /**\n * Determine if character c belong to the kannada script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to kannada script\n */\n public static boolean isKannada(int c) {\n // kannada block\n return (c >= 0x0C00) && (c <= 0x0C7F);\n }\n\n /**\n * Determine if character c belong to the tamil script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to tamil script\n */\n public static boolean isTamil(int c) {\n // tamil block\n return (c >= 0x0B80) && (c <= 0x0BFF);\n }\n\n /**\n * Determine if character c belong to the malayalam script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to malayalam script\n */\n public static boolean isMalayalam(int c) {\n // malayalam block\n return (c >= 0x0D00) && (c <= 0x0D7F);\n }\n\n /**\n * Determine if character c belong to the sinhalese script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to sinhalese script\n */\n public static boolean isSinhalese(int c) {\n // sinhala block\n return (c >= 0x0D80) && (c <= 0x0DFF);\n }\n\n /**\n * Determine if character c belong to the burmese script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to burmese script\n */\n public static boolean isBurmese(int c) {\n if ((c >= 0x1000) && (c <= 0x109F)) { // burmese (myanmar) block\n return true;\n } else // burmese (myanmar) extended block\n return (c >= 0xAA60) && (c <= 0xAA7F);\n }\n\n /**\n * Determine if character c belong to the thai script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to thai script\n */\n public static boolean isThai(int c) {\n // thai block\n return (c >= 0x0E00) && (c <= 0x0E7F);\n }\n\n /**\n * Determine if character c belong to the khmer script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to khmer script\n */\n public static boolean isKhmer(int c) {\n if ((c >= 0x1780) && (c <= 0x17FF)) { // khmer block\n return true;\n } else // khmer symbols block\n return (c >= 0x19E0) && (c <= 0x19FF);\n }\n\n /**\n * Determine if character c belong to the lao script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to lao script\n */\n public static boolean isLao(int c) {\n // lao block\n return (c >= 0x0E80) && (c <= 0x0EFF);\n }\n\n /**\n * Determine if character c belong to the ethiopic (amharic) script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to ethiopic (amharic) script\n */\n public static boolean isEthiopic(int c) {\n if ((c >= 0x1200) && (c <= 0x137F)) { // ethiopic block\n return true;\n } else if ((c >= 0x1380) && (c <= 0x139F)) { // ethoipic supplement block\n return true;\n } else if ((c >= 0x2D80) && (c <= 0x2DDF)) { // ethoipic extended block\n return true;\n } else // ethoipic extended-a block\n return (c >= 0xAB00) && (c <= 0xAB2F);\n }\n\n /**\n * Determine if character c belong to the han (unified cjk) script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to han (unified cjk) script\n */\n public static boolean isHan(int c) {\n if ((c >= 0x3400) && (c <= 0x4DBF)) {\n return true; // cjk unified ideographs extension a\n } else if ((c >= 0x4E00) && (c <= 0x9FFF)) {\n return true; // cjk unified ideographs\n } else if ((c >= 0xF900) && (c <= 0xFAFF)) {\n return true; // cjk compatibility ideographs\n } else if ((c >= 0x20000) && (c <= 0x2A6DF)) {\n return true; // cjk unified ideographs extension b\n } else if ((c >= 0x2A700) && (c <= 0x2B73F)) {\n return true; // cjk unified ideographs extension c\n } else // cjk compatibility ideographs supplement\n return (c >= 0x2F800) && (c <= 0x2FA1F);\n }\n\n /**\n * Determine if character c belong to the bopomofo script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to bopomofo script\n */\n public static boolean isBopomofo(int c) {\n return (c >= 0x3100) && (c <= 0x312F);\n }\n\n /**\n * Determine if character c belong to the hiragana script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to hiragana script\n */\n public static boolean isHiragana(int c) {\n return (c >= 0x3040) && (c <= 0x309F);\n }\n\n /**\n * Determine if character c belong to the katakana script.\n *\n * @param c\n * a character represented as a unicode scalar value\n * @return true if character belongs to katakana script\n */\n public static boolean isKatakana(int c) {\n if ((c >= 0x30A0) && (c <= 0x30FF)) {\n return true;\n } else return (c >= 0x31F0) && (c <= 0x31FF);\n }\n\n /**\n * Obtain ISO15924 numeric script code of character. If script is not or cannot be determined,\n * then the script code 998 ('zyyy') is returned.\n *\n * @param c\n * the character to obtain script\n * @return an ISO15924 script code\n */\n public static int scriptOf(int c) { // [TBD] - needs optimization!!!\n if (CharUtilities.isAnySpace(c)) {\n return SCRIPT_UNDETERMINED;\n } else if (isPunctuation(c)) {\n return SCRIPT_UNDETERMINED;\n } else if (isDigit(c)) {\n return SCRIPT_UNDETERMINED;\n } else if (isLatin(c)) {\n return SCRIPT_LATIN;\n } else if (isCyrillic(c)) {\n return SCRIPT_CYRILLIC;\n } else if (isGreek(c)) {\n return SCRIPT_GREEK;\n } else if (isHan(c)) {\n return SCRIPT_HAN;\n } else if (isBopomofo(c)) {\n return SCRIPT_BOPOMOFO;\n } else if (isKatakana(c)) {\n return SCRIPT_KATAKANA;\n } else if (isHiragana(c)) {\n return SCRIPT_HIRAGANA;\n } else if (isHangul(c)) {\n return SCRIPT_HANGUL;\n } else if (isArabic(c)) {\n return SCRIPT_ARABIC;\n } else if (isHebrew(c)) {\n return SCRIPT_HEBREW;\n } else if (isMongolian(c)) {\n return SCRIPT_MONGOLIAN;\n } else if (isGeorgian(c)) {\n return SCRIPT_GEORGIAN;\n } else if (isGurmukhi(c)) {\n return useV2IndicRules(SCRIPT_GURMUKHI);\n } else if (isDevanagari(c)) {\n return useV2IndicRules(SCRIPT_DEVANAGARI);\n } else if (isGujarati(c)) {\n return useV2IndicRules(SCRIPT_GUJARATI);\n } else if (isBengali(c)) {\n return useV2IndicRules(SCRIPT_BENGALI);\n } else if (isOriya(c)) {\n return useV2IndicRules(SCRIPT_ORIYA);\n } else if (isTibetan(c)) {\n return SCRIPT_TIBETAN;\n } else if (isTelugu(c)) {\n return useV2IndicRules(SCRIPT_TELUGU);\n } else if (isKannada(c)) {\n return useV2IndicRules(SCRIPT_KANNADA);\n } else if (isTamil(c)) {\n return useV2IndicRules(SCRIPT_TAMIL);\n } else if (isMalayalam(c)) {\n return useV2IndicRules(SCRIPT_MALAYALAM);\n } else if (isSinhalese(c)) {\n return SCRIPT_SINHALESE;\n } else if (isBurmese(c)) {\n return SCRIPT_BURMESE;\n } else if (isThai(c)) {\n return SCRIPT_THAI;\n } else if (isKhmer(c)) {\n return SCRIPT_KHMER;\n } else if (isLao(c)) {\n return SCRIPT_LAO;\n } else if (isEthiopic(c)) {\n return SCRIPT_ETHIOPIC;\n } else {\n return SCRIPT_UNDETERMINED;\n }\n }\n\n /**\n * Obtain the V2 indic script code corresponding to V1 indic script code SC if\n * and only iff V2 indic rules apply; otherwise return SC.\n *\n * @param sc\n * a V1 indic script code\n * @return either SC or the V2 flavor of SC if V2 indic rules apply\n */\n public static int useV2IndicRules(int sc) {\n if (USE_V2_INDIC) {\n return (sc < 1000) ? (sc + 1000) : sc;\n } else {\n return sc;\n }\n }\n\n /**\n * Obtain the script codes of each character in a character sequence. If script\n * is not or cannot be determined for some character, then the script code 998\n * ('zyyy') is returned.\n *\n * @param cs\n * the character sequence\n * @return a (possibly empty) array of script codes\n */\n public static int[] scriptsOf(CharSequence cs) {\n Set s = new HashSet();\n for (int i = 0, n = cs.length(); i < n; i++) {\n s.add(Integer.valueOf(scriptOf(cs.charAt(i))));\n }\n int[] sa = new int[s.size()];\n int ns = 0;\n for (Iterator it = s.iterator(); it.hasNext(); ) {\n sa[ns++] = ((Integer) it.next()).intValue();\n }\n Arrays.sort(sa);\n return sa;\n }\n\n /**\n * Determine the dominant script of a character sequence.\n *\n * @param cs\n * the character sequence\n * @return the dominant script or SCRIPT_UNDETERMINED\n */\n public static int dominantScript(CharSequence cs) {\n Map m = new HashMap();\n for (int i = 0, n = cs.length(); i < n; i++) {\n int c = cs.charAt(i);\n int s = scriptOf(c);\n Integer k = Integer.valueOf(s);\n Integer v = (Integer) m.get(k);\n if (v != null) {\n m.put(k, Integer.valueOf(v.intValue() + 1));\n } else {\n m.put(k, Integer.valueOf(0));\n }\n }\n int sMax = -1;\n int cMax = -1;\n for (Iterator it = m.entrySet().iterator(); it.hasNext(); ) {\n Map.Entry e = (Map.Entry) it.next();\n Integer k = (Integer) e.getKey();\n int s = k.intValue();\n switch (s) {\n case SCRIPT_UNDETERMINED:\n case SCRIPT_UNCODED:\n break;\n default:\n Integer v = (Integer) e.getValue();\n assert v != null;\n int c = v.intValue();\n if (c > cMax) {\n cMax = c;\n sMax = s;\n }\n break;\n }\n }\n if (sMax < 0) {\n sMax = SCRIPT_UNDETERMINED;\n }\n return sMax;\n }\n\n /**\n * Determine if script tag denotes an 'Indic' script, where a\n * script is an 'Indic' script if it is intended to be processed by\n * the generic 'Indic' Script Processor.\n *\n * @param script\n * a script tag\n * @return true if script tag is a designated 'Indic' script\n */\n public static boolean isIndicScript(String script) {\n return isIndicScript(scriptCodeFromTag(script));\n }\n\n /**\n * Determine if script tag denotes an 'Indic' script, where a\n * script is an 'Indic' script if it is intended to be processed by\n * the generic 'Indic' Script Processor.\n *\n * @param script\n * a script code\n * @return true if script code is a designated 'Indic' script\n */\n public static boolean isIndicScript(int script) {\n switch (script) {\n case SCRIPT_BENGALI:\n case SCRIPT_BENGALI_2:\n case SCRIPT_BURMESE:\n case SCRIPT_DEVANAGARI:\n case SCRIPT_DEVANAGARI_2:\n case SCRIPT_GUJARATI:\n case SCRIPT_GUJARATI_2:\n case SCRIPT_GURMUKHI:\n case SCRIPT_GURMUKHI_2:\n case SCRIPT_KANNADA:\n case SCRIPT_KANNADA_2:\n case SCRIPT_MALAYALAM:\n case SCRIPT_MALAYALAM_2:\n case SCRIPT_ORIYA:\n case SCRIPT_ORIYA_2:\n case SCRIPT_TAMIL:\n case SCRIPT_TAMIL_2:\n case SCRIPT_TELUGU:\n case SCRIPT_TELUGU_2:\n return true;\n default:\n return false;\n }\n }\n\n /**\n * Determine the script tag associated with an internal script code.\n *\n * @param code\n * the script code\n * @return a script tag\n */\n public static String scriptTagFromCode(int code) {\n Map<Integer, String> m = getScriptTagsMap();\n if (m != null) {\n String tag;\n if ((tag = m.get(Integer.valueOf(code))) != null) {\n return tag;\n } else {\n return \"\";\n }\n } else {\n return \"\";\n }\n }\n\n /**\n * Determine the internal script code associated with a script tag.\n *\n * @param tag\n * the script tag\n * @return a script code\n */\n public static int scriptCodeFromTag(String tag) {\n Map<String, Integer> m = getScriptCodeMap();\n if (m != null) {\n Integer c;\n if ((c = m.get(tag)) != null) {\n return c;\n } else {\n return SCRIPT_UNDETERMINED;\n }\n } else {\n return SCRIPT_UNDETERMINED;\n }\n }\n\n private static Map<Integer, String> scriptTagsMap;\n private static Map<String, Integer> scriptCodeMap;\n\n private static void putScriptTag(Map tm, Map cm, int code, String tag) {\n assert tag != null;\n assert tag.length() != 0;\n assert code >= 0;\n assert code < 2000;\n tm.put(Integer.valueOf(code), tag);\n cm.put(tag, Integer.valueOf(code));\n }\n\n private static void makeScriptMaps() {\n HashMap<Integer, String> tm = new HashMap<Integer, String>();\n HashMap<String, Integer> cm = new HashMap<String, Integer>();\n putScriptTag(tm, cm, SCRIPT_HEBREW, \"hebr\");\n putScriptTag(tm, cm, SCRIPT_MONGOLIAN, \"mong\");\n putScriptTag(tm, cm, SCRIPT_ARABIC, \"arab\");\n putScriptTag(tm, cm, SCRIPT_GREEK, \"grek\");\n putScriptTag(tm, cm, SCRIPT_LATIN, \"latn\");\n putScriptTag(tm, cm, SCRIPT_CYRILLIC, \"cyrl\");\n putScriptTag(tm, cm, SCRIPT_GEORGIAN, \"geor\");\n putScriptTag(tm, cm, SCRIPT_BOPOMOFO, \"bopo\");\n putScriptTag(tm, cm, SCRIPT_HANGUL, \"hang\");\n putScriptTag(tm, cm, SCRIPT_GURMUKHI, \"guru\");\n putScriptTag(tm, cm, SCRIPT_GURMUKHI_2, \"gur2\");\n putScriptTag(tm, cm, SCRIPT_DEVANAGARI, \"deva\");\n putScriptTag(tm, cm, SCRIPT_DEVANAGARI_2, \"dev2\");\n putScriptTag(tm, cm, SCRIPT_GUJARATI, \"gujr\");\n putScriptTag(tm, cm, SCRIPT_GUJARATI_2, \"gjr2\");\n putScriptTag(tm, cm, SCRIPT_BENGALI, \"beng\");\n putScriptTag(tm, cm, SCRIPT_BENGALI_2, \"bng2\");\n putScriptTag(tm, cm, SCRIPT_ORIYA, \"orya\");\n putScriptTag(tm, cm, SCRIPT_ORIYA_2, \"ory2\");\n putScriptTag(tm, cm, SCRIPT_TIBETAN, \"tibt\");\n putScriptTag(tm, cm, SCRIPT_TELUGU, \"telu\");\n putScriptTag(tm, cm, SCRIPT_TELUGU_2, \"tel2\");\n putScriptTag(tm, cm, SCRIPT_KANNADA, \"knda\");\n putScriptTag(tm, cm, SCRIPT_KANNADA_2, \"knd2\");\n putScriptTag(tm, cm, SCRIPT_TAMIL, \"taml\");\n putScriptTag(tm, cm, SCRIPT_TAMIL_2, \"tml2\");\n putScriptTag(tm, cm, SCRIPT_MALAYALAM, \"mlym\");\n putScriptTag(tm, cm, SCRIPT_MALAYALAM_2, \"mlm2\");\n putScriptTag(tm, cm, SCRIPT_SINHALESE, \"sinh\");\n putScriptTag(tm, cm, SCRIPT_BURMESE, \"mymr\");\n putScriptTag(tm, cm, SCRIPT_THAI, \"thai\");\n putScriptTag(tm, cm, SCRIPT_KHMER, \"khmr\");\n putScriptTag(tm, cm, SCRIPT_LAO, \"laoo\");\n putScriptTag(tm, cm, SCRIPT_HIRAGANA, \"hira\");\n putScriptTag(tm, cm, SCRIPT_ETHIOPIC, \"ethi\");\n putScriptTag(tm, cm, SCRIPT_HAN, \"hani\");\n putScriptTag(tm, cm, SCRIPT_KATAKANA, \"kana\");\n putScriptTag(tm, cm, SCRIPT_MATH, \"zmth\");\n putScriptTag(tm, cm, SCRIPT_SYMBOL, \"zsym\");\n putScriptTag(tm, cm, SCRIPT_UNDETERMINED, \"zyyy\");\n putScriptTag(tm, cm, SCRIPT_UNCODED, \"zzzz\");\n scriptTagsMap = tm;\n scriptCodeMap = cm;\n }\n\n private static Map<Integer, String> getScriptTagsMap() {\n if (scriptTagsMap == null) {\n makeScriptMaps();\n }\n return scriptTagsMap;\n }\n\n private static Map<String, Integer> getScriptCodeMap() {\n if (scriptCodeMap == null) {\n makeScriptMaps();\n }\n return scriptCodeMap;\n }\n\n}", "public class GlyphSequence implements Cloneable {\n\n /** default character buffer capacity in case new character buffer is created */\n private static final int DEFAULT_CHARS_CAPACITY = 8;\n\n /** character buffer */\n private IntBuffer characters;\n /** glyph buffer */\n private IntBuffer glyphs;\n /** association list */\n private List associations;\n /** predications flag */\n private boolean predications;\n\n /**\n * Instantiate a glyph sequence, reusing (i.e., not copying) the referenced\n * character and glyph buffers and associations. If characters is null, then\n * an empty character buffer is created. If glyphs is null, then a glyph buffer\n * is created whose capacity is that of the character buffer. If associations is\n * null, then identity associations are created.\n *\n * @param characters\n * a (possibly null) buffer of associated (originating) characters\n * @param glyphs\n * a (possibly null) buffer of glyphs\n * @param associations\n * a (possibly null) array of glyph to character associations\n * @param predications\n * true if predications are enabled\n */\n public GlyphSequence(IntBuffer characters, IntBuffer glyphs, List associations, boolean predications) {\n if (characters == null) {\n characters = IntBuffer.allocate(DEFAULT_CHARS_CAPACITY);\n }\n if (glyphs == null) {\n glyphs = IntBuffer.allocate(characters.capacity());\n }\n if (associations == null) {\n associations = makeIdentityAssociations(characters.limit(), glyphs.limit());\n }\n this.characters = characters;\n this.glyphs = glyphs;\n this.associations = associations;\n this.predications = predications;\n }\n\n /**\n * Instantiate a glyph sequence, reusing (i.e., not copying) the referenced\n * character and glyph buffers and associations. If characters is null, then\n * an empty character buffer is created. If glyphs is null, then a glyph buffer\n * is created whose capacity is that of the character buffer. If associations is\n * null, then identity associations are created.\n *\n * @param characters\n * a (possibly null) buffer of associated (originating) characters\n * @param glyphs\n * a (possibly null) buffer of glyphs\n * @param associations\n * a (possibly null) array of glyph to character associations\n */\n public GlyphSequence(IntBuffer characters, IntBuffer glyphs, List associations) {\n this(characters, glyphs, associations, false);\n }\n\n /**\n * Instantiate a glyph sequence using an existing glyph sequence, where the new glyph sequence shares\n * the character array of the existing sequence (but not the buffer object), and creates new copies\n * of glyphs buffer and association list.\n *\n * @param gs\n * an existing glyph sequence\n */\n public GlyphSequence(GlyphSequence gs) {\n this(gs.characters.duplicate(), copyBuffer(gs.glyphs), copyAssociations(gs.associations), gs.predications);\n }\n\n /**\n * Instantiate a glyph sequence using an existing glyph sequence, where the new glyph sequence shares\n * the character array of the existing sequence (but not the buffer object), but uses the specified\n * backtrack, input, and lookahead glyph arrays to populate the glyphs, and uses the specified\n * of glyphs buffer and association list.\n * backtrack, input, and lookahead association arrays to populate the associations.\n *\n * @param gs\n * an existing glyph sequence\n * @param bga\n * backtrack glyph array\n * @param iga\n * input glyph array\n * @param lga\n * lookahead glyph array\n * @param bal\n * backtrack association list\n * @param ial\n * input association list\n * @param lal\n * lookahead association list\n */\n public GlyphSequence(GlyphSequence gs, int[] bga, int[] iga, int[] lga, CharAssociation[] bal, CharAssociation[] ial,\n CharAssociation[] lal) {\n this(gs.characters.duplicate(), concatGlyphs(bga, iga, lga), concatAssociations(bal, ial, lal), gs.predications);\n }\n\n /**\n * Obtain reference to underlying character buffer.\n *\n * @return character buffer reference\n */\n public IntBuffer getCharacters() {\n return characters;\n }\n\n /**\n * Obtain array of characters. If <code>copy</code> is true, then\n * a newly instantiated array is returned, otherwise a reference to\n * the underlying buffer's array is returned. N.B. in case a reference\n * to the undelying buffer's array is returned, the length\n * of the array is not necessarily the number of characters in array.\n * To determine the number of characters, use {@link #getCharacterCount}.\n *\n * @param copy\n * true if to return a newly instantiated array of characters\n * @return array of characters\n */\n public int[] getCharacterArray(boolean copy) {\n if (copy) {\n return toArray(characters);\n } else {\n return characters.array();\n }\n }\n\n /**\n * Obtain the number of characters in character array, where\n * each character constitutes a unicode scalar value.\n *\n * @return number of characters available in character array\n */\n public int getCharacterCount() {\n return characters.limit();\n }\n\n /**\n * Obtain glyph id at specified index.\n *\n * @param index\n * to obtain glyph\n * @return the glyph identifier of glyph at specified index\n * @throws IndexOutOfBoundsException\n * if index is less than zero\n * or exceeds last valid position\n */\n public int getGlyph(int index) throws IndexOutOfBoundsException {\n return glyphs.get(index);\n }\n\n /**\n * Set glyph id at specified index.\n *\n * @param index\n * to set glyph\n * @param gi\n * glyph index\n * @throws IndexOutOfBoundsException\n * if index is greater or equal to\n * the limit of the underlying glyph buffer\n */\n public void setGlyph(int index, int gi) throws IndexOutOfBoundsException {\n if (gi > 65535) {\n gi = 65535;\n }\n glyphs.put(index, gi);\n }\n\n /**\n * Obtain reference to underlying glyph buffer.\n *\n * @return glyph buffer reference\n */\n public IntBuffer getGlyphs() {\n return glyphs;\n }\n\n /**\n * Obtain count glyphs starting at offset. If <code>count</code> is\n * negative, then it is treated as if the number of available glyphs\n * were specified.\n *\n * @param offset\n * into glyph sequence\n * @param count\n * of glyphs to obtain starting at offset, or negative,\n * indicating all avaialble glyphs starting at offset\n * @return glyph array\n */\n public int[] getGlyphs(int offset, int count) {\n int ng = getGlyphCount();\n if (offset < 0) {\n offset = 0;\n } else if (offset > ng) {\n offset = ng;\n }\n if (count < 0) {\n count = ng - offset;\n }\n int[] ga = new int[count];\n for (int i = offset, n = offset + count, k = 0; i < n; i++) {\n if (k < ga.length) {\n ga[k++] = glyphs.get(i);\n }\n }\n return ga;\n }\n\n /**\n * Obtain array of glyphs. If <code>copy</code> is true, then\n * a newly instantiated array is returned, otherwise a reference to\n * the underlying buffer's array is returned. N.B. in case a reference\n * to the undelying buffer's array is returned, the length\n * of the array is not necessarily the number of glyphs in array.\n * To determine the number of glyphs, use {@link #getGlyphCount}.\n *\n * @param copy\n * true if to return a newly instantiated array of glyphs\n * @return array of glyphs\n */\n public int[] getGlyphArray(boolean copy) {\n if (copy) {\n return toArray(glyphs);\n } else {\n return glyphs.array();\n }\n }\n\n /**\n * Obtain the number of glyphs in glyphs array, where\n * each glyph constitutes a font specific glyph index.\n *\n * @return number of glyphs available in character array\n */\n public int getGlyphCount() {\n return glyphs.limit();\n }\n\n /**\n * Obtain association at specified index.\n *\n * @param index\n * into associations array\n * @return glyph to character associations at specified index\n * @throws IndexOutOfBoundsException\n * if index is less than zero\n * or exceeds last valid position\n */\n public CharAssociation getAssociation(int index) throws IndexOutOfBoundsException {\n return (CharAssociation) associations.get(index);\n }\n\n /**\n * Obtain reference to underlying associations list.\n *\n * @return associations list\n */\n public List getAssociations() {\n return associations;\n }\n\n /**\n * Obtain count associations starting at offset.\n *\n * @param offset\n * into glyph sequence\n * @param count\n * of associations to obtain starting at offset, or negative,\n * indicating all avaialble associations starting at offset\n * @return associations\n */\n public CharAssociation[] getAssociations(int offset, int count) {\n int ng = getGlyphCount();\n if (offset < 0) {\n offset = 0;\n } else if (offset > ng) {\n offset = ng;\n }\n if (count < 0) {\n count = ng - offset;\n }\n CharAssociation[] aa = new CharAssociation[count];\n for (int i = offset, n = offset + count, k = 0; i < n; i++) {\n if (k < aa.length) {\n aa[k++] = (CharAssociation) associations.get(i);\n }\n }\n return aa;\n }\n\n /**\n * Enable or disable predications.\n *\n * @param enable\n * true if predications are to be enabled; otherwise false to disable\n */\n public void setPredications(boolean enable) {\n this.predications = enable;\n }\n\n /**\n * Obtain predications state.\n *\n * @return true if predications are enabled\n */\n public boolean getPredications() {\n return this.predications;\n }\n\n /**\n * Set predication <KEY,VALUE> at glyph sequence OFFSET.\n *\n * @param offset\n * offset (index) into glyph sequence\n * @param key\n * predication key\n * @param value\n * predication value\n */\n public void setPredication(int offset, String key, Object value) {\n if (predications) {\n CharAssociation[] aa = getAssociations(offset, 1);\n CharAssociation ca = aa[0];\n ca.setPredication(key, value);\n }\n }\n\n /**\n * Get predication KEY at glyph sequence OFFSET.\n *\n * @param offset\n * offset (index) into glyph sequence\n * @param key\n * predication key\n * @return predication KEY at OFFSET or null if none exists\n */\n public Object getPredication(int offset, String key) {\n if (predications) {\n CharAssociation[] aa = getAssociations(offset, 1);\n CharAssociation ca = aa[0];\n return ca.getPredication(key);\n } else {\n return null;\n }\n }\n\n /**\n * Compare glyphs.\n *\n * @param gb\n * buffer containing glyph indices with which this glyph sequence's glyphs are to be compared\n * @return zero if glyphs are the same, otherwise returns 1 or -1 according to whether this glyph sequence's\n * glyphs are lexicographically greater or lesser than the glyphs in the specified string buffer\n */\n public int compareGlyphs(IntBuffer gb) {\n int ng = getGlyphCount();\n for (int i = 0, n = gb.limit(); i < n; i++) {\n if (i < ng) {\n int g1 = glyphs.get(i);\n int g2 = gb.get(i);\n if (g1 > g2) {\n return 1;\n } else if (g1 < g2) {\n return -1;\n }\n } else {\n return -1; // this gb is a proper prefix of specified gb\n }\n }\n return 0; // same lengths with no difference\n }\n\n /** {@inheritDoc} */\n public Object clone() {\n try {\n GlyphSequence gs = (GlyphSequence) super.clone();\n gs.characters = copyBuffer(characters);\n gs.glyphs = copyBuffer(glyphs);\n gs.associations = copyAssociations(associations);\n return gs;\n } catch (CloneNotSupportedException e) {\n return null;\n }\n }\n\n /** {@inheritDoc} */\n public String toString() {\n StringBuffer sb = new StringBuffer();\n sb.append('{');\n sb.append(\"chars = [\");\n sb.append(characters);\n sb.append(\"], glyphs = [\");\n sb.append(glyphs);\n sb.append(\"], associations = [\");\n sb.append(associations);\n sb.append(\"]\");\n sb.append('}');\n return sb.toString();\n }\n\n /**\n * Determine if two arrays of glyphs are identical.\n *\n * @param ga1\n * first glyph array\n * @param ga2\n * second glyph array\n * @return true if arrays are botth null or both non-null and have identical elements\n */\n public static boolean sameGlyphs(int[] ga1, int[] ga2) {\n if (ga1 == ga2) {\n return true;\n } else if ((ga1 == null) || (ga2 == null)) {\n return false;\n } else if (ga1.length != ga2.length) {\n return false;\n } else {\n for (int i = 0, n = ga1.length; i < n; i++) {\n if (ga1[i] != ga2[i]) {\n return false;\n }\n }\n return true;\n }\n }\n\n /**\n * Concatenante glyph arrays.\n *\n * @param bga\n * backtrack glyph array\n * @param iga\n * input glyph array\n * @param lga\n * lookahead glyph array\n * @return new integer buffer containing concatenated glyphs\n */\n public static IntBuffer concatGlyphs(int[] bga, int[] iga, int[] lga) {\n int ng = 0;\n if (bga != null) {\n ng += bga.length;\n }\n if (iga != null) {\n ng += iga.length;\n }\n if (lga != null) {\n ng += lga.length;\n }\n IntBuffer gb = IntBuffer.allocate(ng);\n if (bga != null) {\n gb.put(bga);\n }\n if (iga != null) {\n gb.put(iga);\n }\n if (lga != null) {\n gb.put(lga);\n }\n gb.flip();\n return gb;\n }\n\n /**\n * Concatenante association arrays.\n *\n * @param baa\n * backtrack association array\n * @param iaa\n * input association array\n * @param laa\n * lookahead association array\n * @return new list containing concatenated associations\n */\n public static List concatAssociations(CharAssociation[] baa, CharAssociation[] iaa, CharAssociation[] laa) {\n int na = 0;\n if (baa != null) {\n na += baa.length;\n }\n if (iaa != null) {\n na += iaa.length;\n }\n if (laa != null) {\n na += laa.length;\n }\n if (na > 0) {\n List gl = new ArrayList(na);\n if (baa != null) {\n for (int i = 0; i < baa.length; i++) {\n gl.add(baa[i]);\n }\n }\n if (iaa != null) {\n for (int i = 0; i < iaa.length; i++) {\n gl.add(iaa[i]);\n }\n }\n if (laa != null) {\n for (int i = 0; i < laa.length; i++) {\n gl.add(laa[i]);\n }\n }\n return gl;\n } else {\n return null;\n }\n }\n\n /**\n * Join (concatenate) glyph sequences.\n *\n * @param gs\n * original glyph sequence from which to reuse character array reference\n * @param sa\n * array of glyph sequences, whose glyph arrays and association lists are to be concatenated\n * @return new glyph sequence referring to character array of GS and concatenated glyphs and associations of SA\n */\n public static GlyphSequence join(GlyphSequence gs, GlyphSequence[] sa) {\n assert sa != null;\n int tg = 0;\n int ta = 0;\n for (int i = 0, n = sa.length; i < n; i++) {\n GlyphSequence s = sa[i];\n IntBuffer ga = s.getGlyphs();\n assert ga != null;\n int ng = ga.limit();\n List al = s.getAssociations();\n assert al != null;\n int na = al.size();\n assert na == ng;\n tg += ng;\n ta += na;\n }\n IntBuffer uga = IntBuffer.allocate(tg);\n ArrayList ual = new ArrayList(ta);\n for (int i = 0, n = sa.length; i < n; i++) {\n GlyphSequence s = sa[i];\n uga.put(s.getGlyphs());\n ual.addAll(s.getAssociations());\n }\n return new GlyphSequence(gs.getCharacters(), uga, ual, gs.getPredications());\n }\n\n /**\n * Reorder sequence such that [SOURCE,SOURCE+COUNT) is moved just prior to TARGET.\n *\n * @param gs\n * input sequence\n * @param source\n * index of sub-sequence to reorder\n * @param count\n * length of sub-sequence to reorder\n * @param target\n * index to which source sub-sequence is to be moved\n * @return reordered sequence (or original if no reordering performed)\n */\n public static GlyphSequence reorder(GlyphSequence gs, int source, int count, int target) {\n if (source != target) {\n int ng = gs.getGlyphCount();\n int[] ga = gs.getGlyphArray(false);\n int[] nga = new int[ng];\n CharAssociation[] aa = gs.getAssociations(0, ng);\n CharAssociation[] naa = new CharAssociation[ng];\n if (source < target) {\n int t = 0;\n for (int s = 0, e = source; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = source + count, e = target; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = source, e = source + count; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = target, e = ng; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n } else {\n int t = 0;\n for (int s = 0, e = target; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = source, e = source + count; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = target, e = source; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n for (int s = source + count, e = ng; s < e; s++, t++) {\n nga[t] = ga[s];\n naa[t] = aa[s];\n }\n }\n return new GlyphSequence(gs, null, nga, null, null, naa, null);\n } else {\n return gs;\n }\n }\n\n private static int[] toArray(IntBuffer ib) {\n if (ib != null) {\n int n = ib.limit();\n int[] ia = new int[n];\n ib.get(ia, 0, n);\n return ia;\n } else {\n return new int[0];\n }\n }\n\n private static List makeIdentityAssociations(int numChars, int numGlyphs) {\n int nc = numChars;\n int ng = numGlyphs;\n List av = new ArrayList(ng);\n for (int i = 0, n = ng; i < n; i++) {\n int k = (i > nc) ? nc : i;\n av.add(new CharAssociation(i, (k == nc) ? 0 : 1));\n }\n return av;\n }\n\n private static IntBuffer copyBuffer(IntBuffer ib) {\n if (ib != null) {\n int[] ia = new int[ib.capacity()];\n int p = ib.position();\n int l = ib.limit();\n System.arraycopy(ib.array(), 0, ia, 0, ia.length);\n return IntBuffer.wrap(ia, p, l - p);\n } else {\n return null;\n }\n }\n\n private static List copyAssociations(List ca) {\n if (ca != null) {\n return new ArrayList(ca);\n } else {\n return ca;\n }\n }\n\n}", "public interface ScriptContextTester {\n\n /**\n * Obtain a glyph context tester for the specified feature.\n *\n * @param feature\n * a feature identifier\n * @return a glyph context tester or null if none available for the specified feature\n */\n GlyphContextTester getTester(String feature);\n\n}" ]
import com.jaredrummler.fontreader.fonts.GlyphSubstitutionTable; import com.jaredrummler.fontreader.truetype.GlyphTable; import com.jaredrummler.fontreader.complexscripts.fonts.GlyphDefinitionTable; import com.jaredrummler.fontreader.complexscripts.fonts.GlyphPositioningTable; import com.jaredrummler.fontreader.complexscripts.util.CharScript; import com.jaredrummler.fontreader.util.GlyphSequence; import com.jaredrummler.fontreader.util.ScriptContextTester; import java.util.Arrays; import java.util.HashMap; import java.util.Map;
/* * Copyright (C) 2016 Jared Rummler <[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.jaredrummler.fontreader.complexscripts.scripts; /** * <p>Abstract script processor base class for which an implementation of the substitution and positioning methods * must be supplied.</p> * * <p>This work was originally authored by Glenn Adams ([email protected]).</p> */ public abstract class ScriptProcessor { private final String script; private final Map<AssembledLookupsKey, GlyphTable.UseSpec[]> assembledLookups; private static Map<String, ScriptProcessor> processors = new HashMap<String, ScriptProcessor>(); /** * Instantiate a script processor. * * @param script * a script identifier */ protected ScriptProcessor(String script) { if ((script == null) || (script.length() == 0)) { throw new IllegalArgumentException("script must be non-empty string"); } else { this.script = script; this.assembledLookups = new HashMap<>(); } } /** @return script identifier */ public final String getScript() { return script; } /** * Obtain script specific required substitution features. * * @return array of suppported substitution features or null */ public abstract String[] getSubstitutionFeatures(); /** * Obtain script specific optional substitution features. * * @return array of suppported substitution features or null */ public String[] getOptionalSubstitutionFeatures() { return new String[0]; } /** * Obtain script specific substitution context tester. * * @return substitution context tester or null */ public abstract ScriptContextTester getSubstitutionContextTester(); /** * Perform substitution processing using a specific set of lookup tables. * * @param gsub * the glyph substitution table that applies * @param gs * an input glyph sequence * @param script * a script identifier * @param language * a language identifier * @param lookups * a mapping from lookup specifications to glyph subtables to use for substitution processing * @return the substituted (output) glyph sequence */ public final GlyphSequence substitute(GlyphSubstitutionTable gsub, GlyphSequence gs, String script, String language, Map/*<LookupSpec,List<LookupTable>>>*/ lookups) { return substitute(gs, script, language, assembleLookups(gsub, getSubstitutionFeatures(), lookups), getSubstitutionContextTester()); } /** * Perform substitution processing using a specific set of ordered glyph table use specifications. * * @param gs * an input glyph sequence * @param script * a script identifier * @param language * a language identifier * @param usa * an ordered array of glyph table use specs * @param sct * a script specific context tester (or null) * @return the substituted (output) glyph sequence */ public GlyphSequence substitute(GlyphSequence gs, String script, String language, GlyphTable.UseSpec[] usa, ScriptContextTester sct) { assert usa != null; for (int i = 0, n = usa.length; i < n; i++) { GlyphTable.UseSpec us = usa[i]; gs = us.substitute(gs, script, language, sct); } return gs; } /** * Reorder combining marks in glyph sequence so that they precede (within the sequence) the base * character to which they are applied. N.B. In the case of RTL segments, marks are not reordered by this, * method since when the segment is reversed by BIDI processing, marks are automatically reordered to precede * their base glyph. * * @param gdef * the glyph definition table that applies * @param gs * an input glyph sequence * @param unscaledWidths * associated unscaled advance widths (also reordered) * @param gpa * associated glyph position adjustments (also reordered) * @param script * a script identifier * @param language * a language identifier * @return the reordered (output) glyph sequence */ public GlyphSequence reorderCombiningMarks(GlyphDefinitionTable gdef, GlyphSequence gs, int[] unscaledWidths, int[][] gpa, String script, String language) { return gs; } /** * Obtain script specific required positioning features. * * @return array of suppported positioning features or null */ public abstract String[] getPositioningFeatures(); /** * Obtain script specific optional positioning features. * * @return array of suppported positioning features or null */ public String[] getOptionalPositioningFeatures() { return new String[0]; } /** * Obtain script specific positioning context tester. * * @return positioning context tester or null */ public abstract ScriptContextTester getPositioningContextTester(); /** * Perform positioning processing using a specific set of lookup tables. * * @param gpos * the glyph positioning table that applies * @param gs * an input glyph sequence * @param script * a script identifier * @param language * a language identifier * @param fontSize * size in device units * @param lookups * a mapping from lookup specifications to glyph subtables to use for positioning processing * @param widths * array of default advancements for each glyph * @param adjustments * accumulated adjustments array (sequence) of 4-tuples of placement [PX,PY] and advance [AX,AY] adjustments, in * that order, * with one 4-tuple for each element of glyph sequence * @return true if some adjustment is not zero; otherwise, false */
public final boolean position(GlyphPositioningTable gpos, GlyphSequence gs, String script, String language,
3
SOM-Research/EMFtoCSP
plugins/fr.inria.atlanmod.emftocsp.emf/src/fr/inria/atlanmod/emftocsp/emf/impl/UmlModelBuilder.java
[ "public interface IModelReader<R, P, C, AS, AT, OP> {\n\n\tpublic R getModelResource(); \n\n\tpublic List<P> getPackages();\n\n\tpublic List<C> getClasses();\n\n\tpublic List<String> getClassesNames();\n\n\tpublic List<AT> getClassAttributes(C c);\n\n\tpublic List<OP> getClassOperations(C c); \n\n\tpublic List<C> getClassSubtypes(List<C> classList, C c);\n\t\n\tpublic void getClassSubtypes(List<C> cList, C c, List<C> subTypes);\n\n\tpublic C getBaseClass(C c); \n\n\tpublic List<AS> getAssociations();\n\n\tpublic List<String> getAssociationsNames();\n\n\tpublic String getAssociationName(AS as);\n\n\tpublic String getAssociationEndName(AT asEnd);\n\n\tpublic List<String> getAssociationNamesOfNonAbsClasses();\n\n\tpublic R getResource();\n}", "public class EAttributeUMLAdapter extends EAttributeAdapter<Property> implements EStructuralFeature{\n\n\tprotected Resource owningResource;\n\t\n\tpublic EAttributeUMLAdapter(Property newAttribute, Resource owningResource) {\n\t\tsuper(newAttribute);\n\t\tthis.owningResource=owningResource;\n\t}\n\n\t@Override\n\tpublic int getLowerBound() {\n\t\treturn origAttribute.getLower();\n\t}\n\n\t@Override\n\tpublic int getUpperBound() {\n\t\treturn origAttribute.getUpper();\n\t}\n\n\t@Override\n\tpublic boolean isMany() {\n\t\treturn origAttribute.isMultivalued();\n\t}\n\n\t@Override\n\tpublic EClassifier getEType() {\n\t\treturn ((EResourceUMLAdapter)owningResource).getClassIfNotExists(EDatatypeUtil.convertFromString(origAttribute.getType().getName()));\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn origAttribute.getName();\n\t}\n\n\t@Override\n\tpublic EList<EAnnotation> getEAnnotations() {\n\t\tEList<EAnnotation> result = new BasicEList<EAnnotation>();\n\t\t\tfor (EAnnotation annot : origAttribute.getEAnnotations())\n\t\t\t\tresult.add(new EAnnotationUMLAdapter(annot,owningResource));\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic EAnnotation getEAnnotation(String source) {\n\t\tif (origAttribute.getEAnnotation(source) != null)\n\t\t\treturn new EAnnotationUMLAdapter(origAttribute.getEAnnotation(source),owningResource);\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic EDataType getEAttributeType() {\n\t\tString name = origAttribute.getType().getName();\n\t\treturn (EDataType)EDatatypeUtil.convertFromString(name);\n\t}\n\n\t@Override\n\tpublic EClass getEContainingClass() {\n\t\treturn (EClass) ((EResourceUMLAdapter)owningResource).getClassIfNotExists(new EClassUMLAdapter(origAttribute.getClass_(),owningResource));\n\t}\n\n\t@Override\n\tpublic EObject eContainer() {\n\t\treturn ((EResourceUMLAdapter)owningResource).getClassIfNotExists(new EClassUMLAdapter((Class) origAttribute.eContainer(),owningResource));\n\t\t\n\t}\n\n}", "public class EClassUMLAdapter extends EClassAdapter<Class> implements EClassifier{\n\n\tprotected Resource owningResource;\n\tpublic EClassUMLAdapter(Class newClass, Resource owningResource) {\n\t\tsuper(newClass);\n\t\tthis.owningResource = owningResource;\n\t\t\n\t}\n\n\t@Override\n\tpublic EPackage getEPackage() {\n\t\tAssert.isNotNull(origClass.getPackage(),\"NULL Package\");\n\t\treturn new EPackageUMLAdapter(origClass.getPackage(),owningResource);\n\t}\n\n\n\t@Override\n\tpublic String getName() {\n\t\treturn origClass.getName();\n\t}\n\n\t@Override\n\tpublic EObject eContainer() {\n\t\tif (origClass.eContainer() instanceof Package)\n\t\t\treturn new EPackageUMLAdapter((Package) origClass.eContainer(), owningResource);\n\t\telse if (origClass.eContainer() instanceof Class )\n\t\treturn ((EResourceUMLAdapter)owningResource).getClassIfNotExists(new EClassUMLAdapter((Class) origClass.eContainer(),owningResource));\n\t\ttry {\n\t\t\tthrow new Exception (\"Unhandled Type : \" + origClass.eContainer().eClass());\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t} \n\t\t return origClass.eContainer();\n\t}\n\n\t@Override\n\tpublic EList<EClass> getESuperTypes() {\n\t\tEList<EClass> result = new BasicEList<EClass>();\n\t\t\tfor (Generalization g : origClass.getGeneralizations() ){\n\t\t\t\tif ((Class)g.getGeneral() != origClass) \n\t\t\t\t\tresult.add((EClass)((EResourceUMLAdapter)owningResource).getClassIfNotExists(new EClassUMLAdapter((Class)g.getGeneral(),owningResource)));}\n\t\treturn result ;\n\t}\n\n\t@Override\n\tpublic EList<EClass> getEAllSuperTypes() {\n\t\t//TODO\n\t\tEList<EClass> result = new BasicEList<EClass>();\n\t\tEList<Class> allSuperTypes = new BasicEList<Class>();\n\t\tallSuperTypes(origClass,allSuperTypes);\n\t\tfor (Class cls : allSuperTypes)\n\t\t\tresult.add((EClass)((EResourceUMLAdapter)owningResource).getClassIfNotExists(new EClassUMLAdapter(cls,owningResource)));\n\treturn result ;\n\t}\n\n\tprivate void allSuperTypes(Class cls , EList<Class> allSuperTypes) {\n\t\tif (cls.getSuperClasses().isEmpty()) return;\n\t\tfor (Class clas : cls.getSuperClasses()){\n\t\t\tallSuperTypes.add(clas);\n\t\t\tallSuperTypes(clas, allSuperTypes);\n\t\t}\t\n\t}\n\n\t@Override\n\tpublic EList<EAttribute> getEAttributes() {\n\t\tEList<EAttribute> result = new BasicEList<EAttribute>();\n\t\t\tfor (Property pro : origClass.getAttributes())\n\t\t\t\tresult.add(new EAttributeUMLAdapter(pro,owningResource));\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic EList<EReference> getEReferences() {\n\t\tEList<EReference> result = new BasicEList<EReference>();\n\t\tArrayList<Association> asList = getAssociationListFromPackage(origClass.getPackage());\n\t\tfor (Association ass : asList){\n\t\t\tList<Property> pros = ass.getOwnedEnds();\n\t\t\tfor (Property pro : ass.getOwnedEnds()){\n\t\t\t\tString msg = pro.getOtherEnd().getType() == null ? \"NULL\" : pro.getOtherEnd().getType().toString();\n\t\t\t\tif (pro.getOtherEnd().getType().equals(origClass))\n\t\t\t\t\tresult.add(new EReferenceUMLAdapter(pro,owningResource));\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate ArrayList<Association> getAssociationListFromPackage(Package p) {\n\t\t ArrayList<Association> asList = new ArrayList<Association>();\n\t\t for (PackageableElement pkgElement : p.getPackagedElements()) \n\t\t if (pkgElement instanceof Association) \n\t\t asList.add((Association)pkgElement);\n\t\t return asList;\n\t\t }\n\t \n\t@SuppressWarnings(\"unused\")\n\tprivate List<Property> getReferences() {\n\t\tList <Property> result = new ArrayList<Property>(); \n\t\tEList<Association> associations = origClass.getAssociations();\n\t\tfor (Association association : associations)\n\t\t\tresult.addAll(association.getOwnedEnds());\n\t\treturn result;\n\t}\n\n\n\t@Override\n\tpublic EList<EOperation> getEOperations() {\n\t\tEList<EOperation> result = new BasicEList<EOperation>();\n\t\t\tfor (Operation operation : origClass.getOperations()){\n\t\t\t\tif (operation != null)\n\t\t\t\t\tresult.add(new EOperationUMLAdapter(operation,owningResource));}\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic EList<EOperation> getEAllOperations() {\n\t\tEList<EOperation> result = new BasicEList<EOperation>();\n\t\tfor (Operation operation : origClass.getAllOperations())\n\t\t\tresult.add(new EOperationUMLAdapter(operation,owningResource));\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic EList<EAnnotation> getEAnnotations() {\n\t\tEList<EAnnotation> result = new BasicEList<EAnnotation>();\n\t\t\tfor (EAnnotation annot : origClass.getEAnnotations())\n\t\t\t\tresult.add(new EAnnotationUMLAdapter(annot,owningResource));\n\t\treturn result;\n\t}\n\n\tpublic EAnnotation getEAnnotation(String source) {\n\t\tif (origClass.getEAnnotation(source) != null)\n\t\t\treturn new EAnnotationUMLAdapter(origClass.getEAnnotation(source),owningResource);\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean isAbstract() {\n\t\treturn origClass.isAbstract();\n\t}\n\n\t@Override\n\tpublic EClass eClass() {\n\t\treturn EcorePackage.eINSTANCE.getEClass();\n\t}\n\n\t@Override\n\tpublic EList<EStructuralFeature> getEStructuralFeatures() {\n\t\tEList<EStructuralFeature> result = new BasicEList<EStructuralFeature>();\n\t\tresult.addAll(getEAttributes());\n\t\tresult.addAll(getEReferences());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic EList<EStructuralFeature> getEAllStructuralFeatures() {\n\t\tEList<EStructuralFeature> result = new BasicEList<EStructuralFeature>();\n\t\tresult.addAll(getEStructuralFeatures());\n\t\tfor (EClass cls : getESuperTypes())\n\t\t\tresult.addAll(cls.getEAllStructuralFeatures());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic EList<EReference> getEAllReferences() {\n\t\tEList<EReference> result = new BasicEList<EReference>();\n\t\tresult.addAll(getEReferences());\n\t\tfor (EClass cls : getESuperTypes())\n\t\t\tresult.addAll(cls.getEAllReferences());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic EList<EReference> getEAllContainments() {\n\t\tEList<EReference> result = new BasicEList<EReference>();\n\t\tfor (EReference ref : getEAllReferences())\n\t\t\tif (ref.isContainment())\n\t\t\t\tresult.add(ref);\n\t\treturn result;\t\t\t\t\n\t}\n\n\t@Override\n\tpublic EList<EAttribute> getEAllAttributes() {\n\t\tEList<EAttribute> result = new BasicEList<EAttribute>();\n\t\tresult.addAll(getEAttributes());\n\t\tfor (EClass cls : getESuperTypes())\n\t\t\tresult.addAll(cls.getEAllAttributes());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean isSuperTypeOf(EClass someClass) {\n\t\tfor (Generalization gen : origClass.getGeneralizations())\n\t\t\tif (gen.getGeneral().getName().equalsIgnoreCase(origClass.getName()))\t\t\t\t\n\t\t\t\tif (((EResourceUMLAdapter)owningResource).\n\t\t\t\t\t\tgetClassIfNotExists(new EClassUMLAdapter((Class)gen\n\t\t\t\t\t\t\t\t.getSpecific(),owningResource)).equals(someClass))\n\t\t\t\t\treturn true;\t\t\t\t\t\t\t\n\t\treturn false;\n\n\t}\n\n\tpublic Class getOriginalClass() {\n\t\treturn origClass;\n\t}\n}", "public class EReferenceUMLAdapter extends EReferenceAdapter<Property> implements EStructuralFeature {\n\n\tprotected Resource owningResource;\n\tpublic EReferenceUMLAdapter(Property newResource, Resource owningResource) {\n\t\tsuper(newResource);\n\t\tthis.owningResource = owningResource;\n\t}\n\n\t@Override\n\tpublic EClass getEContainingClass() {\t\n\t\t\treturn (EClass) getEOpposite().getEType();\n\t}\n\n\t@Override\n\tpublic int getLowerBound() {\n\t\treturn origEReference.getLower();\n\t}\n\n\t@Override\n\tpublic int getUpperBound() {\n\t\treturn origEReference.getUpper();\n\t}\n\n\t@Override\n\tpublic boolean isMany() {\n\t\treturn origEReference.isMultivalued();\n\t}\n\n\t@Override\n\tpublic EClassifier getEType() {\n\t\t//TODO\n\t\treturn (EClass) ((EResourceUMLAdapter)owningResource).getClassIfNotExists( new EClassUMLAdapter((Class)origEReference.getType(),owningResource));\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn origEReference.getName();\n\t}\n\n\t@Override\n\tpublic EList<EAnnotation> getEAnnotations() {\n\t\tEList<EAnnotation> result = new BasicEList<EAnnotation>();\n\t\t\tfor (EAnnotation annot : origEReference.getEAnnotations())\n\t\t\t\tresult.add(new EAnnotationUMLAdapter(annot,owningResource));\n\t\treturn result;\n\t}\n\n\tpublic EAnnotation getEAnnotation(String source) {\n\t\tif (origEReference.getEAnnotation(source) != null)\n\t\t\treturn new EAnnotationUMLAdapter(origEReference.getEAnnotation(source),owningResource);\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic EObject eContainer() {\n\t\treturn origEReference.eContainer();\n\t}\n\n\t@Override\n\tpublic boolean isContainment() {\n\t\treturn origEReference.getAggregation().getLiteral().equals(AggregationKind.COMPOSITE_LITERAL.getLiteral());\n\t}\n\n\t@Override\n\tpublic boolean isContainer() {\n\t\tif (getEOpposite()== null) return false;\n\t\treturn getEOpposite().isContainment();\n\t}\n\n\t@Override\n\tpublic EReference getEOpposite() {\n\t\tProperty otherEnd = origEReference.getOtherEnd();\n\t\tif (origEReference.getOtherEnd()!= null )\n\t\t\treturn new EReferenceUMLAdapter(origEReference.getOtherEnd(),owningResource);\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic EClass getEReferenceType() {\n\t\treturn (EClass)((EResourceUMLAdapter)owningResource).getClassIfNotExists(new EClassUMLAdapter((Class)origEReference.getType(),owningResource));\n\t}\n\n\t@Override\n\tpublic boolean isOrdered() {\n\t\treturn origEReference.isOrdered();\n\t}\n\n\t@Override\n\tpublic boolean isUnique() {\n\t\treturn origEReference.isUnique();\n\t}\n\n\t@Override\n\tpublic boolean isRequired() {\n\t\treturn isRequired();\n\t}\n\n\n\n}", "public class AssocStruct extends Struct {\n\n\tpublic AssocStruct(CompoundTerm cp, String functor) {\n\t\tsuper(functor);\n\t\t// TODO Auto-generated constructor stub\n\t\tsrcOid=(Integer) cp.arg(1);\n\t\ttrgOid=(Integer) cp.arg(2);\n\t}\n\tprivate int srcOid;\n\tprivate int trgOid;\n\t@Override\n\tpublic String toString() {\n\t\treturn \"AssocStruct [srcOid=\" + srcOid + \", trgOid=\" + trgOid + \"]\";\n\t}\n\tpublic int getSrcOid() {\n\t\treturn srcOid;\n\t}\n\tpublic void setSrcOid(int srcOid) {\n\t\tthis.srcOid = srcOid;\n\t}\n\tpublic int getTrgOid() {\n\t\treturn trgOid;\n\t}\n\tpublic void setTrgOid(int trgOid) {\n\t\tthis.trgOid = trgOid;\n\t}\n\t\n\t\n}", "public class Field {\n\n\tprivate Object value;\n\tprivate int index;\n\tpublic Field(Object arg, int i) {\n\t\tvalue =arg;\n\t\tindex=i;\n\t}\n\tpublic Object getValue() {\n\t\treturn value;\n\t}\n\tpublic int getIndex() {\n\t\treturn index;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Field [value=\" + value + \", index=\" + index + \"type\"+ value.getClass()+\"]\";\n\t}\n\t\n}", "public class ObjectStruct extends Struct {\n\t\n\tprivate List<Field> fields;\n\t\n\tpublic List<Field> getFields() {\n\t\treturn fields;\n\t}\n\n\n\tpublic void setFields(List<Field> fields) {\n\t\tthis.fields = fields;\n\t}\n\n\n\tpublic ObjectStruct(CompoundTerm cp, String functor) {\n\t\tsuper(functor);\n\t\t// TODO Auto-generated constructor stub\n\t\tfields = new LinkedList<Field>();\n\t\tfor (int i=1; i<= cp.arity(); i++)\n\t\t\tfields.add(new Field(cp.arg(i),i));\n\t}\n\n\n\tpublic int getOid(){\n\t\treturn (Integer) fields.get(0).getValue() ;\n\t\t\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ObjectStruct [fields=\" + fields + \"]\";\n\t}\n}", "public class Point {\n\t\n\tprivate int x;\n\tprivate int y;\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + x;\n\t\tresult = prime * result + y;\n\t\treturn result;\n\t}\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tPoint other = (Point) obj;\n\t\tif (x != other.x)\n\t\t\treturn false;\n\t\tif (y != other.y)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\tpublic int getX() {\n\t\treturn x;\n\t}\n\tpublic void setX(int x) {\n\t\tthis.x = x;\n\t}\n\tpublic int getY() {\n\t\treturn y;\n\t}\n\tpublic void setY(int y) {\n\t\tthis.y = y;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Point [x=\" + x + \", y=\" + y + \"]\";\n\t}\n\tpublic Point(int x, int y) {\n\t\tsuper();\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\t\n\n}" ]
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.Assert; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EOperation; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.uml2.uml.Association; import org.eclipse.uml2.uml.Class; import org.eclipse.uml2.uml.Property; import org.eclipse.uml2.uml.UMLFactory; import org.eclipse.uml2.uml.UMLPackage; import org.eclipse.uml2.uml.resource.UMLResource; import org.eclipse.uml2.uml.resources.util.UMLResourcesUtil; import com.parctechnologies.eclipse.CompoundTerm; import fr.inria.atlanmod.emftocsp.IModelReader; import fr.inria.atlanmod.emftocsp.adapters.umlImpl.EAttributeUMLAdapter; import fr.inria.atlanmod.emftocsp.adapters.umlImpl.EClassUMLAdapter; import fr.inria.atlanmod.emftocsp.adapters.umlImpl.EReferenceUMLAdapter; import fr.inria.atlanmod.emftocsp.modelbuilder.AssocStruct; import fr.inria.atlanmod.emftocsp.modelbuilder.Field; import fr.inria.atlanmod.emftocsp.modelbuilder.ObjectStruct; import fr.inria.atlanmod.emftocsp.modelbuilder.Point;
/******************************************************************************* * Copyright (c) 2013 INRIA Rennes Bretagne-Atlantique. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * INRIA Rennes Bretagne-Atlantique - initial API and implementation *******************************************************************************/ package fr.inria.atlanmod.emftocsp.emf.impl; /** * @author <a href="mailto:[email protected]">Amine Benelallam</a> * */ public class UmlModelBuilder extends EmfModelBuilder{ public UmlModelBuilder() { }
public UmlModelBuilder(IModelReader<Resource, EPackage, EClass, EAssociation, EAttribute, EOperation> modelReader, CompoundTerm ct){
0
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java
[ "@ExtendWith(SpringExtension.class)\n@TestPropertySource(locations = \"classpath:test.properties\")\n@Import({BeansFactory.class})\npublic abstract class AbstractTestRunner {\n\n protected Task task;\n protected People people;\n\n protected void initializeData() {\n task = new Task();\n task.setTaskArchived(true);\n task.setTaskName(\"name\");\n task.setTaskDescription(\"description\");\n task.setTaskPriority(\"LOW\");\n task.setTaskStatus(\"ACTIVE\");\n\n people = new People()\n .setName(\"john\")\n .setTask(task);\n }\n\n protected String serializeToJson(Object object) throws JsonProcessingException {\n return new ObjectMapper().writeValueAsString(object);\n }\n}", "public class Account implements AccountInterface {\n\n public String firstName;\n public String lastName;\n}", "public class AccountDecorator implements AccountInterface {\n\n @JsonUnwrapped\n public Account account;\n public Context context;\n\n public AccountDecorator() {\n }\n\n public AccountDecorator(Account account) {\n this.account = account;\n }\n}", "public class Context {\n\n public String ref;\n\n}", "public final class MediaType extends org.springframework.http.MediaType {\n\n public static final org.springframework.http.MediaType APPLICATION_VND_API_V1;\n public static final String APPLICATION_VND_API_V1_VALUE = \"application/vnd.api.v1+json;charset=UTF-8\";\n\n public static final org.springframework.http.MediaType APPLICATION_VND_API_V2;\n public static final String APPLICATION_VND_API_V2_VALUE = \"application/vnd.api.v2+json;charset=UTF-8\";\n\n private MediaType(String type) {\n super(type);\n }\n\n static {\n var applicationType = \"application\";\n APPLICATION_VND_API_V1 = new org.springframework.http.MediaType(applicationType, \"vnd.api.v1+json\", StandardCharsets.UTF_8);\n APPLICATION_VND_API_V2 = new org.springframework.http.MediaType(applicationType, \"vnd.api.v2+json\", StandardCharsets.UTF_8);\n }\n}", "public class ToSerialize implements Cloneable {\n\n public String prop1;\n public String prop2;\n\n @Override\n public ToSerialize clone() throws CloneNotSupportedException {\n return (ToSerialize) super.clone();\n }\n}" ]
import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
/* * 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.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase
class MiscControllerTest extends AbstractTestRunner {
0
DigiArea/es5-model
com.digiarea.es5/src/com/digiarea/es5/FunctionDeclaration.java
[ "public abstract class Statement extends Node {\r\n\r\n Statement() {\r\n super();\r\n }\r\n\r\n Statement(JSDocComment jsDocComment, int posBegin, int posEnd) {\r\n super(jsDocComment, posBegin, posEnd);\r\n }\r\n\r\n}\r", "public class Parameter extends Expression {\r\n\r\n /** \r\n * The name.\r\n */\r\n private String name;\r\n\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n public void setName(String name) {\r\n this.name = name;\r\n }\r\n\r\n Parameter() {\r\n super();\r\n }\r\n\r\n Parameter(String name, JSDocComment jsDocComment, int posBegin, int posEnd) {\r\n super(jsDocComment, posBegin, posEnd);\r\n this.name = name;\r\n }\r\n\r\n @Override\r\n public <C> void accept(VoidVisitor<C> v, C ctx) throws Exception {\r\n v.visit(this, ctx);\r\n }\r\n\r\n @Override\r\n public <R, C> R accept(GenericVisitor<R, C> v, C ctx) throws Exception {\r\n return v.visit(this, ctx);\r\n }\r\n\r\n}\r", "public class NodeList<E extends Node> extends Node implements List<E> {\r\n\r\n /** \r\n * The nodes.\r\n */\r\n private List<E> nodes = null;\r\n\r\n public Iterator<E> iterator() {\r\n if (nodes != null) {\r\n return nodes.iterator();\r\n }\r\n return null;\r\n }\r\n\r\n public int size() {\r\n return nodes.size();\r\n }\r\n\r\n public boolean isEmpty() {\r\n return nodes.isEmpty();\r\n }\r\n\r\n public boolean contains(Object o) {\r\n return nodes.contains(o);\r\n }\r\n\r\n public Object[] toArray() {\r\n return nodes.toArray();\r\n }\r\n\r\n public <T> T[] toArray(T[] a) {\r\n return nodes.toArray(a);\r\n }\r\n\r\n public boolean add(E e) {\r\n return nodes.add(e);\r\n }\r\n\r\n public boolean remove(Object o) {\r\n return nodes.remove(o);\r\n }\r\n\r\n public boolean containsAll(Collection<?> c) {\r\n return nodes.containsAll(c);\r\n }\r\n\r\n public boolean addAll(Collection<? extends E> c) {\r\n return nodes.addAll(c);\r\n }\r\n\r\n public boolean addAll(int index, Collection<? extends E> c) {\r\n return nodes.addAll(index, c);\r\n }\r\n\r\n public boolean removeAll(Collection<?> c) {\r\n return nodes.removeAll(c);\r\n }\r\n\r\n public boolean retainAll(Collection<?> c) {\r\n return nodes.retainAll(c);\r\n }\r\n\r\n public void clear() {\r\n nodes.clear();\r\n }\r\n\r\n public E get(int index) {\r\n return nodes.get(index);\r\n }\r\n\r\n public E set(int index, E element) {\r\n return nodes.set(index, element);\r\n }\r\n\r\n public void add(int index, E element) {\r\n nodes.add(index, element);\r\n }\r\n\r\n public E remove(int index) {\r\n return nodes.remove(index);\r\n }\r\n\r\n public int indexOf(Object o) {\r\n return nodes.indexOf(o);\r\n }\r\n\r\n public int lastIndexOf(Object o) {\r\n return nodes.lastIndexOf(o);\r\n }\r\n\r\n public ListIterator<E> listIterator() {\r\n return nodes.listIterator();\r\n }\r\n\r\n public ListIterator<E> listIterator(int index) {\r\n return nodes.listIterator(index);\r\n }\r\n\r\n public List<E> subList(int fromIndex, int toIndex) {\r\n return nodes.subList(fromIndex, toIndex);\r\n }\r\n\r\n public boolean addNodes(E nodes) {\r\n boolean res = getNodes().add(nodes);\r\n if (res) {\r\n }\r\n return res;\r\n }\r\n\r\n public boolean removeNodes(E nodes) {\r\n boolean res = getNodes().remove(nodes);\r\n if (res) {\r\n }\r\n return res;\r\n }\r\n\r\n public List<E> getNodes() {\r\n return nodes;\r\n }\r\n\r\n public void setNodes(List<E> nodes) {\r\n this.nodes = nodes;\r\n }\r\n\r\n NodeList() {\r\n super();\r\n }\r\n\r\n NodeList(List<E> nodes, JSDocComment jsDocComment, int posBegin, int posEnd) {\r\n super(jsDocComment, posBegin, posEnd);\r\n this.nodes = nodes;\r\n }\r\n\r\n @Override\r\n public <C> void accept(VoidVisitor<C> v, C ctx) throws Exception {\r\n v.visit(this, ctx);\r\n }\r\n\r\n @Override\r\n public <R, C> R accept(GenericVisitor<R, C> v, C ctx) throws Exception {\r\n return v.visit(this, ctx);\r\n }\r\n\r\n}\r", "public final class Block extends Statement {\r\n\r\n /** \r\n * The statements.\r\n */\r\n private NodeList<Statement> statements;\r\n\r\n public NodeList<Statement> getStatements() {\r\n return statements;\r\n }\r\n\r\n public void setStatements(NodeList<Statement> statements) {\r\n this.statements = statements;\r\n }\r\n\r\n Block() {\r\n super();\r\n }\r\n\r\n Block(NodeList<Statement> statements, JSDocComment jsDocComment, int posBegin, int posEnd) {\r\n super(jsDocComment, posBegin, posEnd);\r\n this.statements = statements;\r\n }\r\n\r\n @Override\r\n public <C> void accept(VoidVisitor<C> v, C ctx) throws Exception {\r\n v.visit(this, ctx);\r\n }\r\n\r\n @Override\r\n public <R, C> R accept(GenericVisitor<R, C> v, C ctx) throws Exception {\r\n return v.visit(this, ctx);\r\n }\r\n\r\n}\r", "public final class JSDocComment extends Comment {\r\n\r\n JSDocComment() {\r\n super();\r\n }\r\n\r\n JSDocComment(String content, JSDocComment jsDocComment, int posBegin, int posEnd) {\r\n super(content, jsDocComment, posBegin, posEnd);\r\n }\r\n\r\n @Override\r\n public <C> void accept(VoidVisitor<C> v, C ctx) throws Exception {\r\n v.visit(this, ctx);\r\n }\r\n\r\n @Override\r\n public <R, C> R accept(GenericVisitor<R, C> v, C ctx) throws Exception {\r\n return v.visit(this, ctx);\r\n }\r\n\r\n}\r", "public interface VoidVisitor<C> {\r\n\r\n public void visit(AllocationExpression n, C ctx) throws Exception;\r\n\r\n public void visit(ArrayAccessExpression n, C ctx) throws Exception;\r\n\r\n public void visit(ArrayLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(AssignmentExpression n, C ctx) throws Exception;\r\n\r\n public void visit(AssignOperator n, C ctx) throws Exception;\r\n\r\n public void visit(BinaryExpression n, C ctx) throws Exception;\r\n\r\n public void visit(BinaryOperator n, C ctx) throws Exception;\r\n\r\n public void visit(Block n, C ctx) throws Exception;\r\n\r\n public void visit(BlockComment n, C ctx) throws Exception;\r\n\r\n public void visit(BooleanLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(BreakStatement n, C ctx) throws Exception;\r\n\r\n public void visit(CallExpression n, C ctx) throws Exception;\r\n\r\n public void visit(CaseBlock n, C ctx) throws Exception;\r\n\r\n public void visit(CaseClause n, C ctx) throws Exception;\r\n\r\n public void visit(CatchClause n, C ctx) throws Exception;\r\n\r\n public void visit(CompilationUnit n, C ctx) throws Exception;\r\n\r\n public void visit(ConditionalExpression n, C ctx) throws Exception;\r\n\r\n public void visit(ConstantStatement n, C ctx) throws Exception;\r\n\r\n public void visit(ContinueStatement n, C ctx) throws Exception;\r\n\r\n public void visit(DebuggerStatement n, C ctx) throws Exception;\r\n\r\n public void visit(DecimalLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(DefaultClause n, C ctx) throws Exception;\r\n\r\n public void visit(DoWhileStatement n, C ctx) throws Exception;\r\n\r\n public void visit(EmptyLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(EmptyStatement n, C ctx) throws Exception;\r\n\r\n public void visit(EnclosedExpression n, C ctx) throws Exception;\r\n\r\n public void visit(ExpressionStatement n, C ctx) throws Exception;\r\n\r\n public void visit(FieldAccessExpression n, C ctx) throws Exception;\r\n\r\n public void visit(FloatLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(ForeachStatement n, C ctx) throws Exception;\r\n\r\n public void visit(ForStatement n, C ctx) throws Exception;\r\n\r\n public void visit(FunctionDeclaration n, C ctx) throws Exception;\r\n\r\n public void visit(FunctionExpression n, C ctx) throws Exception;\r\n\r\n public void visit(GetAssignment n, C ctx) throws Exception;\r\n\r\n public void visit(HexIntegerLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(IdentifierName n, C ctx) throws Exception;\r\n\r\n public void visit(IfStatement n, C ctx) throws Exception;\r\n\r\n public void visit(ImportStatement n, C ctx) throws Exception;\r\n\r\n public void visit(JSDocComment n, C ctx) throws Exception;\r\n\r\n public void visit(LabelledStatement n, C ctx) throws Exception;\r\n\r\n public void visit(LetDefinition n, C ctx) throws Exception;\r\n\r\n public void visit(LetExpression n, C ctx) throws Exception;\r\n\r\n public void visit(LetStatement n, C ctx) throws Exception;\r\n\r\n public void visit(LineComment n, C ctx) throws Exception;\r\n\r\n public void visit(NewExpression n, C ctx) throws Exception;\r\n\r\n public <E extends Node> void visit(NodeList<E> n, C ctx) throws Exception;\r\n\r\n public void visit(NullLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(ObjectLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(OctalLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(Parameter n, C ctx) throws Exception;\r\n\r\n public void visit(Project n, C ctx) throws Exception;\r\n\r\n public void visit(PutAssignment n, C ctx) throws Exception;\r\n\r\n public void visit(RegexpLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(ReturnStatement n, C ctx) throws Exception;\r\n\r\n public void visit(SequenceExpression n, C ctx) throws Exception;\r\n\r\n public void visit(SetAssignment n, C ctx) throws Exception;\r\n\r\n public void visit(StringLiteralDouble n, C ctx) throws Exception;\r\n\r\n public void visit(StringLiteralSingle n, C ctx) throws Exception;\r\n\r\n public void visit(SuperExpression n, C ctx) throws Exception;\r\n\r\n public void visit(SwitchStatement n, C ctx) throws Exception;\r\n\r\n public void visit(ThisExpression n, C ctx) throws Exception;\r\n\r\n public void visit(ThrowStatement n, C ctx) throws Exception;\r\n\r\n public void visit(TryStatement n, C ctx) throws Exception;\r\n\r\n public void visit(UnaryExpression n, C ctx) throws Exception;\r\n\r\n public void visit(UnaryOperator n, C ctx) throws Exception;\r\n\r\n public void visit(VariableDeclaration n, C ctx) throws Exception;\r\n\r\n public void visit(VariableExpression n, C ctx) throws Exception;\r\n\r\n public void visit(VariableStatement n, C ctx) throws Exception;\r\n\r\n public void visit(WhileStatement n, C ctx) throws Exception;\r\n\r\n public void visit(WithStatement n, C ctx) throws Exception;\r\n\r\n}\r", "public interface GenericVisitor<R, C> {\r\n\r\n public R visit(AllocationExpression n, C ctx) throws Exception;\r\n\r\n public R visit(ArrayAccessExpression n, C ctx) throws Exception;\r\n\r\n public R visit(ArrayLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(AssignmentExpression n, C ctx) throws Exception;\r\n\r\n public R visit(AssignOperator n, C ctx) throws Exception;\r\n\r\n public R visit(BinaryExpression n, C ctx) throws Exception;\r\n\r\n public R visit(BinaryOperator n, C ctx) throws Exception;\r\n\r\n public R visit(Block n, C ctx) throws Exception;\r\n\r\n public R visit(BlockComment n, C ctx) throws Exception;\r\n\r\n public R visit(BooleanLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(BreakStatement n, C ctx) throws Exception;\r\n\r\n public R visit(CallExpression n, C ctx) throws Exception;\r\n\r\n public R visit(CaseBlock n, C ctx) throws Exception;\r\n\r\n public R visit(CaseClause n, C ctx) throws Exception;\r\n\r\n public R visit(CatchClause n, C ctx) throws Exception;\r\n\r\n public R visit(CompilationUnit n, C ctx) throws Exception;\r\n\r\n public R visit(ConditionalExpression n, C ctx) throws Exception;\r\n\r\n public R visit(ConstantStatement n, C ctx) throws Exception;\r\n\r\n public R visit(ContinueStatement n, C ctx) throws Exception;\r\n\r\n public R visit(DebuggerStatement n, C ctx) throws Exception;\r\n\r\n public R visit(DecimalLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(DefaultClause n, C ctx) throws Exception;\r\n\r\n public R visit(DoWhileStatement n, C ctx) throws Exception;\r\n\r\n public R visit(EmptyLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(EmptyStatement n, C ctx) throws Exception;\r\n\r\n public R visit(EnclosedExpression n, C ctx) throws Exception;\r\n\r\n public R visit(ExpressionStatement n, C ctx) throws Exception;\r\n\r\n public R visit(FieldAccessExpression n, C ctx) throws Exception;\r\n\r\n public R visit(FloatLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(ForeachStatement n, C ctx) throws Exception;\r\n\r\n public R visit(ForStatement n, C ctx) throws Exception;\r\n\r\n public R visit(FunctionDeclaration n, C ctx) throws Exception;\r\n\r\n public R visit(FunctionExpression n, C ctx) throws Exception;\r\n\r\n public R visit(GetAssignment n, C ctx) throws Exception;\r\n\r\n public R visit(HexIntegerLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(IdentifierName n, C ctx) throws Exception;\r\n\r\n public R visit(IfStatement n, C ctx) throws Exception;\r\n\r\n public R visit(ImportStatement n, C ctx) throws Exception;\r\n\r\n public R visit(JSDocComment n, C ctx) throws Exception;\r\n\r\n public R visit(LabelledStatement n, C ctx) throws Exception;\r\n\r\n public R visit(LetDefinition n, C ctx) throws Exception;\r\n\r\n public R visit(LetExpression n, C ctx) throws Exception;\r\n\r\n public R visit(LetStatement n, C ctx) throws Exception;\r\n\r\n public R visit(LineComment n, C ctx) throws Exception;\r\n\r\n public R visit(NewExpression n, C ctx) throws Exception;\r\n\r\n public <E extends Node> R visit(NodeList<E> n, C ctx) throws Exception;\r\n\r\n public R visit(NullLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(ObjectLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(OctalLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(Parameter n, C ctx) throws Exception;\r\n\r\n public R visit(Project n, C ctx) throws Exception;\r\n\r\n public R visit(PutAssignment n, C ctx) throws Exception;\r\n\r\n public R visit(RegexpLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(ReturnStatement n, C ctx) throws Exception;\r\n\r\n public R visit(SequenceExpression n, C ctx) throws Exception;\r\n\r\n public R visit(SetAssignment n, C ctx) throws Exception;\r\n\r\n public R visit(StringLiteralDouble n, C ctx) throws Exception;\r\n\r\n public R visit(StringLiteralSingle n, C ctx) throws Exception;\r\n\r\n public R visit(SuperExpression n, C ctx) throws Exception;\r\n\r\n public R visit(SwitchStatement n, C ctx) throws Exception;\r\n\r\n public R visit(ThisExpression n, C ctx) throws Exception;\r\n\r\n public R visit(ThrowStatement n, C ctx) throws Exception;\r\n\r\n public R visit(TryStatement n, C ctx) throws Exception;\r\n\r\n public R visit(UnaryExpression n, C ctx) throws Exception;\r\n\r\n public R visit(UnaryOperator n, C ctx) throws Exception;\r\n\r\n public R visit(VariableDeclaration n, C ctx) throws Exception;\r\n\r\n public R visit(VariableExpression n, C ctx) throws Exception;\r\n\r\n public R visit(VariableStatement n, C ctx) throws Exception;\r\n\r\n public R visit(WhileStatement n, C ctx) throws Exception;\r\n\r\n public R visit(WithStatement n, C ctx) throws Exception;\r\n\r\n}\r" ]
import com.digiarea.es5.Statement; import com.digiarea.es5.Parameter; import com.digiarea.es5.NodeList; import com.digiarea.es5.Block; import com.digiarea.es5.JSDocComment; import com.digiarea.es5.visitor.VoidVisitor; import com.digiarea.es5.visitor.GenericVisitor;
package com.digiarea.es5; /** * The Class FunctionDeclaration. */ public class FunctionDeclaration extends Statement { /** * The name. */ private String name; /** * The parameters. */ private NodeList<Parameter> parameters; /** * The body. */ private Block body; public String getName() { return name; } public void setName(String name) { this.name = name; } public NodeList<Parameter> getParameters() { return parameters; } public void setParameters(NodeList<Parameter> parameters) { this.parameters = parameters; } public Block getBody() { return body; } public void setBody(Block body) { this.body = body; } FunctionDeclaration() { super(); } FunctionDeclaration(String name, NodeList<Parameter> parameters, Block body, JSDocComment jsDocComment, int posBegin, int posEnd) { super(jsDocComment, posBegin, posEnd); this.name = name; this.parameters = parameters; this.body = body; } @Override
public <C> void accept(VoidVisitor<C> v, C ctx) throws Exception {
5
jjhesk/LoyalNativeSlider
library/src/main/java/com/hkm/slider/SliderLayout.java
[ "public interface BaseAnimationInterface {\n\n /**\n * When the current item prepare to start leaving the screen.\n *\n * @param current view\n */\n void onPrepareCurrentItemLeaveScreen(View current);\n\n /**\n * The next item which will be shown in ViewPager/\n *\n * @param next view\n */\n void onPrepareNextItemShowInScreen(View next);\n\n /**\n * Current item totally disappear from screen.\n *\n * @param view view\n */\n void onCurrentItemDisappear(View view);\n\n /**\n * Next item totally show in screen.\n *\n * @param view view\n */\n void onNextItemAppear(View view);\n}", "public class NumContainer<customText extends TextView> implements IContainer, ViewPagerEx.OnPageChangeListener {\n protected int mTotalSlides, mCurrentSlide;\n private ViewPagerEx mPager;\n protected RelativeLayout mContainer;\n protected View mWrapper;\n protected customText tv;\n protected boolean isInfinite = false;\n protected Context mContext;\n\n /**\n * This method will be invoked when the current page is scrolled, either as part\n * of a programmatically initiated smooth scroll or a user initiated touch scroll.\n *\n * @param position Position index of the first page currently being displayed.\n * Page position+1 will be visible if positionOffset is nonzero.\n * @param positionOffset Value from [0, 1) indicating the offset from the page at position.\n * @param positionOffsetPixels Value in pixels indicating the offset from position.\n */\n @Override\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n if (mTotalSlides == 0) {\n return;\n }\n int n = position % mTotalSlides + 1;\n update(mCurrentSlide = n, mTotalSlides);\n\n }\n\n /**\n * This method will be invoked when a new page becomes selected. Animation is not\n * necessarily complete.\n *\n * @param position Position index of the new selected page.\n */\n @Override\n public void onPageSelected(int position) {\n\n }\n\n /**\n * Called when the scroll state changes. Useful for discovering when the user\n * begins dragging, when the pager is automatically settling to the current page,\n * or when it is fully stopped/idle.\n *\n * @param state The new scroll state.\n * @see ViewPagerEx#SCROLL_STATE_IDLE\n * @see ViewPagerEx#SCROLL_STATE_DRAGGING\n * @see ViewPagerEx#SCROLL_STATE_SETTLING\n */\n @Override\n public void onPageScrollStateChanged(int state) {\n\n }\n\n\n @Override\n public int getResLayout() {\n return R.layout.default_num_layout;\n }\n\n @Override\n public int getTextField() {\n return R.id.ns_number_holder;\n }\n\n\n public NumContainer(Context c) {\n mContext = c;\n setCustomLayoutForCustomAttachDisplay(getResLayout());\n }\n\n public NumContainer(Context c, @LayoutRes int mLayout) {\n this(c);\n setCustomLayoutForCustomAttachDisplay(mLayout);\n }\n\n public NumContainer setCustomLayoutForCustomAttachDisplay(@LayoutRes int mLayout) {\n mWrapper = LayoutInflater.from(mContext).inflate(mLayout, null, false);\n tv = (customText) mWrapper.findViewById(getTextField());\n return this;\n }\n\n\n public NumContainer 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 return this;\n }\n\n public NumContainer withView(RelativeLayout mContainer) {\n this.mContainer = mContainer;\n return this;\n }\n\n public void build() {\n if (mContainer == null) {\n throw new NullPointerException(\"Container is not an instance\");\n }\n mContainer.removeAllViews();\n mContainer.addView(mWrapper);\n }\n\n\n private DataSetObserver dataChangeObserver = new DataSetObserver() {\n @Override\n public void onChanged() {\n PagerAdapter adapter = mPager.getAdapter();\n if (adapter instanceof InfinitePagerAdapter) {\n mTotalSlides = ((InfinitePagerAdapter) adapter).getRealCount();\n } else {\n mTotalSlides = adapter.getCount();\n }\n }\n\n @Override\n public void onInvalidated() {\n super.onInvalidated();\n }\n };\n\n protected void update(final int mCurrentSlide, final int total) {\n tv.setText(mCurrentSlide + \"/\" + total);\n }\n\n /**\n * called by module\n *\n * @return View object\n */\n public View getView() {\n return mWrapper;\n }\n\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 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}", "public class AnimationHelper {\n public static long mTransitionAnimation = 1000;\n\n public static void notify_component(final @Nullable View mObject, final SliderAdapter mSliderAdapter, Handler postHandler, final int delayPost) {\n mTransitionAnimation = delayPost;\n notify_component(mObject, mSliderAdapter, postHandler);\n }\n\n public static void notify_component(final @Nullable View mObject, final SliderAdapter mSliderAdapter, Handler postHandler) {\n if (mObject == null) return;\n int count = mSliderAdapter.getCount();\n if (count <= 1) {\n postHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n if (mObject != null) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {\n mObject.animate().alpha(0).withEndAction(new Runnable() {\n @Override\n public void run() {\n mObject.setVisibility(View.GONE);\n }\n });\n } else {\n mObject.animate().alpha(0);\n }\n }\n }\n }, mTransitionAnimation);\n } else {\n if (mObject.getVisibility() != View.GONE) return;\n postHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n if (mObject != null) {\n if (mObject.getVisibility() != View.GONE) return;\n mObject.setVisibility(View.VISIBLE);\n mObject.setAlpha(0);\n mObject.animate().alpha(1);\n }\n }\n }, mTransitionAnimation);\n }\n }\n\n\n}", "public class ArrowControl {\n private ImageView left, right;\n\n\n private int mLWidthB, mRWidthB, count, current_position;\n boolean mLopen, mRopen, circular;\n\n public final void setCurrentPosition(final int p) {\n current_position = p;\n }\n\n public final void setTotal(final int total) {\n count = total;\n }\n\n public final void noSlideButtons() {\n left.setVisibility(View.GONE);\n right.setVisibility(View.GONE);\n mLopen = false;\n mRopen = false;\n }\n\n public final void IsCirularView(boolean b) {\n circular = b;\n }\n\n public final void notifyOnPageChanged() {\n if (count <= 1) {\n if (mLopen) {\n left.animate().translationX(-mLWidthB);\n mLopen = false;\n }\n if (mRopen) {\n right.animate().translationX(mRWidthB);\n mRopen = false;\n }\n } else {\n if (current_position == 0) {\n if (mLopen) {\n left.animate().translationX(-mLWidthB);\n mLopen = false;\n }\n } else if (current_position == count - 1) {\n if (mRopen) {\n right.animate().translationX(mRWidthB);\n mRopen = false;\n }\n } else {\n if (!mRopen) {\n right.animate().translationX(0);\n mRopen = true;\n }\n if (!mLopen) {\n left.animate().translationX(0);\n mLopen = true;\n }\n }\n }\n }\n\n\n public void setListeners(View.OnClickListener lefttrigger, View.OnClickListener righttrigger) {\n left.setOnClickListener(lefttrigger);\n right.setOnClickListener(righttrigger);\n\n mLopen = true;\n mRopen = true;\n }\n\n public ArrowControl(ImageView left_arrow, ImageView right_arrow) {\n left = left_arrow;\n right = right_arrow;\n\n mLopen = true;\n mRopen = true;\n mLWidthB = left.getDrawable().getIntrinsicWidth();\n mRWidthB = right.getDrawable().getIntrinsicWidth();\n\n }\n}", "public class ViewPagerEx extends ViewGroup {\n private static final String TAG = \"ViewPagerEx\";\n private static final boolean DEBUG = true;\n\n private static final boolean USE_CACHE = false;\n\n private static final int DEFAULT_OFFSCREEN_PAGES = 1;\n private static final int MAX_SETTLE_DURATION = 600; // ms\n private static final int MIN_DISTANCE_FOR_FLING = 25; // dips\n\n private static final int DEFAULT_GUTTER_SIZE = 16; // dips\n\n private static final int MIN_FLING_VELOCITY = 400; // dips\n\n private static final int[] LAYOUT_ATTRS = new int[]{\n android.R.attr.layout_gravity\n };\n\n /**\n * Used to track what the expected number of items in the adapter should be.\n * If the app changes this when we don't expect it, we'll throw a big obnoxious exception.\n */\n private int mExpectedAdapterCount;\n\n static class ItemInfo {\n Object object;\n int position;\n boolean scrolling;\n float widthFactor;\n float offset;\n }\n\n private static final Comparator<ItemInfo> COMPARATOR = new Comparator<ItemInfo>() {\n @Override\n public int compare(ItemInfo lhs, ItemInfo rhs) {\n return lhs.position - rhs.position;\n }\n };\n\n private static final Interpolator sInterpolator = new Interpolator() {\n public float getInterpolation(float t) {\n t -= 1.0f;\n return t * t * t * t * t + 1.0f;\n }\n };\n\n private final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();\n private final ItemInfo mTempItem = new ItemInfo();\n\n private final Rect mTempRect = new Rect();\n\n private PagerAdapter mAdapter;\n private int mCurItem; // Index of currently displayed page.\n private int mRestoredCurItem = -1;\n private Parcelable mRestoredAdapterState = null;\n private ClassLoader mRestoredClassLoader = null;\n private Scroller mScroller;\n private PagerObserver mObserver;\n\n private int mPageMargin;\n private Drawable mMarginDrawable;\n private int mTopPageBounds;\n private int mBottomPageBounds;\n\n // Offsets of the first and last items, if known.\n // Set during population, used to determine if we are at the beginning\n // or end of the pager data set during touch scrolling.\n private float mFirstOffset = -Float.MAX_VALUE;\n private float mLastOffset = Float.MAX_VALUE;\n\n private int mChildWidthMeasureSpec;\n private int mChildHeightMeasureSpec;\n private boolean mInLayout;\n\n private boolean mScrollingCacheEnabled;\n\n private boolean mPopulatePending;\n private int mOffscreenPageLimit = DEFAULT_OFFSCREEN_PAGES;\n\n private boolean mIsBeingDragged;\n private boolean mIsUnableToDrag;\n private boolean mIgnoreGutter;\n private int mDefaultGutterSize;\n private int mGutterSize;\n private int mTouchSlop;\n /**\n * Position of the last motion event.\n */\n private float mLastMotionX;\n private float mLastMotionY;\n private float mInitialMotionX;\n private float mInitialMotionY;\n /**\n * ID of the active pointer. This is used to retain consistency during\n * drags/flings if multiple pointers are used.\n */\n private int mActivePointerId = INVALID_POINTER;\n /**\n * Sentinel value for no current active pointer.\n * Used by {@link #mActivePointerId}.\n */\n private static final int INVALID_POINTER = -1;\n\n /**\n * Determines speed during touch scrolling\n */\n private VelocityTracker mVelocityTracker;\n private int mMinimumVelocity;\n private int mMaximumVelocity;\n private int mFlingDistance;\n private int mCloseEnough;\n\n // If the pager is at least this close to its final position, complete the scroll\n // on touch down and let the user interact with the content inside instead of\n // \"catching\" the flinging pager.\n private static final int CLOSE_ENOUGH = 2; // dp\n\n private boolean mFakeDragging;\n private long mFakeDragBeginTime;\n\n private EdgeEffectCompat mLeftEdge;\n private EdgeEffectCompat mRightEdge;\n\n private boolean mFirstLayout = true;\n private boolean mNeedCalculatePageOffsets = false;\n private boolean mCalledSuper;\n private int mDecorChildCount;\n\n private OnPageChangeListener mOnPageChangeListener;\n private OnPageChangeListener mInternalPageChangeListener;\n private OnAdapterChangeListener mAdapterChangeListener;\n private PageTransformer mPageTransformer;\n private Method mSetChildrenDrawingOrderEnabled;\n\n private static final int DRAW_ORDER_DEFAULT = 0;\n private static final int DRAW_ORDER_FORWARD = 1;\n private static final int DRAW_ORDER_REVERSE = 2;\n private int mDrawingOrder;\n private ArrayList<View> mDrawingOrderedChildren;\n private static final ViewPositionComparator sPositionComparator = new ViewPositionComparator();\n\n\n private ArrayList<OnPageChangeListener> mOnPageChangeListeners = new ArrayList<>();\n /**\n * Indicates that the pager is in an idle, settled state. The current page\n * is fully in view and no animation is in progress.\n */\n public static final int SCROLL_STATE_IDLE = 0;\n\n /**\n * Indicates that the pager is currently being dragged by the user.\n */\n public static final int SCROLL_STATE_DRAGGING = 1;\n\n /**\n * Indicates that the pager is in the process of settling to a final position.\n */\n public static final int SCROLL_STATE_SETTLING = 2;\n\n private final Runnable mEndScrollRunnable = new Runnable() {\n public void run() {\n setScrollState(SCROLL_STATE_IDLE);\n populate();\n }\n };\n\n private int mScrollState = SCROLL_STATE_IDLE;\n\n /**\n * Callback interface for responding to changing state of the selected page.\n */\n public interface OnPageChangeListener {\n\n /**\n * This method will be invoked when the current page is scrolled, either as part\n * of a programmatically initiated smooth scroll or a user initiated touch scroll.\n *\n * @param position Position index of the first page currently being displayed.\n * Page position+1 will be visible if positionOffset is nonzero.\n * @param positionOffset Value from [0, 1) indicating the offset from the page at position.\n * @param positionOffsetPixels Value in pixels indicating the offset from position.\n */\n void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);\n\n /**\n * This method will be invoked when a new page becomes selected. Animation is not\n * necessarily complete.\n *\n * @param position Position index of the new selected page.\n */\n void onPageSelected(int position);\n\n /**\n * Called when the scroll state changes. Useful for discovering when the user\n * begins dragging, when the pager is automatically settling to the current page,\n * or when it is fully stopped/idle.\n *\n * @param state The new scroll state.\n * @see ViewPagerEx#SCROLL_STATE_IDLE\n * @see ViewPagerEx#SCROLL_STATE_DRAGGING\n * @see ViewPagerEx#SCROLL_STATE_SETTLING\n */\n void onPageScrollStateChanged(int state);\n }\n\n /**\n * Simple implementation of the {@link OnPageChangeListener} interface with stub\n * implementations of each method. Extend this if you do not intend to override\n * every method of {@link OnPageChangeListener}.\n */\n public static class SimpleOnPageChangeListener implements OnPageChangeListener {\n @Override\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n // This space for rent\n }\n\n @Override\n public void onPageSelected(int position) {\n // This space for rent\n }\n\n @Override\n public void onPageScrollStateChanged(int state) {\n // This space for rent\n }\n }\n\n private void triggerOnPageChangeEvent(int position) {\n for (OnPageChangeListener eachListener : mOnPageChangeListeners) {\n if (eachListener != null) {\n InfinitePagerAdapter infiniteAdapter = (InfinitePagerAdapter) mAdapter;\n if (infiniteAdapter.getRealCount() == 0) {\n return;\n }\n int n = position % infiniteAdapter.getRealCount();\n eachListener.onPageSelected(n);\n }\n }\n if (mInternalPageChangeListener != null) {\n mInternalPageChangeListener.onPageSelected(position);\n }\n }\n\n /**\n * A PageTransformer is invoked whenever a visible/attached page is scrolled.\n * This offers an opportunity for the application to apply a custom transformation\n * to the page views using animation properties.\n * /\n * As property animation is only supported as of Android 3.0 and forward,\n * setting a PageTransformer on a ViewPager on earlier platform versions will\n * be ignored.\n */\n public interface PageTransformer {\n /**\n * Apply a property transformation to the given page.\n *\n * @param page Apply the transformation to this page\n * @param position Position of page relative to the current front-and-center\n * position of the pager. 0 is front and center. 1 is one full\n * page position to the right, and -1 is one page position to the left.\n */\n public void transformPage(View page, float position);\n\n }\n\n /**\n * Used internally to monitor when adapters are switched.\n */\n interface OnAdapterChangeListener {\n public void onAdapterChanged(PagerAdapter oldAdapter, PagerAdapter newAdapter);\n }\n\n /**\n * Used internally to tag special types of child views that should be added as pager decorations by default.\n */\n interface Decor {\n }\n\n public ViewPagerEx(Context context) {\n super(context);\n initViewPager();\n }\n\n public ViewPagerEx(Context context, AttributeSet attrs) {\n super(context, attrs);\n initViewPager();\n }\n\n void initViewPager() {\n setWillNotDraw(false);\n setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);\n setFocusable(true);\n final Context context = getContext();\n mScroller = new Scroller(context, sInterpolator);\n final ViewConfiguration configuration = ViewConfiguration.get(context);\n final float density = context.getResources().getDisplayMetrics().density;\n\n mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);\n mMinimumVelocity = (int) (MIN_FLING_VELOCITY * density);\n mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();\n mLeftEdge = new EdgeEffectCompat(context);\n mRightEdge = new EdgeEffectCompat(context);\n\n mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);\n mCloseEnough = (int) (CLOSE_ENOUGH * density);\n mDefaultGutterSize = (int) (DEFAULT_GUTTER_SIZE * density);\n\n ViewCompat.setAccessibilityDelegate(this, new MyAccessibilityDelegate());\n\n if (ViewCompat.getImportantForAccessibility(this)\n == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {\n ViewCompat.setImportantForAccessibility(this,\n ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n removeCallbacks(mEndScrollRunnable);\n super.onDetachedFromWindow();\n }\n\n private void setScrollState(int newState) {\n if (mScrollState == newState) {\n return;\n }\n\n mScrollState = newState;\n if (mPageTransformer != null) {\n // PageTransformers can do complex things that benefit from hardware layers.\n enableLayers(newState != SCROLL_STATE_IDLE);\n }\n\n for (OnPageChangeListener eachListener : mOnPageChangeListeners) {\n if (eachListener != null) {\n eachListener.onPageScrollStateChanged(newState);\n }\n }\n }\n\n /**\n * Add a listener that will be invoked whenever the page changes or is incrementally\n * scrolled. See {@link OnPageChangeListener}.\n *\n * @param listener Listener to add\n */\n public void addOnPageChangeListener(OnPageChangeListener listener) {\n if (!mOnPageChangeListeners.contains(listener)) {\n mOnPageChangeListeners.add(listener);\n }\n }\n\n /**\n * Remove a listener that was added with addOnPageChangeListener\n * See {@link OnPageChangeListener}.\n *\n * @param listener Listener to remove\n */\n public void removeOnPageChangeListener(OnPageChangeListener listener) {\n mOnPageChangeListeners.remove(listener);\n }\n\n /**\n * Set a PagerAdapter that will supply views for this pager as needed.\n *\n * @param adapter Adapter to use\n */\n public void setAdapter(PagerAdapter adapter) {\n if (mAdapter != null) {\n mAdapter.unregisterDataSetObserver(mObserver);\n mAdapter.startUpdate(this);\n for (int i = 0; i < mItems.size(); i++) {\n final ItemInfo ii = mItems.get(i);\n mAdapter.destroyItem(this, ii.position, ii.object);\n }\n mAdapter.finishUpdate(this);\n mItems.clear();\n removeNonDecorViews();\n mCurItem = 0;\n scrollTo(0, 0);\n }\n\n final PagerAdapter oldAdapter = mAdapter;\n mAdapter = adapter;\n mExpectedAdapterCount = 0;\n\n if (mAdapter != null) {\n if (mObserver == null) {\n mObserver = new PagerObserver();\n }\n mAdapter.registerDataSetObserver(mObserver);\n mPopulatePending = false;\n final boolean wasFirstLayout = mFirstLayout;\n mFirstLayout = true;\n mExpectedAdapterCount = mAdapter.getCount();\n if (mRestoredCurItem >= 0) {\n mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader);\n setCurrentItemInternal(mRestoredCurItem, false, true);\n mRestoredCurItem = -1;\n mRestoredAdapterState = null;\n mRestoredClassLoader = null;\n } else if (!wasFirstLayout) {\n populate();\n } else {\n requestLayout();\n }\n }\n\n if (mAdapterChangeListener != null && oldAdapter != adapter) {\n mAdapterChangeListener.onAdapterChanged(oldAdapter, adapter);\n }\n }\n\n private void removeNonDecorViews() {\n for (int i = 0; i < getChildCount(); i++) {\n final View child = getChildAt(i);\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n if (!lp.isDecor) {\n removeViewAt(i);\n i--;\n }\n }\n }\n\n /**\n * Retrieve the current adapter supplying pages.\n *\n * @return The currently registered PagerAdapter\n */\n public PagerAdapter getAdapter() {\n return mAdapter;\n }\n\n void setOnAdapterChangeListener(OnAdapterChangeListener listener) {\n mAdapterChangeListener = listener;\n }\n\n private int getClientWidth() {\n return getMeasuredWidth() - getPaddingLeft() - getPaddingRight();\n }\n\n /**\n * Set the currently selected page. If the ViewPager has already been through its first\n * layout with its current adapter there will be a smooth animated transition between\n * the current item and the specified item.\n *\n * @param item Item index to select\n */\n public void setCurrentItem(int item) {\n mPopulatePending = false;\n setCurrentItemInternal(item, !mFirstLayout, false);\n }\n\n /**\n * Set the currently selected page.\n *\n * @param item Item index to select\n * @param smoothScroll True to smoothly scroll to the new item, false to transition immediately\n */\n public void setCurrentItem(int item, boolean smoothScroll) {\n mPopulatePending = false;\n setCurrentItemInternal(item, smoothScroll, false);\n }\n\n public int getCurrentItem() {\n return mCurItem;\n }\n\n void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) {\n setCurrentItemInternal(item, smoothScroll, always, 0);\n }\n\n void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) {\n if (mAdapter == null || mAdapter.getCount() <= 0) {\n setScrollingCacheEnabled(false);\n return;\n }\n if (!always && mCurItem == item && mItems.size() != 0) {\n setScrollingCacheEnabled(false);\n return;\n }\n\n if (item < 0) {\n item = 0;\n } else if (item >= mAdapter.getCount()) {\n item = mAdapter.getCount() - 1;\n }\n final int pageLimit = mOffscreenPageLimit;\n if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) {\n // We are doing a jump by more than one page. To avoid\n // glitches, we want to keep all current pages in the view\n // until the scroll ends.\n for (int i = 0; i < mItems.size(); i++) {\n mItems.get(i).scrolling = true;\n }\n }\n final boolean dispatchSelected = mCurItem != item;\n\n if (mFirstLayout) {\n // We don't have any idea how big we are yet and shouldn't have any pages either.\n // Just set things up and let the pending layout handle things.\n mCurItem = item;\n triggerOnPageChangeEvent(item);\n if (dispatchSelected && mOnPageChangeListener != null) {\n mOnPageChangeListener.onPageSelected(item);\n }\n if (dispatchSelected && mInternalPageChangeListener != null) {\n mInternalPageChangeListener.onPageSelected(item);\n }\n requestLayout();\n } else {\n populate(item);\n scrollToItem(item, smoothScroll, velocity, dispatchSelected);\n }\n }\n\n private void scrollToItem(int item, boolean smoothScroll, int velocity,\n boolean dispatchSelected) {\n final ItemInfo curInfo = infoForPosition(item);\n int destX = 0;\n if (curInfo != null) {\n final int width = getClientWidth();\n destX = (int) (width * Math.max(mFirstOffset,\n Math.min(curInfo.offset, mLastOffset)));\n }\n if (smoothScroll) {\n smoothScrollTo(destX, 0, velocity);\n if (dispatchSelected && mOnPageChangeListener != null) {\n mOnPageChangeListener.onPageSelected(item);\n }\n if (dispatchSelected && mInternalPageChangeListener != null) {\n mInternalPageChangeListener.onPageSelected(item);\n }\n if (dispatchSelected && mOnPageChangeListeners != null) {\n triggerOnPageChangeEvent(item);\n }\n } else {\n if (dispatchSelected && mOnPageChangeListener != null) {\n mOnPageChangeListener.onPageSelected(item);\n }\n if (dispatchSelected && mInternalPageChangeListener != null) {\n mInternalPageChangeListener.onPageSelected(item);\n }\n if (dispatchSelected && mOnPageChangeListeners != null) {\n triggerOnPageChangeEvent(item);\n }\n completeScroll(false);\n scrollTo(destX, 0);\n pageScrolled(destX);\n }\n }\n\n /**\n * Set a listener that will be invoked whenever the page changes or is incrementally\n * scrolled. See {@link OnPageChangeListener}.\n *\n * @param listener Listener to set\n */\n public void setOnPageChangeListener(OnPageChangeListener listener) {\n mOnPageChangeListener = listener;\n }\n\n /**\n * Set a {@link PageTransformer} that will be called for each attached page whenever\n * the scroll position is changed. This allows the application to apply custom property\n * transformations to each page, overriding the default sliding look and feel.\n * /\n * <em>Note:</em> Prior to Android 3.0 the property animation APIs did not exist.\n * As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.\n *\n * @param reverseDrawingOrder true if the supplied PageTransformer requires page views\n * to be drawn from last to first instead of first to last.\n * @param transformer PageTransformer that will modify each page's animation properties\n */\n public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) {\n final boolean hasTransformer = transformer != null;\n final boolean needsPopulate = hasTransformer != (mPageTransformer != null);\n mPageTransformer = transformer;\n setChildrenDrawingOrderEnabledCompat(hasTransformer);\n if (hasTransformer) {\n mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD;\n } else {\n mDrawingOrder = DRAW_ORDER_DEFAULT;\n }\n if (needsPopulate) populate();\n }\n\n void setChildrenDrawingOrderEnabledCompat(boolean enable) {\n if (Build.VERSION.SDK_INT >= 7) {\n if (mSetChildrenDrawingOrderEnabled == null) {\n try {\n mSetChildrenDrawingOrderEnabled = ViewGroup.class.getDeclaredMethod(\n \"setChildrenDrawingOrderEnabled\", new Class[]{Boolean.TYPE});\n } catch (NoSuchMethodException e) {\n Log.e(TAG, \"Can't find setChildrenDrawingOrderEnabled\", e);\n }\n }\n try {\n mSetChildrenDrawingOrderEnabled.invoke(this, enable);\n } catch (Exception e) {\n Log.e(TAG, \"Error changing children drawing order\", e);\n }\n }\n }\n\n @Override\n protected int getChildDrawingOrder(int childCount, int i) {\n final int index = mDrawingOrder == DRAW_ORDER_REVERSE ? childCount - 1 - i : i;\n final int result = ((LayoutParams) mDrawingOrderedChildren.get(index).getLayoutParams()).childIndex;\n return result;\n }\n\n /**\n * Set a separate OnPageChangeListener for internal use by the support library.\n *\n * @param listener Listener to set\n * @return The old listener that was set, if any.\n */\n OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener listener) {\n OnPageChangeListener oldListener = mInternalPageChangeListener;\n mInternalPageChangeListener = listener;\n return oldListener;\n }\n\n /**\n * Returns the number of pages that will be retained to either side of the\n * current page in the view hierarchy in an idle state. Defaults to 1.\n *\n * @return How many pages will be kept offscreen on either side\n * @see #setOffscreenPageLimit(int)\n */\n public int getOffscreenPageLimit() {\n return mOffscreenPageLimit;\n }\n\n /**\n * Set the number of pages that should be retained to either side of the\n * current page in the view hierarchy in an idle state. Pages beyond this\n * limit will be recreated from the adapter when needed.\n * /\n * This is offered as an optimization. If you know in advance the number\n * of pages you will need to support or have lazy-loading mechanisms in place\n * on your pages, tweaking this setting can have benefits in perceived smoothness\n * of paging animations and interaction. If you have a small number of pages (3-4)\n * that you can keep active all at once, less time will be spent in layout for\n * newly created view subtrees as the user pages back and forth.\n * /\n * You should keep this limit low, especially if your pages have complex layouts.\n * This setting defaults to 1.\n *\n * @param limit How many pages will be kept offscreen in an idle state.\n */\n public void setOffscreenPageLimit(int limit) {\n if (limit < DEFAULT_OFFSCREEN_PAGES) {\n Log.w(TAG, \"Requested offscreen page limit \" + limit + \" too small; defaulting to \" +\n DEFAULT_OFFSCREEN_PAGES);\n limit = DEFAULT_OFFSCREEN_PAGES;\n }\n if (limit != mOffscreenPageLimit) {\n mOffscreenPageLimit = limit;\n populate();\n }\n }\n\n /**\n * Set the margin between pages.\n *\n * @param marginPixels Distance between adjacent pages in pixels\n * @see #getPageMargin()\n * @see #setPageMarginDrawable(Drawable)\n * @see #setPageMarginDrawable(int)\n */\n public void setPageMargin(int marginPixels) {\n final int oldMargin = mPageMargin;\n mPageMargin = marginPixels;\n\n final int width = getWidth();\n recomputeScrollPosition(width, width, marginPixels, oldMargin);\n\n requestLayout();\n }\n\n /**\n * Return the margin between pages.\n *\n * @return The size of the margin in pixels\n */\n public int getPageMargin() {\n return mPageMargin;\n }\n\n /**\n * Set a drawable that will be used to fill the margin between pages.\n *\n * @param d Drawable to display between pages\n */\n public void setPageMarginDrawable(Drawable d) {\n mMarginDrawable = d;\n if (d != null) refreshDrawableState();\n setWillNotDraw(d == null);\n invalidate();\n }\n\n /**\n * Set a drawable that will be used to fill the margin between pages.\n *\n * @param resId Resource ID of a drawable to display between pages\n */\n public void setPageMarginDrawable(int resId) {\n setPageMarginDrawable(getContext().getResources().getDrawable(resId));\n }\n\n @Override\n protected boolean verifyDrawable(Drawable who) {\n return super.verifyDrawable(who) || who == mMarginDrawable;\n }\n\n @Override\n protected void drawableStateChanged() {\n super.drawableStateChanged();\n final Drawable d = mMarginDrawable;\n if (d != null && d.isStateful()) {\n d.setState(getDrawableState());\n }\n }\n\n // We want the duration of the page snap animation to be influenced by the distance that\n // the screen has to travel, however, we don't want this duration to be effected in a\n // purely linear fashion. Instead, we use this method to moderate the effect that the distance\n // of travel has on the overall snap duration.\n float distanceInfluenceForSnapDuration(float f) {\n f -= 0.5f; // center the values about 0.\n f *= 0.3f * Math.PI / 2.0f;\n return (float) Math.sin(f);\n }\n\n /**\n * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.\n *\n * @param x the number of pixels to scroll by on the X axis\n * @param y the number of pixels to scroll by on the Y axis\n */\n void smoothScrollTo(int x, int y) {\n smoothScrollTo(x, y, 0);\n }\n\n /**\n * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.\n *\n * @param x the number of pixels to scroll by on the X axis\n * @param y the number of pixels to scroll by on the Y axis\n * @param velocity the velocity associated with a fling, if applicable. (0 otherwise)\n */\n void smoothScrollTo(int x, int y, int velocity) {\n if (getChildCount() == 0) {\n // Nothing to do.\n setScrollingCacheEnabled(false);\n return;\n }\n int sx = getScrollX();\n int sy = getScrollY();\n int dx = x - sx;\n int dy = y - sy;\n if (dx == 0 && dy == 0) {\n completeScroll(false);\n populate();\n setScrollState(SCROLL_STATE_IDLE);\n return;\n }\n\n setScrollingCacheEnabled(true);\n setScrollState(SCROLL_STATE_SETTLING);\n\n final int width = getClientWidth();\n final int halfWidth = width / 2;\n final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);\n final float distance = halfWidth + halfWidth *\n distanceInfluenceForSnapDuration(distanceRatio);\n\n int duration = 0;\n velocity = Math.abs(velocity);\n if (velocity > 0) {\n duration = 4 * Math.round(1000 * Math.abs(distance / velocity));\n } else {\n final float pageWidth = width * mAdapter.getPageWidth(mCurItem);\n final float pageDelta = (float) Math.abs(dx) / (pageWidth + mPageMargin);\n duration = (int) ((pageDelta + 1) * 100);\n }\n duration = Math.min(duration, MAX_SETTLE_DURATION);\n\n mScroller.startScroll(sx, sy, dx, dy, duration);\n ViewCompat.postInvalidateOnAnimation(this);\n }\n\n ItemInfo addNewItem(int position, int index) {\n ItemInfo ii = new ItemInfo();\n ii.position = position;\n ii.object = mAdapter.instantiateItem(this, position);\n ii.widthFactor = mAdapter.getPageWidth(position);\n if (index < 0 || index >= mItems.size()) {\n mItems.add(ii);\n } else {\n mItems.add(index, ii);\n }\n return ii;\n }\n\n void dataSetChanged() {\n // This method only gets called if our observer is attached, so mAdapter is non-null.\n\n final int adapterCount = mAdapter.getCount();\n mExpectedAdapterCount = adapterCount;\n boolean needPopulate = mItems.size() < mOffscreenPageLimit * 2 + 1 &&\n mItems.size() < adapterCount;\n int newCurrItem = mCurItem;\n\n boolean isUpdating = false;\n for (int i = 0; i < mItems.size(); i++) {\n final ItemInfo ii = mItems.get(i);\n final int newPos = mAdapter.getItemPosition(ii.object);\n\n if (newPos == PagerAdapter.POSITION_UNCHANGED) {\n continue;\n }\n\n if (newPos == PagerAdapter.POSITION_NONE) {\n mItems.remove(i);\n i--;\n\n if (!isUpdating) {\n mAdapter.startUpdate(this);\n isUpdating = true;\n }\n\n mAdapter.destroyItem(this, ii.position, ii.object);\n needPopulate = true;\n\n if (mCurItem == ii.position) {\n // Keep the current item in the valid range\n newCurrItem = Math.max(0, Math.min(mCurItem, adapterCount - 1));\n needPopulate = true;\n }\n continue;\n }\n\n if (ii.position != newPos) {\n if (ii.position == mCurItem) {\n // Our current item changed position. Follow it.\n newCurrItem = newPos;\n }\n\n ii.position = newPos;\n needPopulate = true;\n }\n }\n\n if (isUpdating) {\n mAdapter.finishUpdate(this);\n }\n\n Collections.sort(mItems, COMPARATOR);\n\n if (needPopulate) {\n // Reset our known page widths; populate will recompute them.\n final int childCount = getChildCount();\n for (int i = 0; i < childCount; i++) {\n final View child = getChildAt(i);\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n if (!lp.isDecor) {\n lp.widthFactor = 0.f;\n }\n }\n\n setCurrentItemInternal(newCurrItem, false, true);\n requestLayout();\n }\n }\n\n void populate() {\n populate(mCurItem);\n }\n\n void populate(int newCurrentItem) {\n ItemInfo oldCurInfo = null;\n int focusDirection = View.FOCUS_FORWARD;\n if (mCurItem != newCurrentItem) {\n focusDirection = mCurItem < newCurrentItem ? View.FOCUS_RIGHT : View.FOCUS_LEFT;\n oldCurInfo = infoForPosition(mCurItem);\n mCurItem = newCurrentItem;\n }\n\n if (mAdapter == null) {\n sortChildDrawingOrder();\n return;\n }\n\n // Bail now if we are waiting to populate. This is to hold off\n // on creating views from the time the user releases their finger to\n // fling to a new position until we have finished the scroll to\n // that position, avoiding glitches from happening at that point.\n if (mPopulatePending) {\n if (DEBUG) Log.i(TAG, \"populate is pending, skipping for now...\");\n sortChildDrawingOrder();\n return;\n }\n\n // Also, don't populate until we are attached to a window. This is to\n // avoid trying to populate before we have restored our view hierarchy\n // state and conflicting with what is restored.\n if (getWindowToken() == null) {\n return;\n }\n\n mAdapter.startUpdate(this);\n\n final int pageLimit = mOffscreenPageLimit;\n final int startPos = Math.max(0, mCurItem - pageLimit);\n final int N = mAdapter.getCount();\n final int endPos = Math.min(N - 1, mCurItem + pageLimit);\n\n if (N != mExpectedAdapterCount) {\n String resName;\n try {\n resName = getResources().getResourceName(getId());\n } catch (Resources.NotFoundException e) {\n resName = Integer.toHexString(getId());\n }\n throw new IllegalStateException(\"The application's PagerAdapter changed the adapter's\" +\n \" contents without calling PagerAdapter#notifyDataSetChanged!\" +\n \" Expected adapter item count: \" + mExpectedAdapterCount + \", found: \" + N +\n \" Pager id: \" + resName +\n \" Pager class: \" + getClass() +\n \" Problematic adapter: \" + mAdapter.getClass());\n }\n\n // Locate the currently focused item or add it if needed.\n int curIndex = -1;\n ItemInfo curItem = null;\n for (curIndex = 0; curIndex < mItems.size(); curIndex++) {\n final ItemInfo ii = mItems.get(curIndex);\n if (ii.position >= mCurItem) {\n if (ii.position == mCurItem) curItem = ii;\n break;\n }\n }\n\n if (curItem == null && N > 0) {\n curItem = addNewItem(mCurItem, curIndex);\n }\n\n // Fill 3x the available width or up to the number of offscreen\n // pages requested to either side, whichever is larger.\n // If we have no current item we have no work to do.\n if (curItem != null) {\n float extraWidthLeft = 0.f;\n int itemIndex = curIndex - 1;\n ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;\n final int clientWidth = getClientWidth();\n final float leftWidthNeeded = clientWidth <= 0 ? 0 :\n 2.f - curItem.widthFactor + (float) getPaddingLeft() / (float) clientWidth;\n for (int pos = mCurItem - 1; pos >= 0; pos--) {\n if (extraWidthLeft >= leftWidthNeeded && pos < startPos) {\n if (ii == null) {\n break;\n }\n if (pos == ii.position && !ii.scrolling) {\n mItems.remove(itemIndex);\n mAdapter.destroyItem(this, pos, ii.object);\n if (DEBUG) {\n Log.i(TAG, \"populate() - destroyItem() with pos: \" + pos +\n \" view: \" + ((View) ii.object));\n }\n itemIndex--;\n curIndex--;\n ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;\n }\n } else if (ii != null && pos == ii.position) {\n extraWidthLeft += ii.widthFactor;\n itemIndex--;\n ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;\n } else {\n ii = addNewItem(pos, itemIndex + 1);\n extraWidthLeft += ii.widthFactor;\n curIndex++;\n ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;\n }\n }\n\n float extraWidthRight = curItem.widthFactor;\n itemIndex = curIndex + 1;\n if (extraWidthRight < 2.f) {\n ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;\n final float rightWidthNeeded = clientWidth <= 0 ? 0 :\n (float) getPaddingRight() / (float) clientWidth + 2.f;\n for (int pos = mCurItem + 1; pos < N; pos++) {\n if (extraWidthRight >= rightWidthNeeded && pos > endPos) {\n if (ii == null) {\n break;\n }\n if (pos == ii.position && !ii.scrolling) {\n mItems.remove(itemIndex);\n mAdapter.destroyItem(this, pos, ii.object);\n if (DEBUG) {\n Log.i(TAG, \"populate() - destroyItem() with pos: \" + pos +\n \" view: \" + ((View) ii.object));\n }\n ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;\n }\n } else if (ii != null && pos == ii.position) {\n extraWidthRight += ii.widthFactor;\n itemIndex++;\n ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;\n } else {\n ii = addNewItem(pos, itemIndex);\n itemIndex++;\n extraWidthRight += ii.widthFactor;\n ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;\n }\n }\n }\n\n calculatePageOffsets(curItem, curIndex, oldCurInfo);\n }\n\n if (DEBUG) {\n Log.i(TAG, \"Current page list:\");\n for (int i = 0; i < mItems.size(); i++) {\n Log.i(TAG, \"#\" + i + \": page \" + mItems.get(i).position);\n }\n }\n\n mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null);\n\n mAdapter.finishUpdate(this);\n\n // Check width measurement of current pages and drawing sort order.\n // Update LayoutParams as needed.\n final int childCount = getChildCount();\n for (int i = 0; i < childCount; i++) {\n final View child = getChildAt(i);\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n lp.childIndex = i;\n if (!lp.isDecor && lp.widthFactor == 0.f) {\n // 0 means requery the adapter for this, it doesn't have a valid width.\n final ItemInfo ii = infoForChild(child);\n if (ii != null) {\n lp.widthFactor = ii.widthFactor;\n lp.position = ii.position;\n }\n }\n }\n sortChildDrawingOrder();\n\n if (hasFocus()) {\n View currentFocused = findFocus();\n ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null;\n if (ii == null || ii.position != mCurItem) {\n for (int i = 0; i < getChildCount(); i++) {\n View child = getChildAt(i);\n ii = infoForChild(child);\n if (ii != null && ii.position == mCurItem) {\n if (child.requestFocus(focusDirection)) {\n break;\n }\n }\n }\n }\n }\n }\n\n private void sortChildDrawingOrder() {\n if (mDrawingOrder != DRAW_ORDER_DEFAULT) {\n if (mDrawingOrderedChildren == null) {\n mDrawingOrderedChildren = new ArrayList<View>();\n } else {\n mDrawingOrderedChildren.clear();\n }\n final int childCount = getChildCount();\n for (int i = 0; i < childCount; i++) {\n final View child = getChildAt(i);\n mDrawingOrderedChildren.add(child);\n }\n Collections.sort(mDrawingOrderedChildren, sPositionComparator);\n }\n }\n\n private void calculatePageOffsets(ItemInfo curItem, int curIndex, ItemInfo oldCurInfo) {\n final int N = mAdapter.getCount();\n final int width = getClientWidth();\n final float marginOffset = width > 0 ? (float) mPageMargin / width : 0;\n // Fix up offsets for later layout.\n if (oldCurInfo != null) {\n final int oldCurPosition = oldCurInfo.position;\n // Base offsets off of oldCurInfo.\n if (oldCurPosition < curItem.position) {\n int itemIndex = 0;\n ItemInfo ii = null;\n float offset = oldCurInfo.offset + oldCurInfo.widthFactor + marginOffset;\n for (int pos = oldCurPosition + 1;\n pos <= curItem.position && itemIndex < mItems.size(); pos++) {\n ii = mItems.get(itemIndex);\n while (pos > ii.position && itemIndex < mItems.size() - 1) {\n itemIndex++;\n ii = mItems.get(itemIndex);\n }\n while (pos < ii.position) {\n // We don't have an item populated for this,\n // ask the adapter for an offset.\n offset += mAdapter.getPageWidth(pos) + marginOffset;\n pos++;\n }\n ii.offset = offset;\n offset += ii.widthFactor + marginOffset;\n }\n } else if (oldCurPosition > curItem.position) {\n int itemIndex = mItems.size() - 1;\n ItemInfo ii = null;\n float offset = oldCurInfo.offset;\n for (int pos = oldCurPosition - 1;\n pos >= curItem.position && itemIndex >= 0; pos--) {\n ii = mItems.get(itemIndex);\n while (pos < ii.position && itemIndex > 0) {\n itemIndex--;\n ii = mItems.get(itemIndex);\n }\n while (pos > ii.position) {\n // We don't have an item populated for this,\n // ask the adapter for an offset.\n offset -= mAdapter.getPageWidth(pos) + marginOffset;\n pos--;\n }\n offset -= ii.widthFactor + marginOffset;\n ii.offset = offset;\n }\n }\n }\n\n // Base all offsets off of curItem.\n final int itemCount = mItems.size();\n float offset = curItem.offset;\n int pos = curItem.position - 1;\n mFirstOffset = curItem.position == 0 ? curItem.offset : -Float.MAX_VALUE;\n mLastOffset = curItem.position == N - 1 ?\n curItem.offset + curItem.widthFactor - 1 : Float.MAX_VALUE;\n // Previous pages\n for (int i = curIndex - 1; i >= 0; i--, pos--) {\n final ItemInfo ii = mItems.get(i);\n while (pos > ii.position) {\n offset -= mAdapter.getPageWidth(pos--) + marginOffset;\n }\n offset -= ii.widthFactor + marginOffset;\n ii.offset = offset;\n if (ii.position == 0) mFirstOffset = offset;\n }\n offset = curItem.offset + curItem.widthFactor + marginOffset;\n pos = curItem.position + 1;\n // Next pages\n for (int i = curIndex + 1; i < itemCount; i++, pos++) {\n final ItemInfo ii = mItems.get(i);\n while (pos < ii.position) {\n offset += mAdapter.getPageWidth(pos++) + marginOffset;\n }\n if (ii.position == N - 1) {\n mLastOffset = offset + ii.widthFactor - 1;\n }\n ii.offset = offset;\n offset += ii.widthFactor + marginOffset;\n }\n\n mNeedCalculatePageOffsets = false;\n }\n\n /**\n * This is the persistent state that is saved by ViewPager. Only needed if you are creating a sublass of ViewPager that must save its own state, in which case it should implement a subclass of this which contains that state.\n */\n public static class SavedState extends BaseSavedState {\n int position;\n Parcelable adapterState;\n ClassLoader loader;\n\n public SavedState(Parcelable superState) {\n super(superState);\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n super.writeToParcel(out, flags);\n out.writeInt(position);\n out.writeParcelable(adapterState, flags);\n }\n\n @Override\n public String toString() {\n return \"FragmentPager.SavedState{\"\n + Integer.toHexString(System.identityHashCode(this))\n + \" position=\" + position + \"}\";\n }\n\n public static final Parcelable.Creator<SavedState> CREATOR\n = ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() {\n @Override\n public SavedState createFromParcel(Parcel in, ClassLoader loader) {\n return new SavedState(in, loader);\n }\n\n @Override\n public SavedState[] newArray(int size) {\n return new SavedState[size];\n }\n });\n\n SavedState(Parcel in, ClassLoader loader) {\n super(in);\n if (loader == null) {\n loader = getClass().getClassLoader();\n }\n position = in.readInt();\n adapterState = in.readParcelable(loader);\n this.loader = loader;\n }\n }\n\n @Override\n public Parcelable onSaveInstanceState() {\n Parcelable superState = super.onSaveInstanceState();\n SavedState ss = new SavedState(superState);\n ss.position = mCurItem;\n if (mAdapter != null) {\n ss.adapterState = mAdapter.saveState();\n }\n return ss;\n }\n\n @Override\n public void onRestoreInstanceState(Parcelable state) {\n if (!(state instanceof SavedState)) {\n super.onRestoreInstanceState(state);\n return;\n }\n\n SavedState ss = (SavedState) state;\n super.onRestoreInstanceState(ss.getSuperState());\n\n if (mAdapter != null) {\n mAdapter.restoreState(ss.adapterState, ss.loader);\n setCurrentItemInternal(ss.position, false, true);\n } else {\n mRestoredCurItem = ss.position;\n mRestoredAdapterState = ss.adapterState;\n mRestoredClassLoader = ss.loader;\n }\n }\n\n @Override\n public void addView(View child, int index, ViewGroup.LayoutParams params) {\n if (!checkLayoutParams(params)) {\n params = generateLayoutParams(params);\n }\n final LayoutParams lp = (LayoutParams) params;\n lp.isDecor |= child instanceof Decor;\n if (mInLayout) {\n if (lp != null && lp.isDecor) {\n throw new IllegalStateException(\"Cannot add pager decor view during layout\");\n }\n lp.needsMeasure = true;\n addViewInLayout(child, index, params);\n } else {\n super.addView(child, index, params);\n }\n\n if (USE_CACHE) {\n if (child.getVisibility() != GONE) {\n child.setDrawingCacheEnabled(mScrollingCacheEnabled);\n } else {\n child.setDrawingCacheEnabled(false);\n }\n }\n }\n\n @Override\n public void removeView(View view) {\n if (mInLayout) {\n removeViewInLayout(view);\n } else {\n super.removeView(view);\n }\n }\n\n ItemInfo infoForChild(View child) {\n for (int i = 0; i < mItems.size(); i++) {\n ItemInfo ii = mItems.get(i);\n if (mAdapter.isViewFromObject(child, ii.object)) {\n return ii;\n }\n }\n return null;\n }\n\n ItemInfo infoForAnyChild(View child) {\n ViewParent parent;\n while ((parent = child.getParent()) != this) {\n if (parent == null || !(parent instanceof View)) {\n return null;\n }\n child = (View) parent;\n }\n return infoForChild(child);\n }\n\n ItemInfo infoForPosition(int position) {\n for (int i = 0; i < mItems.size(); i++) {\n ItemInfo ii = mItems.get(i);\n if (ii.position == position) {\n return ii;\n }\n }\n return null;\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n mFirstLayout = true;\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n // For simple implementation, our internal size is always 0.\n // We depend on the container to specify the layout size of\n // our view. We can't really know what it is since we will be\n // adding and removing different arbitrary views and do not\n // want the layout to change as this happens.\n setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),\n getDefaultSize(0, heightMeasureSpec));\n\n final int measuredWidth = getMeasuredWidth();\n final int maxGutterSize = measuredWidth / 10;\n mGutterSize = Math.min(maxGutterSize, mDefaultGutterSize);\n\n // Children are just made to fill our space.\n int childWidthSize = measuredWidth - getPaddingLeft() - getPaddingRight();\n int childHeightSize = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();\n\n /*\n * Make sure all children have been properly measured. Decor views first.\n * Right now we cheat and make this less complicated by assuming decor\n * views won't intersect. We will pin to edges based on gravity.\n */\n int size = getChildCount();\n for (int i = 0; i < size; ++i) {\n final View child = getChildAt(i);\n if (child.getVisibility() != GONE) {\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n if (lp != null && lp.isDecor) {\n final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;\n final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;\n int widthMode = MeasureSpec.AT_MOST;\n int heightMode = MeasureSpec.AT_MOST;\n boolean consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM;\n boolean consumeHorizontal = hgrav == Gravity.LEFT || hgrav == Gravity.RIGHT;\n\n if (consumeVertical) {\n widthMode = MeasureSpec.EXACTLY;\n } else if (consumeHorizontal) {\n heightMode = MeasureSpec.EXACTLY;\n }\n\n int widthSize = childWidthSize;\n int heightSize = childHeightSize;\n if (lp.width != LayoutParams.WRAP_CONTENT) {\n widthMode = MeasureSpec.EXACTLY;\n if (lp.width != LayoutParams.FILL_PARENT) {\n widthSize = lp.width;\n }\n }\n if (lp.height != LayoutParams.WRAP_CONTENT) {\n heightMode = MeasureSpec.EXACTLY;\n if (lp.height != LayoutParams.FILL_PARENT) {\n heightSize = lp.height;\n }\n }\n final int widthSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode);\n final int heightSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode);\n child.measure(widthSpec, heightSpec);\n\n if (consumeVertical) {\n childHeightSize -= child.getMeasuredHeight();\n } else if (consumeHorizontal) {\n childWidthSize -= child.getMeasuredWidth();\n }\n }\n }\n }\n\n mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);\n mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY);\n\n // Make sure we have created all fragments that we need to have shown.\n mInLayout = true;\n populate();\n mInLayout = false;\n\n // Page views next.\n size = getChildCount();\n for (int i = 0; i < size; ++i) {\n final View child = getChildAt(i);\n if (child.getVisibility() != GONE) {\n if (DEBUG) Log.v(TAG, \"Measuring #\" + i + \" \" + child\n + \": \" + mChildWidthMeasureSpec);\n\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n if (lp == null || !lp.isDecor) {\n final int widthSpec = MeasureSpec.makeMeasureSpec(\n (int) (childWidthSize * lp.widthFactor), MeasureSpec.EXACTLY);\n child.measure(widthSpec, mChildHeightMeasureSpec);\n }\n }\n }\n }\n\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n\n // Make sure scroll position is set correctly.\n if (w != oldw) {\n recomputeScrollPosition(w, oldw, mPageMargin, mPageMargin);\n }\n }\n\n private void recomputeScrollPosition(int width, int oldWidth, int margin, int oldMargin) {\n if (oldWidth > 0 && !mItems.isEmpty()) {\n final int widthWithMargin = width - getPaddingLeft() - getPaddingRight() + margin;\n final int oldWidthWithMargin = oldWidth - getPaddingLeft() - getPaddingRight()\n + oldMargin;\n final int xpos = getScrollX();\n final float pageOffset = (float) xpos / oldWidthWithMargin;\n final int newOffsetPixels = (int) (pageOffset * widthWithMargin);\n\n scrollTo(newOffsetPixels, getScrollY());\n if (!mScroller.isFinished()) {\n // We now return to your regularly scheduled scroll, already in progress.\n final int newDuration = mScroller.getDuration() - mScroller.timePassed();\n ItemInfo targetInfo = infoForPosition(mCurItem);\n mScroller.startScroll(newOffsetPixels, 0,\n (int) (targetInfo.offset * width), 0, newDuration);\n }\n } else {\n final ItemInfo ii = infoForPosition(mCurItem);\n final float scrollOffset = ii != null ? Math.min(ii.offset, mLastOffset) : 0;\n final int scrollPos = (int) (scrollOffset *\n (width - getPaddingLeft() - getPaddingRight()));\n if (scrollPos != getScrollX()) {\n completeScroll(false);\n scrollTo(scrollPos, getScrollY());\n }\n }\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n final int count = getChildCount();\n int width = r - l;\n int height = b - t;\n int paddingLeft = getPaddingLeft();\n int paddingTop = getPaddingTop();\n int paddingRight = getPaddingRight();\n int paddingBottom = getPaddingBottom();\n final int scrollX = getScrollX();\n\n int decorCount = 0;\n\n // First pass - decor views. We need to do this in two passes so that\n // we have the proper offsets for non-decor views later.\n for (int i = 0; i < count; i++) {\n final View child = getChildAt(i);\n if (child.getVisibility() != GONE) {\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n int childLeft = 0;\n int childTop = 0;\n if (lp.isDecor) {\n final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;\n final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;\n switch (hgrav) {\n default:\n childLeft = paddingLeft;\n break;\n case Gravity.LEFT:\n childLeft = paddingLeft;\n paddingLeft += child.getMeasuredWidth();\n break;\n case Gravity.CENTER_HORIZONTAL:\n childLeft = Math.max((width - child.getMeasuredWidth()) / 2,\n paddingLeft);\n break;\n case Gravity.RIGHT:\n childLeft = width - paddingRight - child.getMeasuredWidth();\n paddingRight += child.getMeasuredWidth();\n break;\n }\n switch (vgrav) {\n default:\n childTop = paddingTop;\n break;\n case Gravity.TOP:\n childTop = paddingTop;\n paddingTop += child.getMeasuredHeight();\n break;\n case Gravity.CENTER_VERTICAL:\n childTop = Math.max((height - child.getMeasuredHeight()) / 2,\n paddingTop);\n break;\n case Gravity.BOTTOM:\n childTop = height - paddingBottom - child.getMeasuredHeight();\n paddingBottom += child.getMeasuredHeight();\n break;\n }\n childLeft += scrollX;\n child.layout(childLeft, childTop,\n childLeft + child.getMeasuredWidth(),\n childTop + child.getMeasuredHeight());\n decorCount++;\n }\n }\n }\n\n final int childWidth = width - paddingLeft - paddingRight;\n // Page views. Do this once we have the right padding offsets from above.\n for (int i = 0; i < count; i++) {\n final View child = getChildAt(i);\n if (child.getVisibility() != GONE) {\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n ItemInfo ii;\n if (!lp.isDecor && (ii = infoForChild(child)) != null) {\n int loff = (int) (childWidth * ii.offset);\n int childLeft = paddingLeft + loff;\n int childTop = paddingTop;\n if (lp.needsMeasure) {\n // This was added during layout and needs measurement.\n // Do it now that we know what we're working with.\n lp.needsMeasure = false;\n final int widthSpec = MeasureSpec.makeMeasureSpec(\n (int) (childWidth * lp.widthFactor),\n MeasureSpec.EXACTLY);\n final int heightSpec = MeasureSpec.makeMeasureSpec(\n (int) (height - paddingTop - paddingBottom),\n MeasureSpec.EXACTLY);\n child.measure(widthSpec, heightSpec);\n }\n if (DEBUG) Log.v(TAG, \"Positioning #\" + i + \" \" + child + \" f=\" + ii.object\n + \":\" + childLeft + \",\" + childTop + \" \" + child.getMeasuredWidth()\n + \"x\" + child.getMeasuredHeight());\n child.layout(childLeft, childTop,\n childLeft + child.getMeasuredWidth(),\n childTop + child.getMeasuredHeight());\n }\n }\n }\n mTopPageBounds = paddingTop;\n mBottomPageBounds = height - paddingBottom;\n mDecorChildCount = decorCount;\n\n if (mFirstLayout) {\n scrollToItem(mCurItem, false, 0, false);\n }\n mFirstLayout = false;\n }\n\n @Override\n public void computeScroll() {\n if (!mScroller.isFinished() && mScroller.computeScrollOffset()) {\n int oldX = getScrollX();\n int oldY = getScrollY();\n int x = mScroller.getCurrX();\n int y = mScroller.getCurrY();\n\n if (oldX != x || oldY != y) {\n scrollTo(x, y);\n if (!pageScrolled(x)) {\n mScroller.abortAnimation();\n scrollTo(0, y);\n }\n }\n\n // Keep on drawing until the animation has finished.\n ViewCompat.postInvalidateOnAnimation(this);\n return;\n }\n\n // Done with scroll, clean up state.\n completeScroll(true);\n }\n\n private boolean pageScrolled(int xpos) {\n if (mItems.size() == 0) {\n mCalledSuper = false;\n onPageScrolled(0, 0, 0);\n if (!mCalledSuper) {\n throw new IllegalStateException(\n \"onPageScrolled did not call superclass implementation\");\n }\n return false;\n }\n final ItemInfo ii = infoForCurrentScrollPosition();\n final int width = getClientWidth();\n final int widthWithMargin = width + mPageMargin;\n final float marginOffset = (float) mPageMargin / width;\n final int currentPage = ii.position;\n final float pageOffset = (((float) xpos / width) - ii.offset) /\n (ii.widthFactor + marginOffset);\n final int offsetPixels = (int) (pageOffset * widthWithMargin);\n\n mCalledSuper = false;\n onPageScrolled(currentPage, pageOffset, offsetPixels);\n if (!mCalledSuper) {\n throw new IllegalStateException(\n \"onPageScrolled did not call superclass implementation\");\n }\n return true;\n }\n\n /**\n * This method will be invoked when the current page is scrolled, either as part\n * of a programmatically initiated smooth scroll or a user initiated touch scroll.\n * If you override this method you must call through to the superclass implementation\n * (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled\n * returns.\n *\n * @param position Position index of the first page currently being displayed.\n * Page position+1 will be visible if positionOffset is nonzero.\n * @param offset Value from [0, 1) indicating the offset from the page at position.\n * @param offsetPixels Value in pixels indicating the offset from position.\n */\n protected void onPageScrolled(int position, float offset, int offsetPixels) {\n // Offset any decor views if needed - keep them on-screen at all times.\n if (mDecorChildCount > 0) {\n final int scrollX = getScrollX();\n int paddingLeft = getPaddingLeft();\n int paddingRight = getPaddingRight();\n final int width = getWidth();\n final int childCount = getChildCount();\n for (int i = 0; i < childCount; i++) {\n final View child = getChildAt(i);\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n if (!lp.isDecor) continue;\n\n final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;\n int childLeft = 0;\n switch (hgrav) {\n default:\n childLeft = paddingLeft;\n break;\n case Gravity.LEFT:\n childLeft = paddingLeft;\n paddingLeft += child.getWidth();\n break;\n case Gravity.CENTER_HORIZONTAL:\n childLeft = Math.max((width - child.getMeasuredWidth()) / 2,\n paddingLeft);\n break;\n case Gravity.RIGHT:\n childLeft = width - paddingRight - child.getMeasuredWidth();\n paddingRight += child.getMeasuredWidth();\n break;\n }\n childLeft += scrollX;\n\n final int childOffset = childLeft - child.getLeft();\n if (childOffset != 0) {\n child.offsetLeftAndRight(childOffset);\n }\n }\n }\n\n for (OnPageChangeListener eachListener : mOnPageChangeListeners) {\n if (eachListener != null) {\n eachListener.onPageScrolled(position, offset, offsetPixels);\n }\n }\n\n if (mOnPageChangeListener != null) {\n mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels);\n }\n if (mInternalPageChangeListener != null) {\n mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels);\n }\n\n if (mPageTransformer != null) {\n final int scrollX = getScrollX();\n final int childCount = getChildCount();\n for (int i = 0; i < childCount; i++) {\n final View child = getChildAt(i);\n final LayoutParams lp = (LayoutParams) child.getLayoutParams();\n\n if (lp.isDecor) continue;\n\n final float transformPos = (float) (child.getLeft() - scrollX) / getClientWidth();\n mPageTransformer.transformPage(child, transformPos);\n }\n }\n\n mCalledSuper = true;\n }\n\n private void completeScroll(boolean postEvents) {\n boolean needPopulate = mScrollState == SCROLL_STATE_SETTLING;\n if (needPopulate) {\n // Done with scroll, no longer want to cache view drawing.\n setScrollingCacheEnabled(false);\n mScroller.abortAnimation();\n int oldX = getScrollX();\n int oldY = getScrollY();\n int x = mScroller.getCurrX();\n int y = mScroller.getCurrY();\n if (oldX != x || oldY != y) {\n scrollTo(x, y);\n }\n }\n mPopulatePending = false;\n for (int i = 0; i < mItems.size(); i++) {\n ItemInfo ii = mItems.get(i);\n if (ii.scrolling) {\n needPopulate = true;\n ii.scrolling = false;\n }\n }\n if (needPopulate) {\n if (postEvents) {\n ViewCompat.postOnAnimation(this, mEndScrollRunnable);\n } else {\n mEndScrollRunnable.run();\n }\n }\n }\n\n private boolean isGutterDrag(float x, float dx) {\n return (x < mGutterSize && dx > 0) || (x > getWidth() - mGutterSize && dx < 0);\n }\n\n private void enableLayers(boolean enable) {\n final int childCount = getChildCount();\n for (int i = 0; i < childCount; i++) {\n final int layerType = enable ?\n ViewCompat.LAYER_TYPE_HARDWARE : ViewCompat.LAYER_TYPE_NONE;\n ViewCompat.setLayerType(getChildAt(i), layerType, null);\n }\n }\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n /*\n * This method JUST determines whether we want to intercept the motion.\n * If we return true, onMotionEvent will be called and we do the actual\n * scrolling there.\n */\n\n final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;\n\n // Always take care of the touch gesture being complete.\n if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {\n // Release the drag.\n if (DEBUG) Log.v(TAG, \"Intercept done!\");\n mIsBeingDragged = false;\n mIsUnableToDrag = false;\n mActivePointerId = INVALID_POINTER;\n if (mVelocityTracker != null) {\n mVelocityTracker.recycle();\n mVelocityTracker = null;\n }\n return false;\n }\n\n // Nothing more to do here if we have decided whether or not we\n // are dragging.\n if (action != MotionEvent.ACTION_DOWN) {\n if (mIsBeingDragged) {\n if (DEBUG) Log.v(TAG, \"Intercept returning true!\");\n return true;\n }\n if (mIsUnableToDrag) {\n if (DEBUG) Log.v(TAG, \"Intercept returning false!\");\n return false;\n }\n }\n\n switch (action) {\n case MotionEvent.ACTION_MOVE: {\n /*\n * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check\n * whether the user has moved far enough from his original down touch.\n */\n\n /*\n * Locally do absolute value. mLastMotionY is set to the y value\n * of the down event.\n */\n final int activePointerId = mActivePointerId;\n if (activePointerId == INVALID_POINTER) {\n // If we don't have a valid id, the touch down wasn't on content.\n break;\n }\n\n final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId);\n final float x = MotionEventCompat.getX(ev, pointerIndex);\n final float dx = x - mLastMotionX;\n final float xDiff = Math.abs(dx);\n final float y = MotionEventCompat.getY(ev, pointerIndex);\n final float yDiff = Math.abs(y - mInitialMotionY);\n if (DEBUG) Log.v(TAG, \"Moved x to \" + x + \",\" + y + \" diff=\" + xDiff + \",\" + yDiff);\n\n if (dx != 0 && !isGutterDrag(mLastMotionX, dx) &&\n canScroll(this, false, (int) dx, (int) x, (int) y)) {\n // Nested view has scrollable area under this point. Let it be handled there.\n mLastMotionX = x;\n mLastMotionY = y;\n mIsUnableToDrag = true;\n return false;\n }\n if (xDiff > mTouchSlop && xDiff * 0.5f > yDiff) {\n if (DEBUG) Log.v(TAG, \"Starting drag!\");\n mIsBeingDragged = true;\n requestParentDisallowInterceptTouchEvent(true);\n setScrollState(SCROLL_STATE_DRAGGING);\n mLastMotionX = dx > 0 ? mInitialMotionX + mTouchSlop :\n mInitialMotionX - mTouchSlop;\n mLastMotionY = y;\n setScrollingCacheEnabled(true);\n } else if (yDiff > mTouchSlop) {\n // The finger has moved enough in the vertical\n // direction to be counted as a drag... abort\n // any attempt to drag horizontally, to work correctly\n // with children that have scrolling containers.\n if (DEBUG) Log.v(TAG, \"Starting unable to drag!\");\n mIsUnableToDrag = true;\n }\n if (mIsBeingDragged) {\n // Scroll to follow the motion event\n if (performDrag(x)) {\n ViewCompat.postInvalidateOnAnimation(this);\n }\n }\n break;\n }\n\n case MotionEvent.ACTION_DOWN: {\n /*\n * Remember location of down touch.\n * ACTION_DOWN always refers to pointer index 0.\n */\n mLastMotionX = mInitialMotionX = ev.getX();\n mLastMotionY = mInitialMotionY = ev.getY();\n mActivePointerId = MotionEventCompat.getPointerId(ev, 0);\n mIsUnableToDrag = false;\n\n mScroller.computeScrollOffset();\n if (mScrollState == SCROLL_STATE_SETTLING &&\n Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) > mCloseEnough) {\n // Let the user 'catch' the pager as it animates.\n mScroller.abortAnimation();\n mPopulatePending = false;\n populate();\n mIsBeingDragged = true;\n requestParentDisallowInterceptTouchEvent(true);\n setScrollState(SCROLL_STATE_DRAGGING);\n } else {\n completeScroll(false);\n mIsBeingDragged = false;\n }\n\n InfinitePagerAdapter infiniteAdapter = (InfinitePagerAdapter) mAdapter;\n if (infiniteAdapter.getRealCount() == 1) {\n requestParentDisallowInterceptTouchEvent(true);\n }\n\n\n if (DEBUG) Log.v(TAG, \"Down at \" + mLastMotionX + \",\" + mLastMotionY\n + \" mIsBeingDragged=\" + mIsBeingDragged\n + \"mIsUnableToDrag=\" + mIsUnableToDrag);\n break;\n }\n\n case MotionEventCompat.ACTION_POINTER_UP:\n onSecondaryPointerUp(ev);\n break;\n }\n\n if (mVelocityTracker == null) {\n mVelocityTracker = VelocityTracker.obtain();\n }\n mVelocityTracker.addMovement(ev);\n\n /*\n * The only time we want to intercept motion events is if we are in the\n * drag mode.\n */\n // if (!mIsBeingDragged) {\n ///onSecondaryPointerUp(ev);\n // }\n return mIsBeingDragged;\n }\n\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n if (mFakeDragging) {\n // A fake drag is in progress already, ignore this real one\n // but still eat the touch events.\n // (It is likely that the user is multi-touching the screen.)\n return true;\n }\n\n if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {\n // Don't handle edge touches immediately -- they may actually belong to one of our\n // descendants.\n return false;\n }\n\n if (mAdapter == null || mAdapter.getCount() == 0) {\n // Nothing to present or scroll; nothing to touch.\n return false;\n }\n if (mVelocityTracker == null) {\n mVelocityTracker = VelocityTracker.obtain();\n }\n mVelocityTracker.addMovement(ev);\n\n final int action = ev.getAction();\n boolean needsInvalidate = false;\n\n switch (action & MotionEventCompat.ACTION_MASK) {\n case MotionEvent.ACTION_DOWN: {\n mScroller.abortAnimation();\n mPopulatePending = false;\n populate();\n\n // Remember where the motion event started\n mLastMotionX = mInitialMotionX = ev.getX();\n mLastMotionY = mInitialMotionY = ev.getY();\n mActivePointerId = MotionEventCompat.getPointerId(ev, 0);\n break;\n }\n case MotionEvent.ACTION_MOVE:\n if (!mIsBeingDragged) {\n final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);\n final float x = MotionEventCompat.getX(ev, pointerIndex);\n final float xDiff = Math.abs(x - mLastMotionX);\n final float y = MotionEventCompat.getY(ev, pointerIndex);\n final float yDiff = Math.abs(y - mLastMotionY);\n if (DEBUG)\n Log.v(TAG, \"Moved x to \" + x + \",\" + y + \" diff=\" + xDiff + \",\" + yDiff);\n if (xDiff > mTouchSlop && xDiff > yDiff) {\n if (DEBUG) Log.v(TAG, \"Starting drag!\");\n mIsBeingDragged = true;\n requestParentDisallowInterceptTouchEvent(true);\n mLastMotionX = x - mInitialMotionX > 0 ? mInitialMotionX + mTouchSlop :\n mInitialMotionX - mTouchSlop;\n mLastMotionY = y;\n setScrollState(SCROLL_STATE_DRAGGING);\n setScrollingCacheEnabled(true);\n\n // Disallow Parent Intercept, just in case\n ViewParent parent = getParent();\n if (parent != null) {\n parent.requestDisallowInterceptTouchEvent(true);\n }\n }\n }\n // Not else! Note that mIsBeingDragged can be set above.\n if (mIsBeingDragged) {\n // Scroll to follow the motion event\n final int activePointerIndex = MotionEventCompat.findPointerIndex(\n ev, mActivePointerId);\n final float x = MotionEventCompat.getX(ev, activePointerIndex);\n needsInvalidate |= performDrag(x);\n }\n break;\n case MotionEvent.ACTION_UP:\n if (mIsBeingDragged) {\n final VelocityTracker velocityTracker = mVelocityTracker;\n velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);\n int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(\n velocityTracker, mActivePointerId);\n mPopulatePending = true;\n final int width = getClientWidth();\n final int scrollX = getScrollX();\n final ItemInfo ii = infoForCurrentScrollPosition();\n final int currentPage = ii.position;\n final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor;\n final int activePointerIndex =\n MotionEventCompat.findPointerIndex(ev, mActivePointerId);\n final float x = MotionEventCompat.getX(ev, activePointerIndex);\n final int totalDelta = (int) (x - mInitialMotionX);\n int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta);\n\n if (isRealCountMoreThanOne()) {\n setCurrentItemInternal(nextPage, true, true, initialVelocity);\n }\n mActivePointerId = INVALID_POINTER;\n if (isRealCountMoreThanOne()) {\n endDrag();\n needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();\n }\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n if (mIsBeingDragged) {\n scrollToItem(mCurItem, true, 0, false);\n mActivePointerId = INVALID_POINTER;\n endDrag();\n needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();\n }\n break;\n case MotionEventCompat.ACTION_POINTER_DOWN: {\n final int index = MotionEventCompat.getActionIndex(ev);\n final float x = MotionEventCompat.getX(ev, index);\n mLastMotionX = x;\n mActivePointerId = MotionEventCompat.getPointerId(ev, index);\n break;\n }\n case MotionEventCompat.ACTION_POINTER_UP:\n onSecondaryPointerUp(ev);\n mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));\n break;\n }\n if (needsInvalidate) {\n ViewCompat.postInvalidateOnAnimation(this);\n }\n return true;\n }\n\n private void requestParentDisallowInterceptTouchEvent(boolean disallowIntercept) {\n final ViewParent parent = getParent();\n if (parent != null) {\n parent.requestDisallowInterceptTouchEvent(disallowIntercept);\n }\n }\n\n private boolean performDrag(float x) {\n boolean needsInvalidate = false;\n\n final float deltaX = mLastMotionX - x;\n mLastMotionX = x;\n\n float oldScrollX = getScrollX();\n float scrollX = oldScrollX + deltaX;\n final int width = getClientWidth();\n\n float leftBound = width * mFirstOffset;\n float rightBound = width * mLastOffset;\n boolean leftAbsolute = true;\n boolean rightAbsolute = true;\n\n final ItemInfo firstItem = mItems.get(0);\n final ItemInfo lastItem = mItems.get(mItems.size() - 1);\n if (firstItem.position != 0) {\n leftAbsolute = false;\n leftBound = firstItem.offset * width;\n }\n if (lastItem.position != mAdapter.getCount() - 1) {\n rightAbsolute = false;\n rightBound = lastItem.offset * width;\n }\n\n if (scrollX < leftBound) {\n if (leftAbsolute) {\n float over = leftBound - scrollX;\n needsInvalidate = mLeftEdge.onPull(Math.abs(over) / width);\n }\n scrollX = leftBound;\n } else if (scrollX > rightBound) {\n if (rightAbsolute) {\n float over = scrollX - rightBound;\n needsInvalidate = mRightEdge.onPull(Math.abs(over) / width);\n }\n scrollX = rightBound;\n }\n // Don't lose the rounded component\n mLastMotionX += scrollX - (int) scrollX;\n\n //determine if the scroll is enabled\n if (isRealCountMoreThanOne()) {\n scrollTo((int) scrollX, getScrollY());\n pageScrolled((int) scrollX);\n }\n\n return needsInvalidate;\n }\n\n private boolean isRealCountMoreThanOne() {\n InfinitePagerAdapter infiniteAdapter = (InfinitePagerAdapter) mAdapter;\n return infiniteAdapter.getRealCount() > 1;\n }\n\n /**\n * @return Info about the page at the current scroll position.\n * This can be synthetic for a missing middle page; the 'object' field can be null.\n */\n private ItemInfo infoForCurrentScrollPosition() {\n final int width = getClientWidth();\n final float scrollOffset = width > 0 ? (float) getScrollX() / width : 0;\n final float marginOffset = width > 0 ? (float) mPageMargin / width : 0;\n int lastPos = -1;\n float lastOffset = 0.f;\n float lastWidth = 0.f;\n boolean first = true;\n\n ItemInfo lastItem = null;\n for (int i = 0; i < mItems.size(); i++) {\n ItemInfo ii = mItems.get(i);\n float offset;\n if (!first && ii.position != lastPos + 1) {\n // Create a synthetic item for a missing page.\n ii = mTempItem;\n ii.offset = lastOffset + lastWidth + marginOffset;\n ii.position = lastPos + 1;\n ii.widthFactor = mAdapter.getPageWidth(ii.position);\n i--;\n }\n offset = ii.offset;\n\n final float leftBound = offset;\n final float rightBound = offset + ii.widthFactor + marginOffset;\n if (first || scrollOffset >= leftBound) {\n if (scrollOffset < rightBound || i == mItems.size() - 1) {\n return ii;\n }\n } else {\n return lastItem;\n }\n first = false;\n lastPos = ii.position;\n lastOffset = offset;\n lastWidth = ii.widthFactor;\n lastItem = ii;\n }\n\n return lastItem;\n }\n\n private int determineTargetPage(int currentPage, float pageOffset, int velocity, int deltaX) {\n int targetPage;\n if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) {\n targetPage = velocity > 0 ? currentPage : currentPage + 1;\n } else {\n final float truncator = currentPage >= mCurItem ? 0.4f : 0.6f;\n targetPage = (int) (currentPage + pageOffset + truncator);\n }\n\n if (mItems.size() > 0) {\n final ItemInfo firstItem = mItems.get(0);\n final ItemInfo lastItem = mItems.get(mItems.size() - 1);\n\n // Only let the user target pages we have items for\n targetPage = Math.max(firstItem.position, Math.min(targetPage, lastItem.position));\n }\n\n return targetPage;\n }\n\n @Override\n public void draw(Canvas canvas) {\n super.draw(canvas);\n boolean needsInvalidate = false;\n\n final int overScrollMode = ViewCompat.getOverScrollMode(this);\n if (overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS ||\n (overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS &&\n mAdapter != null && mAdapter.getCount() > 1)) {\n if (!mLeftEdge.isFinished()) {\n final int restoreCount = canvas.save();\n final int height = getHeight() - getPaddingTop() - getPaddingBottom();\n final int width = getWidth();\n\n canvas.rotate(270);\n canvas.translate(-height + getPaddingTop(), mFirstOffset * width);\n mLeftEdge.setSize(height, width);\n needsInvalidate |= mLeftEdge.draw(canvas);\n canvas.restoreToCount(restoreCount);\n }\n if (!mRightEdge.isFinished()) {\n final int restoreCount = canvas.save();\n final int width = getWidth();\n final int height = getHeight() - getPaddingTop() - getPaddingBottom();\n\n canvas.rotate(90);\n canvas.translate(-getPaddingTop(), -(mLastOffset + 1) * width);\n mRightEdge.setSize(height, width);\n needsInvalidate |= mRightEdge.draw(canvas);\n canvas.restoreToCount(restoreCount);\n }\n } else {\n mLeftEdge.finish();\n mRightEdge.finish();\n }\n\n if (needsInvalidate) {\n // Keep animating\n ViewCompat.postInvalidateOnAnimation(this);\n }\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n\n // Draw the margin drawable between pages if needed.\n if (mPageMargin > 0 && mMarginDrawable != null && mItems.size() > 0 && mAdapter != null) {\n final int scrollX = getScrollX();\n final int width = getWidth();\n\n final float marginOffset = (float) mPageMargin / width;\n int itemIndex = 0;\n ItemInfo ii = mItems.get(0);\n float offset = ii.offset;\n final int itemCount = mItems.size();\n final int firstPos = ii.position;\n final int lastPos = mItems.get(itemCount - 1).position;\n for (int pos = firstPos; pos < lastPos; pos++) {\n while (pos > ii.position && itemIndex < itemCount) {\n ii = mItems.get(++itemIndex);\n }\n\n float drawAt;\n if (pos == ii.position) {\n drawAt = (ii.offset + ii.widthFactor) * width;\n offset = ii.offset + ii.widthFactor + marginOffset;\n } else {\n float widthFactor = mAdapter.getPageWidth(pos);\n drawAt = (offset + widthFactor) * width;\n offset += widthFactor + marginOffset;\n }\n\n if (drawAt + mPageMargin > scrollX) {\n mMarginDrawable.setBounds((int) drawAt, mTopPageBounds,\n (int) (drawAt + mPageMargin + 0.5f), mBottomPageBounds);\n mMarginDrawable.draw(canvas);\n }\n\n if (drawAt > scrollX + width) {\n break; // No more visible, no sense in continuing\n }\n }\n }\n }\n\n /**\n * Start a fake drag of the pager.\n * /\n * A fake drag can be useful if you want to synchronize the motion of the ViewPager\n * with the touch scrolling of another view, while still letting the ViewPager\n * control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.)\n * Call {@link #fakeDragBy(float)} to simulate the actual drag motion. Call\n * {@link #endFakeDrag()} to complete the fake drag and fling as necessary.\n * /\n * During a fake drag the ViewPager will ignore all touch events. If a real drag\n * is already in progress, this method will return false.\n *\n * @return true if the fake drag began successfully, false if it could not be started.\n * @see #fakeDragBy(float)\n * @see #endFakeDrag()\n */\n public boolean beginFakeDrag() {\n if (mIsBeingDragged) {\n return false;\n }\n mFakeDragging = true;\n setScrollState(SCROLL_STATE_DRAGGING);\n mInitialMotionX = mLastMotionX = 0;\n if (mVelocityTracker == null) {\n mVelocityTracker = VelocityTracker.obtain();\n } else {\n mVelocityTracker.clear();\n }\n final long time = SystemClock.uptimeMillis();\n final MotionEvent ev = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0);\n mVelocityTracker.addMovement(ev);\n ev.recycle();\n mFakeDragBeginTime = time;\n return true;\n }\n\n /**\n * End a fake drag of the pager.\n *\n * @see #beginFakeDrag()\n * @see #fakeDragBy(float)\n */\n public void endFakeDrag() {\n if (!mFakeDragging) {\n throw new IllegalStateException(\"No fake drag in progress. Call beginFakeDrag first.\");\n }\n\n final VelocityTracker velocityTracker = mVelocityTracker;\n velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);\n int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(\n velocityTracker, mActivePointerId);\n mPopulatePending = true;\n final int width = getClientWidth();\n final int scrollX = getScrollX();\n final ItemInfo ii = infoForCurrentScrollPosition();\n final int currentPage = ii.position;\n final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor;\n final int totalDelta = (int) (mLastMotionX - mInitialMotionX);\n int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity,\n totalDelta);\n setCurrentItemInternal(nextPage, true, true, initialVelocity);\n endDrag();\n\n mFakeDragging = false;\n }\n\n /**\n * Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first.\n *\n * @param xOffset Offset in pixels to drag by.\n * @see #beginFakeDrag()\n * @see #endFakeDrag()\n */\n public void fakeDragBy(float xOffset) {\n if (!mFakeDragging) {\n throw new IllegalStateException(\"No fake drag in progress. Call beginFakeDrag first.\");\n }\n\n mLastMotionX += xOffset;\n\n float oldScrollX = getScrollX();\n float scrollX = oldScrollX - xOffset;\n final int width = getClientWidth();\n\n float leftBound = width * mFirstOffset;\n float rightBound = width * mLastOffset;\n\n final ItemInfo firstItem = mItems.get(0);\n final ItemInfo lastItem = mItems.get(mItems.size() - 1);\n if (firstItem.position != 0) {\n leftBound = firstItem.offset * width;\n }\n if (lastItem.position != mAdapter.getCount() - 1) {\n rightBound = lastItem.offset * width;\n }\n\n if (scrollX < leftBound) {\n scrollX = leftBound;\n } else if (scrollX > rightBound) {\n scrollX = rightBound;\n }\n // Don't lose the rounded component\n mLastMotionX += scrollX - (int) scrollX;\n scrollTo((int) scrollX, getScrollY());\n pageScrolled((int) scrollX);\n\n // Synthesize an event for the VelocityTracker.\n final long time = SystemClock.uptimeMillis();\n final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE,\n mLastMotionX, 0, 0);\n mVelocityTracker.addMovement(ev);\n ev.recycle();\n }\n\n /**\n * Returns true if a fake drag is in progress.\n *\n * @return true if currently in a fake drag, false otherwise.\n * @see #beginFakeDrag()\n * @see #fakeDragBy(float)\n * @see #endFakeDrag()\n */\n public boolean isFakeDragging() {\n return mFakeDragging;\n }\n\n private void onSecondaryPointerUp(MotionEvent ev) {\n final int pointerIndex = MotionEventCompat.getActionIndex(ev);\n final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);\n if (pointerId == mActivePointerId) {\n // This was our active pointer going up. Choose a new\n // active pointer and adjust accordingly.\n final int newPointerIndex = pointerIndex == 0 ? 1 : 0;\n mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex);\n mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);\n if (mVelocityTracker != null) {\n mVelocityTracker.clear();\n }\n }\n }\n\n private void endDrag() {\n mIsBeingDragged = false;\n mIsUnableToDrag = false;\n\n if (mVelocityTracker != null) {\n mVelocityTracker.recycle();\n mVelocityTracker = null;\n }\n }\n\n private void setScrollingCacheEnabled(boolean enabled) {\n if (mScrollingCacheEnabled != enabled) {\n mScrollingCacheEnabled = enabled;\n if (USE_CACHE) {\n final int size = getChildCount();\n for (int i = 0; i < size; ++i) {\n final View child = getChildAt(i);\n if (child.getVisibility() != GONE) {\n child.setDrawingCacheEnabled(enabled);\n }\n }\n }\n }\n }\n\n public boolean canScrollHorizontally(int direction) {\n if (mAdapter == null) {\n return false;\n }\n\n final int width = getClientWidth();\n final int scrollX = getScrollX();\n if (direction < 0) {\n return (scrollX > (int) (width * mFirstOffset));\n } else if (direction > 0) {\n return (scrollX < (int) (width * mLastOffset));\n } else {\n return false;\n }\n }\n\n /**\n * Tests scrollability within child views of v given a delta of dx.\n *\n * @param v View to test for horizontal scrollability\n * @param checkV Whether the view v passed should itself be checked for scrollability (true),\n * or just its children (false).\n * @param dx Delta scrolled in pixels\n * @param x X coordinate of the active touch point\n * @param y Y coordinate of the active touch point\n * @return true if child views of v can be scrolled by delta of dx.\n */\n protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {\n if (v instanceof ViewGroup) {\n final ViewGroup group = (ViewGroup) v;\n final int scrollX = v.getScrollX();\n final int scrollY = v.getScrollY();\n final int count = group.getChildCount();\n // Count backwards - let topmost views consume scroll distance first.\n for (int i = count - 1; i >= 0; i--) {\n // TODO: Add versioned support here for transformed views.\n // This will not work for transformed views in Honeycomb+\n final View child = group.getChildAt(i);\n if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() &&\n y + scrollY >= child.getTop() && y + scrollY < child.getBottom() &&\n canScroll(child, true, dx, x + scrollX - child.getLeft(),\n y + scrollY - child.getTop())) {\n return true;\n }\n }\n }\n\n return checkV && ViewCompat.canScrollHorizontally(v, -dx);\n }\n\n @Override\n public boolean dispatchKeyEvent(KeyEvent event) {\n // Let the focused view and/or our descendants get the key first\n return super.dispatchKeyEvent(event) || executeKeyEvent(event);\n }\n\n /**\n * You can call this function yourself to have the scroll view perform\n * scrolling from a key event, just as if the event had been dispatched to\n * it by the view hierarchy.\n *\n * @param event The key event to execute.\n * @return Return true if the event was handled, else false.\n */\n public boolean executeKeyEvent(KeyEvent event) {\n boolean handled = false;\n if (event.getAction() == KeyEvent.ACTION_DOWN) {\n switch (event.getKeyCode()) {\n case KeyEvent.KEYCODE_DPAD_LEFT:\n handled = arrowScroll(FOCUS_LEFT);\n break;\n case KeyEvent.KEYCODE_DPAD_RIGHT:\n handled = arrowScroll(FOCUS_RIGHT);\n break;\n case KeyEvent.KEYCODE_TAB:\n if (Build.VERSION.SDK_INT >= 11) {\n // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD\n // before Android 3.0. Ignore the tab key on those devices.\n if (KeyEventCompat.hasNoModifiers(event)) {\n handled = arrowScroll(FOCUS_FORWARD);\n } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {\n handled = arrowScroll(FOCUS_BACKWARD);\n }\n }\n break;\n }\n }\n return handled;\n }\n\n public boolean arrowScroll(int direction) {\n View currentFocused = findFocus();\n if (currentFocused == this) {\n currentFocused = null;\n } else if (currentFocused != null) {\n boolean isChild = false;\n for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup;\n parent = parent.getParent()) {\n if (parent == this) {\n isChild = true;\n break;\n }\n }\n if (!isChild) {\n // This would cause the focus search down below to fail in fun ways.\n final StringBuilder sb = new StringBuilder();\n sb.append(currentFocused.getClass().getSimpleName());\n for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup;\n parent = parent.getParent()) {\n sb.append(\" => \").append(parent.getClass().getSimpleName());\n }\n Log.e(TAG, \"arrowScroll tried to find focus based on non-child \" +\n \"current focused view \" + sb.toString());\n currentFocused = null;\n }\n }\n\n boolean handled = false;\n\n View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused,\n direction);\n if (nextFocused != null && nextFocused != currentFocused) {\n if (direction == View.FOCUS_LEFT) {\n // If there is nothing to the left, or this is causing us to\n // jump to the right, then what we really want to do is page left.\n final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;\n final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;\n if (currentFocused != null && nextLeft >= currLeft) {\n handled = pageLeft();\n } else {\n handled = nextFocused.requestFocus();\n }\n } else if (direction == View.FOCUS_RIGHT) {\n // If there is nothing to the right, or this is causing us to\n // jump to the left, then what we really want to do is page right.\n final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;\n final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;\n if (currentFocused != null && nextLeft <= currLeft) {\n handled = pageRight();\n } else {\n handled = nextFocused.requestFocus();\n }\n }\n } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) {\n // Trying to move left and nothing there; try to page.\n handled = pageLeft();\n } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) {\n // Trying to move right and nothing there; try to page.\n handled = pageRight();\n }\n if (handled) {\n playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));\n }\n return handled;\n }\n\n private Rect getChildRectInPagerCoordinates(Rect outRect, View child) {\n if (outRect == null) {\n outRect = new Rect();\n }\n if (child == null) {\n outRect.set(0, 0, 0, 0);\n return outRect;\n }\n outRect.left = child.getLeft();\n outRect.right = child.getRight();\n outRect.top = child.getTop();\n outRect.bottom = child.getBottom();\n\n ViewParent parent = child.getParent();\n while (parent instanceof ViewGroup && parent != this) {\n final ViewGroup group = (ViewGroup) parent;\n outRect.left += group.getLeft();\n outRect.right += group.getRight();\n outRect.top += group.getTop();\n outRect.bottom += group.getBottom();\n\n parent = group.getParent();\n }\n return outRect;\n }\n\n boolean pageLeft() {\n if (mCurItem > 0) {\n setCurrentItem(mCurItem - 1, true);\n return true;\n }\n return false;\n }\n\n boolean pageRight() {\n if (mAdapter != null && mCurItem < (mAdapter.getCount() - 1)) {\n setCurrentItem(mCurItem + 1, true);\n return true;\n }\n return false;\n }\n\n /**\n * We only want the current page that is being shown to be focusable.\n */\n @Override\n public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {\n final int focusableCount = views.size();\n\n final int descendantFocusability = getDescendantFocusability();\n\n if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {\n for (int i = 0; i < getChildCount(); i++) {\n final View child = getChildAt(i);\n if (child.getVisibility() == VISIBLE) {\n ItemInfo ii = infoForChild(child);\n if (ii != null && ii.position == mCurItem) {\n child.addFocusables(views, direction, focusableMode);\n }\n }\n }\n }\n\n // we add ourselves (if focusable) in all cases except for when we are\n // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is\n // to avoid the focus search finding layouts when a more precise search\n // among the focusable children would be more interesting.\n if (\n descendantFocusability != FOCUS_AFTER_DESCENDANTS ||\n // No focusable descendants\n (focusableCount == views.size())) {\n // Note that we can't call the superclass here, because it will\n // add all views in. So we need to do the same thing View does.\n if (!isFocusable()) {\n return;\n }\n if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&\n isInTouchMode() && !isFocusableInTouchMode()) {\n return;\n }\n if (views != null) {\n views.add(this);\n }\n }\n }\n\n /**\n * We only want the current page that is being shown to be touchable.\n */\n @Override\n public void addTouchables(ArrayList<View> views) {\n // Note that we don't call super.addTouchables(), which means that\n // we don't call View.addTouchables(). This is okay because a ViewPager\n // is itself not touchable.\n for (int i = 0; i < getChildCount(); i++) {\n final View child = getChildAt(i);\n if (child.getVisibility() == VISIBLE) {\n ItemInfo ii = infoForChild(child);\n if (ii != null && ii.position == mCurItem) {\n child.addTouchables(views);\n }\n }\n }\n }\n\n /**\n * We only want the current page that is being shown to be focusable.\n */\n @Override\n protected boolean onRequestFocusInDescendants(int direction,\n Rect previouslyFocusedRect) {\n int index;\n int increment;\n int end;\n int count = getChildCount();\n if ((direction & FOCUS_FORWARD) != 0) {\n index = 0;\n increment = 1;\n end = count;\n } else {\n index = count - 1;\n increment = -1;\n end = -1;\n }\n for (int i = index; i != end; i += increment) {\n View child = getChildAt(i);\n if (child.getVisibility() == VISIBLE) {\n ItemInfo ii = infoForChild(child);\n if (ii != null && ii.position == mCurItem) {\n if (child.requestFocus(direction, previouslyFocusedRect)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n @Override\n public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {\n // Dispatch scroll events from this ViewPager.\n if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED) {\n return super.dispatchPopulateAccessibilityEvent(event);\n }\n\n // Dispatch all other accessibility events from the current page.\n final int childCount = getChildCount();\n for (int i = 0; i < childCount; i++) {\n final View child = getChildAt(i);\n if (child.getVisibility() == VISIBLE) {\n final ItemInfo ii = infoForChild(child);\n if (ii != null && ii.position == mCurItem &&\n child.dispatchPopulateAccessibilityEvent(event)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n @Override\n protected ViewGroup.LayoutParams generateDefaultLayoutParams() {\n return new LayoutParams();\n }\n\n @Override\n protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {\n return generateDefaultLayoutParams();\n }\n\n @Override\n protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {\n return p instanceof LayoutParams && super.checkLayoutParams(p);\n }\n\n @Override\n public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {\n return new LayoutParams(getContext(), attrs);\n }\n\n class MyAccessibilityDelegate extends AccessibilityDelegateCompat {\n\n @Override\n public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {\n super.onInitializeAccessibilityEvent(host, event);\n event.setClassName(ViewPagerEx.class.getName());\n final AccessibilityRecordCompat recordCompat = AccessibilityRecordCompat.obtain();\n recordCompat.setScrollable(canScroll());\n if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED\n && mAdapter != null) {\n recordCompat.setItemCount(mAdapter.getCount());\n recordCompat.setFromIndex(mCurItem);\n recordCompat.setToIndex(mCurItem);\n }\n }\n\n @Override\n public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {\n super.onInitializeAccessibilityNodeInfo(host, info);\n info.setClassName(ViewPagerEx.class.getName());\n info.setScrollable(canScroll());\n if (canScrollHorizontally(1)) {\n info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);\n }\n if (canScrollHorizontally(-1)) {\n info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);\n }\n }\n\n @Override\n public boolean performAccessibilityAction(View host, int action, Bundle args) {\n if (super.performAccessibilityAction(host, action, args)) {\n return true;\n }\n switch (action) {\n case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: {\n if (canScrollHorizontally(1)) {\n setCurrentItem(mCurItem + 1);\n return true;\n }\n }\n return false;\n case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: {\n if (canScrollHorizontally(-1)) {\n setCurrentItem(mCurItem - 1);\n return true;\n }\n }\n return false;\n }\n return false;\n }\n\n private boolean canScroll() {\n return (mAdapter != null) && (mAdapter.getCount() > 1);\n }\n }\n\n private class PagerObserver extends DataSetObserver {\n @Override\n public void onChanged() {\n dataSetChanged();\n }\n\n @Override\n public void onInvalidated() {\n dataSetChanged();\n }\n }\n\n /**\n * Layout parameters that should be supplied for views added to a\n * ViewPager.\n */\n public static class LayoutParams extends ViewGroup.LayoutParams {\n /**\n * true if this view is a decoration on the pager itself and not\n * a view supplied by the adapter.\n */\n public boolean isDecor;\n\n /**\n * Gravity setting for use on decor views only:\n * Where to position the view page within the overall ViewPager\n * container; constants are defined in {@link android.view.Gravity}.\n */\n public int gravity;\n\n /**\n * Width as a 0-1 multiplier of the measured pager width\n */\n float widthFactor = 0.f;\n\n /**\n * true if this view was added during layout and needs to be measured\n * before being positioned.\n */\n boolean needsMeasure;\n\n /**\n * Adapter position this view is for if !isDecor\n */\n int position;\n\n /**\n * Current child index within the ViewPager that this view occupies\n */\n int childIndex;\n\n public LayoutParams() {\n super(FILL_PARENT, FILL_PARENT);\n }\n\n public LayoutParams(Context context, AttributeSet attrs) {\n super(context, attrs);\n\n final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);\n gravity = a.getInteger(0, Gravity.TOP);\n a.recycle();\n }\n }\n\n static class ViewPositionComparator implements Comparator<View> {\n @Override\n public int compare(View lhs, View rhs) {\n final LayoutParams llp = (LayoutParams) lhs.getLayoutParams();\n final LayoutParams rlp = (LayoutParams) rhs.getLayoutParams();\n if (llp.isDecor != rlp.isDecor) {\n return llp.isDecor ? 1 : -1;\n }\n return llp.position - rlp.position;\n }\n }\n}" ]
import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.support.annotation.IntDef; import android.support.v4.view.PagerAdapter; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.view.animation.Interpolator; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.hkm.slider.Animations.BaseAnimationInterface; import com.hkm.slider.Indicators.NumContainer; import com.hkm.slider.Indicators.PagerIndicator; import com.hkm.slider.SliderTypes.BaseSliderView; import com.hkm.slider.Transformers.BaseTransformer; import com.hkm.slider.Tricks.AnimationHelper; import com.hkm.slider.Tricks.ArrowControl; import com.hkm.slider.Tricks.FixedSpeedScroller; import com.hkm.slider.Tricks.InfinitePagerAdapter; import com.hkm.slider.Tricks.InfiniteViewPager; import com.hkm.slider.Tricks.MultiViewPager; import com.hkm.slider.Tricks.ViewPagerEx; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Timer; import java.util.TimerTask; import static com.hkm.slider.SliderLayout.PresentationConfig.Dots; import static com.hkm.slider.SliderLayout.PresentationConfig.Numbers; import static com.hkm.slider.SliderLayout.PresentationConfig.Smart; import static com.hkm.slider.SliderLayout.PresentationConfig.byVal;
} }; private Handler postHandler = new Handler(); private ImageView mButtonLeft, mButtonRight; private int mLWidthB, mRWidthB; private boolean mLopen, mRopen, button_side_function_flip = false; private ArrowControl arrow_instance; private void navigation_button_initialization() { mButtonLeft = (ImageView) findViewById(R.id.arrow_l); mButtonRight = (ImageView) findViewById(R.id.arrow_r); mButtonLeft.setImageResource(buttondl); mButtonRight.setImageResource(buttondr); arrow_instance = new ArrowControl(mButtonLeft, mButtonRight); mLWidthB = mButtonLeft.getDrawable().getIntrinsicWidth(); mRWidthB = mButtonRight.getDrawable().getIntrinsicWidth(); if (!sidebuttons) { arrow_instance.noSlideButtons(); } else { arrow_instance.setListeners( new OnClickListener() { @Override public void onClick(View v) { if (!button_side_function_flip) moveNextPosition(true); else movePrevPosition(true); } }, new OnClickListener() { @Override public void onClick(View v) { if (!button_side_function_flip) movePrevPosition(true); else moveNextPosition(true); } } ); } mLopen = mRopen = true; } private void notify_navigation_buttons() { arrow_instance.setTotal(mSliderAdapter.getCount()); int count = mSliderAdapter.getCount(); //DisplayMetrics m = getResources().getDisplayMetrics(); // final int width = m.widthPixels; final int end_close_left = -mLWidthB; final int end_close_right = mRWidthB; final int open_left = 0; final int open_right = 0; if (count <= 1) { postHandler.postDelayed(new Runnable() { @Override public void run() { if (mButtonLeft != null && mLopen) { mButtonLeft.animate().translationX(end_close_left); mLopen = false; } if (mButtonRight != null && mRopen) { mButtonRight.animate().translationX(end_close_right); mRopen = false; } } }, mTransitionAnimation); } else { postHandler.postDelayed(new Runnable() { @Override public void run() { if (mButtonLeft != null && !mLopen) { mButtonLeft.animate().translationX(open_left); mLopen = true; } if (mButtonRight != null && !mRopen) { mButtonRight.animate().translationX(open_right); mRopen = true; } } }, mTransitionAnimation); } } public SliderLayout setType(final @SliderLayoutType int t) { pagerType = t; return this; } public SliderLayout setActivity(final Activity t) { activity = t; return this; } private void pagerSetup() { mSliderAdapter = new SliderAdapter(mContext); if (pagerType == NONZOOMABLE) { PagerAdapter wrappedAdapter = new InfinitePagerAdapter(mSliderAdapter); mViewPager = (InfiniteViewPager) findViewById(R.id.daimajia_slider_viewpager); if (mPagerMargin > -1) { mViewPager.setMargin(mPagerMargin); } mViewPager.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_UP: recoverCycle(); break; } return false; } }); mViewPager.setAdapter(wrappedAdapter); } else if (pagerType == ZOOMABLE) { } mSliderAdapter.registerDataSetObserver(sliderDataObserver); }
public <TN extends NumContainer> void setNumLayout(final TN container) {
1
stridercheng/chatui
app/src/main/java/com/rance/chatui/adapter/ChatAdapter.java
[ "public class BaseViewHolder<M> extends RecyclerView.ViewHolder {\n\n public BaseViewHolder(View itemView) {\n super(itemView);\n }\n\n public void setData(M data) {\n\n }\n}", "public class ChatAcceptViewHolder extends BaseViewHolder<MessageInfo> {\n private static final String TAG = \"ChatAcceptViewHolder\";\n TextView chatItemDate;\n ImageView chatItemHeader;\n GifTextView chatItemContentText;\n BubbleImageView chatItemContentImage;\n ImageView chatItemVoice;\n BubbleLinearLayout chatItemLayoutContent;\n TextView chatItemVoiceTime;\n BubbleLinearLayout chatItemLayoutFile;\n ImageView ivFileType;\n TextView tvFileName;\n TextView tvFileSize;\n\n BubbleLinearLayout chatItemLayoutContact;\n TextView tvContactSurname;\n TextView tvContactName;\n TextView tvContactPhone;\n\n BubbleLinearLayout chatItemLayoutLink;\n TextView tvLinkSubject;\n TextView tvLinkText;\n ImageView ivLinkPicture;\n private ChatAdapter.onItemClickListener onItemClickListener;\n private Handler handler;\n private RelativeLayout.LayoutParams layoutParams;\n private Context mContext;\n\n public ChatAcceptViewHolder(ViewGroup parent, ChatAdapter.onItemClickListener onItemClickListener, Handler handler) {\n super(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_accept, parent, false));\n findViewByIds(itemView);\n setItemLongClick();\n setItemClick();\n this.mContext = parent.getContext();\n this.onItemClickListener = onItemClickListener;\n this.handler = handler;\n layoutParams = (RelativeLayout.LayoutParams) chatItemLayoutContent.getLayoutParams();\n }\n\n private void findViewByIds(View itemView) {\n chatItemDate = (TextView) itemView.findViewById(R.id.chat_item_date);\n chatItemHeader = (ImageView) itemView.findViewById(R.id.chat_item_header);\n chatItemContentText = (GifTextView) itemView.findViewById(R.id.chat_item_content_text);\n chatItemContentImage = (BubbleImageView) itemView.findViewById(R.id.chat_item_content_image);\n chatItemVoice = (ImageView) itemView.findViewById(R.id.chat_item_voice);\n chatItemLayoutContent = (BubbleLinearLayout) itemView.findViewById(R.id.chat_item_layout_content);\n chatItemVoiceTime = (TextView) itemView.findViewById(R.id.chat_item_voice_time);\n chatItemLayoutFile = (BubbleLinearLayout) itemView.findViewById(R.id.chat_item_layout_file);\n ivFileType = (ImageView) itemView.findViewById(R.id.iv_file_type);\n tvFileName = (TextView) itemView.findViewById(R.id.tv_file_name);\n tvFileSize = (TextView) itemView.findViewById(R.id.tv_file_size);\n chatItemLayoutContact = (BubbleLinearLayout) itemView.findViewById(R.id.chat_item_layout_contact);\n tvContactSurname = (TextView) itemView.findViewById(R.id.tv_contact_surname);\n tvContactPhone = (TextView) itemView.findViewById(R.id.tv_contact_phone);\n chatItemLayoutLink = (BubbleLinearLayout) itemView.findViewById(R.id.chat_item_layout_link);\n tvLinkSubject = (TextView) itemView.findViewById(R.id.tv_link_subject);\n tvLinkText = (TextView) itemView.findViewById(R.id.tv_link_text);\n ivLinkPicture = (ImageView) itemView.findViewById(R.id.iv_link_picture);\n }\n\n @Override\n public void setData(MessageInfo data) {\n chatItemDate.setText(data.getTime() != null ? data.getTime() : \"\");\n Glide.with(mContext).load(data.getHeader()).into(chatItemHeader);\n chatItemHeader.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onHeaderClick((Integer) itemView.getTag());\n }\n });\n switch (data.getFileType()) {\n case Constants.CHAT_FILE_TYPE_TEXT:\n chatItemContentText.setSpanText(handler, data.getContent(), true);\n chatItemVoice.setVisibility(View.GONE);\n chatItemContentText.setVisibility(View.VISIBLE);\n chatItemLayoutContent.setVisibility(View.VISIBLE);\n chatItemVoiceTime.setVisibility(View.GONE);\n chatItemContentImage.setVisibility(View.GONE);\n chatItemLayoutContact.setVisibility(View.GONE);\n\n TextPaint paint = chatItemContentText.getPaint();\n // 计算textview在屏幕上占多宽\n int len = (int) paint.measureText(chatItemContentText.getText().toString().trim());\n if (len < Utils.dp2px(mContext, 200)){\n layoutParams.width = len + Utils.dp2px(mContext, 30);\n } else {\n layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;\n }\n layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;\n chatItemLayoutContent.setLayoutParams(layoutParams);\n break;\n case Constants.CHAT_FILE_TYPE_IMAGE:\n chatItemVoice.setVisibility(View.GONE);\n chatItemLayoutContent.setVisibility(View.GONE);\n chatItemVoiceTime.setVisibility(View.GONE);\n chatItemContentText.setVisibility(View.GONE);\n chatItemContentImage.setVisibility(View.VISIBLE);\n chatItemLayoutContact.setVisibility(View.GONE);\n\n Glide.with(mContext).load(data.getFilepath()).into(chatItemContentImage);\n chatItemContentImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onImageClick(chatItemContentImage, (Integer) itemView.getTag());\n }\n });\n layoutParams.width = Utils.dp2px(mContext, 120);\n layoutParams.height = Utils.dp2px(mContext, 48);\n chatItemLayoutContent.setLayoutParams(layoutParams);\n break;\n case Constants.CHAT_FILE_TYPE_VOICE:\n chatItemVoice.setVisibility(View.VISIBLE);\n chatItemLayoutContent.setVisibility(View.VISIBLE);\n chatItemContentText.setVisibility(View.GONE);\n chatItemVoiceTime.setVisibility(View.VISIBLE);\n chatItemContentImage.setVisibility(View.GONE);\n chatItemLayoutContact.setVisibility(View.GONE);\n\n chatItemVoiceTime.setText(Utils.formatTime(data.getVoiceTime()));\n chatItemLayoutContent.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onVoiceClick(chatItemVoice, (Integer) itemView.getTag());\n }\n });\n layoutParams.width = Utils.dp2px(mContext, 120);\n layoutParams.height = Utils.dp2px(mContext, 48);\n chatItemLayoutContent.setLayoutParams(layoutParams);\n break;\n case Constants.CHAT_FILE_TYPE_FILE:\n chatItemVoice.setVisibility(View.GONE);\n chatItemContentText.setVisibility(View.GONE);\n chatItemContentImage.setVisibility(View.GONE);\n chatItemVoiceTime.setVisibility(View.GONE);\n chatItemLayoutContent.setVisibility(View.GONE);\n chatItemLayoutContact.setVisibility(View.GONE);\n\n// chatItemLayoutContent.setVisibility(View.VISIBLE);\n chatItemLayoutFile.setVisibility(View.VISIBLE);\n tvFileName.setText(FileUtils.getFileName(data.getFilepath()));\n try {\n tvFileSize.setText(FileUtils.getFileSize(data.getFilepath()));\n switch (FileUtils.getExtensionName(data.getFilepath())) {\n case \"doc\":\n case \"docx\":\n ivFileType.setImageResource(R.mipmap.icon_file_word);\n break;\n case \"ppt\":\n case \"pptx\":\n ivFileType.setImageResource(R.mipmap.icon_file_ppt);\n break;\n case \"xls\":\n case \"xlsx\":\n ivFileType.setImageResource(R.mipmap.icon_file_excel);\n break;\n case \"pdf\":\n ivFileType.setImageResource(R.mipmap.icon_file_pdf);\n break;\n default:\n ivFileType.setImageResource(R.mipmap.icon_file_other);\n break;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n break;\n case Constants.CHAT_FILE_TYPE_CONTACT:\n chatItemVoice.setVisibility(View.GONE);\n chatItemContentText.setVisibility(View.GONE);\n chatItemContentImage.setVisibility(View.GONE);\n chatItemVoiceTime.setVisibility(View.GONE);\n chatItemLayoutContent.setVisibility(View.GONE);\n chatItemLayoutFile.setVisibility(View.GONE);\n\n chatItemLayoutContact.setVisibility(View.VISIBLE);\n\n IMContact imContact = (IMContact) data.getObject();\n tvContactSurname.setText(imContact.getSurname());\n tvContactName.setText(imContact.getName());\n tvContactPhone.setText(imContact.getPhonenumber());\n break;\n case Constants.CHAT_FILE_TYPE_LINK:\n chatItemVoice.setVisibility(View.GONE);\n chatItemContentText.setVisibility(View.GONE);\n chatItemContentImage.setVisibility(View.GONE);\n chatItemVoiceTime.setVisibility(View.GONE);\n chatItemLayoutContent.setVisibility(View.GONE);\n chatItemLayoutFile.setVisibility(View.GONE);\n chatItemLayoutContact.setVisibility(View.GONE);\n\n chatItemLayoutLink.setVisibility(View.VISIBLE);\n Link link = (Link) data.getObject();\n\n tvLinkSubject.setText(link.getSubject());\n tvLinkText.setText(link.getText());\n Glide.with(mContext).load(link.getStream()).into(ivLinkPicture);\n break;\n }\n }\n\n public void setItemLongClick() {\n chatItemContentImage.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n onItemClickListener.onLongClickImage(v, (Integer) itemView.getTag());\n return true;\n }\n });\n chatItemContentText.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n onItemClickListener.onLongClickText(v, (Integer) itemView.getTag());\n return true;\n }\n });\n chatItemLayoutContent.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n onItemClickListener.onLongClickItem(v, (Integer) itemView.getTag());\n return true;\n }\n });\n chatItemLayoutFile.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n onItemClickListener.onLongClickFile(v, (Integer) itemView.getTag());\n return true;\n }\n });\n }\n\n public void setItemClick() {\n chatItemContentImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onImageClick(chatItemContentImage, (Integer) itemView.getTag());\n }\n });\n\n chatItemLayoutFile.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onVoiceClick(chatItemVoice, (Integer) itemView.getTag());\n }\n });\n\n chatItemLayoutFile.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onFileClick(v, (Integer) itemView.getTag());\n }\n });\n\n chatItemLayoutLink.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onLinkClick(v, (Integer) itemView.getTag());\n }\n });\n }\n}", "public class ChatSendViewHolder extends BaseViewHolder<MessageInfo> {\n private static final String TAG = \"ChatSendViewHolder\";\n TextView chatItemDate;\n ImageView chatItemHeader;\n GifTextView chatItemContentText;\n BubbleImageView chatItemContentImage;\n ImageView chatItemFail;\n ProgressBar chatItemProgress;\n ImageView chatItemVoice;\n BubbleLinearLayout chatItemLayoutContent;\n TextView chatItemVoiceTime;\n BubbleLinearLayout chatItemLayoutFile;\n ImageView ivFileType;\n TextView tvFileName;\n TextView tvFileSize;\n\n BubbleLinearLayout chatItemLayoutContact;\n TextView tvContactSurname;\n TextView tvContactName;\n TextView tvContactPhone;\n\n BubbleLinearLayout chatItemLayoutLink;\n TextView tvLinkSubject;\n TextView tvLinkText;\n ImageView ivLinkPicture;\n private ChatAdapter.onItemClickListener onItemClickListener;\n private Handler handler;\n private RelativeLayout.LayoutParams layoutParams;\n private Context mContext;\n\n public ChatSendViewHolder(ViewGroup parent, ChatAdapter.onItemClickListener onItemClickListener, Handler handler) {\n super(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_send, parent, false));\n findViewByIds(itemView);\n setItemLongClick();\n setItemClick();\n this.mContext = parent.getContext();\n this.onItemClickListener = onItemClickListener;\n this.handler = handler;\n layoutParams = (RelativeLayout.LayoutParams) chatItemLayoutContent.getLayoutParams();\n }\n\n private void findViewByIds(View itemView) {\n chatItemDate = (TextView) itemView.findViewById(R.id.chat_item_date);\n chatItemHeader = (ImageView) itemView.findViewById(R.id.chat_item_header);\n chatItemContentText = (GifTextView) itemView.findViewById(R.id.chat_item_content_text);\n chatItemFail = (ImageView) itemView.findViewById(R.id.chat_item_fail);\n chatItemProgress = (ProgressBar) itemView.findViewById(R.id.chat_item_progress);\n chatItemContentImage = (BubbleImageView) itemView.findViewById(R.id.chat_item_content_image);\n chatItemVoice = (ImageView) itemView.findViewById(R.id.chat_item_voice);\n chatItemLayoutContent = (BubbleLinearLayout) itemView.findViewById(R.id.chat_item_layout_content);\n chatItemVoiceTime = (TextView) itemView.findViewById(R.id.chat_item_voice_time);\n chatItemLayoutFile = (BubbleLinearLayout) itemView.findViewById(R.id.chat_item_layout_file);\n ivFileType = (ImageView) itemView.findViewById(R.id.iv_file_type);\n tvFileName = (TextView) itemView.findViewById(R.id.tv_file_name);\n tvFileSize = (TextView) itemView.findViewById(R.id.tv_file_size);\n chatItemLayoutContact = (BubbleLinearLayout) itemView.findViewById(R.id.chat_item_layout_contact);\n tvContactSurname = (TextView) itemView.findViewById(R.id.tv_contact_surname);\n tvContactPhone = (TextView) itemView.findViewById(R.id.tv_contact_phone);\n chatItemLayoutLink = (BubbleLinearLayout) itemView.findViewById(R.id.chat_item_layout_link);\n tvLinkSubject = (TextView) itemView.findViewById(R.id.tv_link_subject);\n tvLinkText = (TextView) itemView.findViewById(R.id.tv_link_text);\n ivLinkPicture = (ImageView) itemView.findViewById(R.id.iv_link_picture);\n }\n\n\n @Override\n public void setData(MessageInfo data) {\n chatItemDate.setText(data.getTime() != null ? data.getTime() : \"\");\n Glide.with(mContext).load(data.getHeader()).into(chatItemHeader);\n chatItemHeader.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onHeaderClick((Integer) itemView.getTag());\n }\n });\n switch (data.getFileType()) {\n case Constants.CHAT_FILE_TYPE_TEXT:\n chatItemContentText.setSpanText(handler, data.getContent(), true);\n chatItemVoice.setVisibility(View.GONE);\n chatItemVoiceTime.setVisibility(View.GONE);\n chatItemContentImage.setVisibility(View.GONE);\n chatItemLayoutFile.setVisibility(View.GONE);\n chatItemLayoutContact.setVisibility(View.GONE);\n chatItemLayoutLink.setVisibility(View.GONE);\n\n chatItemContentText.setVisibility(View.VISIBLE);\n chatItemLayoutContent.setVisibility(View.VISIBLE);\n TextPaint paint = chatItemContentText.getPaint();\n paint.setColor(ContextCompat.getColor(mContext, R.color.chat_send_text));\n // 计算textview在屏幕上占多宽\n int len = (int) paint.measureText(chatItemContentText.getText().toString().trim());\n if (len < Utils.dp2px(mContext, 200)){\n layoutParams.width = len + Utils.dp2px(mContext, 30);\n } else {\n layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;\n }\n layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;\n chatItemLayoutContent.setLayoutParams(layoutParams);\n break;\n case Constants.CHAT_FILE_TYPE_IMAGE:\n chatItemVoice.setVisibility(View.GONE);\n chatItemLayoutContent.setVisibility(View.GONE);\n chatItemVoiceTime.setVisibility(View.GONE);\n chatItemContentText.setVisibility(View.GONE);\n chatItemLayoutFile.setVisibility(View.GONE);\n chatItemLayoutContact.setVisibility(View.GONE);\n chatItemLayoutLink.setVisibility(View.GONE);\n\n chatItemContentImage.setVisibility(View.VISIBLE);\n Glide.with(mContext).load(data.getFilepath()).into(chatItemContentImage);\n layoutParams.width = Utils.dp2px(mContext, 120);\n layoutParams.height = Utils.dp2px(mContext, 48);\n chatItemLayoutContent.setLayoutParams(layoutParams);\n break;\n case Constants.CHAT_FILE_TYPE_VOICE:\n chatItemVoice.setVisibility(View.VISIBLE);\n chatItemLayoutContent.setVisibility(View.VISIBLE);\n chatItemContentText.setVisibility(View.GONE);\n chatItemVoiceTime.setVisibility(View.VISIBLE);\n chatItemContentImage.setVisibility(View.GONE);\n chatItemLayoutContact.setVisibility(View.GONE);\n chatItemLayoutLink.setVisibility(View.GONE);\n\n chatItemLayoutFile.setVisibility(View.GONE);\n chatItemVoiceTime.setText(Utils.formatTime(data.getVoiceTime()));\n layoutParams.width = Utils.dp2px(mContext, 120);\n layoutParams.height = Utils.dp2px(mContext, 48);\n chatItemLayoutContent.setLayoutParams(layoutParams);\n break;\n case Constants.CHAT_FILE_TYPE_FILE:\n chatItemVoice.setVisibility(View.GONE);\n chatItemContentText.setVisibility(View.GONE);\n chatItemContentImage.setVisibility(View.GONE);\n chatItemVoiceTime.setVisibility(View.GONE);\n chatItemLayoutContent.setVisibility(View.GONE);\n chatItemLayoutContact.setVisibility(View.GONE);\n chatItemLayoutLink.setVisibility(View.GONE);\n\n chatItemLayoutFile.setVisibility(View.VISIBLE);\n tvFileName.setText(FileUtils.getFileName(data.getFilepath()));\n try {\n tvFileSize.setText(FileUtils.getFileSize(data.getFilepath()));\n switch (FileUtils.getExtensionName(data.getFilepath())) {\n case \"doc\":\n case \"docx\":\n ivFileType.setImageResource(R.mipmap.icon_file_word);\n break;\n case \"ppt\":\n case \"pptx\":\n ivFileType.setImageResource(R.mipmap.icon_file_ppt);\n break;\n case \"xls\":\n case \"xlsx\":\n ivFileType.setImageResource(R.mipmap.icon_file_excel);\n break;\n case \"pdf\":\n ivFileType.setImageResource(R.mipmap.icon_file_pdf);\n break;\n default:\n ivFileType.setImageResource(R.mipmap.icon_file_other);\n break;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n break;\n case Constants.CHAT_FILE_TYPE_CONTACT:\n chatItemVoice.setVisibility(View.GONE);\n chatItemContentText.setVisibility(View.GONE);\n chatItemContentImage.setVisibility(View.GONE);\n chatItemVoiceTime.setVisibility(View.GONE);\n chatItemLayoutContent.setVisibility(View.GONE);\n chatItemLayoutFile.setVisibility(View.GONE);\n\n chatItemLayoutContact.setVisibility(View.VISIBLE);\n\n IMContact imContact = (IMContact) data.getObject();\n tvContactSurname.setText(imContact.getSurname());\n tvContactName.setText(imContact.getName());\n tvContactPhone.setText(imContact.getPhonenumber());\n break;\n case Constants.CHAT_FILE_TYPE_LINK:\n chatItemVoice.setVisibility(View.GONE);\n chatItemContentText.setVisibility(View.GONE);\n chatItemContentImage.setVisibility(View.GONE);\n chatItemVoiceTime.setVisibility(View.GONE);\n chatItemLayoutContent.setVisibility(View.GONE);\n chatItemLayoutFile.setVisibility(View.GONE);\n chatItemLayoutContact.setVisibility(View.GONE);\n\n chatItemLayoutLink.setVisibility(View.VISIBLE);\n Link link = (Link) data.getObject();\n\n tvLinkSubject.setText(link.getSubject());\n tvLinkText.setText(link.getText());\n Glide.with(mContext).load(link.getStream()).into(ivLinkPicture);\n break;\n }\n switch (data.getSendState()) {\n case Constants.CHAT_ITEM_SENDING:\n chatItemProgress.setVisibility(View.VISIBLE);\n chatItemFail.setVisibility(View.GONE);\n break;\n case Constants.CHAT_ITEM_SEND_ERROR:\n chatItemProgress.setVisibility(View.GONE);\n chatItemFail.setVisibility(View.VISIBLE);\n break;\n case Constants.CHAT_ITEM_SEND_SUCCESS:\n chatItemProgress.setVisibility(View.GONE);\n chatItemFail.setVisibility(View.GONE);\n break;\n }\n }\n\n public void setItemLongClick() {\n chatItemContentImage.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n onItemClickListener.onLongClickImage(v, (Integer) itemView.getTag());\n return true;\n }\n });\n chatItemContentText.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n onItemClickListener.onLongClickText(v, (Integer) itemView.getTag());\n return true;\n }\n });\n chatItemLayoutContent.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n onItemClickListener.onLongClickItem(v, (Integer) itemView.getTag());\n return true;\n }\n });\n chatItemLayoutFile.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n onItemClickListener.onLongClickFile(v, (Integer) itemView.getTag());\n return true;\n }\n });\n }\n\n public void setItemClick() {\n chatItemContentImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onImageClick(chatItemContentImage, (Integer) itemView.getTag());\n }\n });\n\n chatItemLayoutFile.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onVoiceClick(chatItemVoice, (Integer) itemView.getTag());\n }\n });\n\n chatItemLayoutFile.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onFileClick(v, (Integer) itemView.getTag());\n }\n });\n\n chatItemLayoutLink.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClickListener.onLinkClick(v, (Integer) itemView.getTag());\n }\n });\n }\n}", "public class MessageInfo {\n private int type;\n private String content;\n private String filepath;\n private int sendState;\n private String time;\n private String header;\n private long voiceTime;\n private String msgId;\n private String fileType;\n private Object object;\n private String mimeType;\n\n public Object getObject() {\n return object;\n }\n\n public void setObject(Object object) {\n this.object = object;\n }\n\n public String getFileType() {\n return fileType;\n }\n\n public void setFileType(String fileType) {\n this.fileType = fileType;\n }\n\n public int getType() {\n return type;\n }\n\n public void setType(int type) {\n this.type = type;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public String getFilepath() {\n return filepath;\n }\n\n public void setFilepath(String filepath) {\n this.filepath = filepath;\n }\n\n public int getSendState() {\n return sendState;\n }\n\n public void setSendState(int sendState) {\n this.sendState = sendState;\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 String getHeader() {\n return header;\n }\n\n public void setHeader(String header) {\n this.header = header;\n }\n\n public long getVoiceTime() {\n return voiceTime;\n }\n\n public void setVoiceTime(long voiceTime) {\n this.voiceTime = voiceTime;\n }\n\n public String getMsgId() {\n return msgId;\n }\n\n public void setMsgId(String msgId) {\n this.msgId = msgId;\n }\n\n public String getMimeType() {\n return mimeType;\n }\n\n public void setMimeType(String mimeType) {\n this.mimeType = mimeType;\n }\n\n @Override\n public String toString() {\n return \"MessageInfo{\" +\n \"type=\" + type +\n \", content='\" + content + '\\'' +\n \", filepath='\" + filepath + '\\'' +\n \", sendState=\" + sendState +\n \", time='\" + time + '\\'' +\n \", header='\" + header + '\\'' +\n \", mimeType='\" + mimeType + '\\'' +\n \", voiceTime=\" + voiceTime +\n \", msgId='\" + msgId + '\\'' +\n \", fileType='\" + fileType + '\\'' +\n \", object=\" + object +\n '}';\n }\n}", "public class Constants {\n public static final String TAG = \"rance\";\n public static final String AUTHORITY = \"com.chatui.fileprovider\";\n /** 0x001-接受消息 0x002-发送消息**/\n public static final int CHAT_ITEM_TYPE_LEFT = 0x001;\n public static final int CHAT_ITEM_TYPE_RIGHT = 0x002;\n /** 0x003-发送中 0x004-发送失败 0x005-发送成功**/\n public static final int CHAT_ITEM_SENDING = 0x003;\n public static final int CHAT_ITEM_SEND_ERROR = 0x004;\n public static final int CHAT_ITEM_SEND_SUCCESS = 0x005;\n\n public static final String CHAT_FILE_TYPE_TEXT = \"text\";\n public static final String CHAT_FILE_TYPE_FILE = \"file\";\n public static final String CHAT_FILE_TYPE_IMAGE = \"image\";\n public static final String CHAT_FILE_TYPE_VOICE = \"voice\";\n public static final String CHAT_FILE_TYPE_CONTACT = \"contact\";\n public static final String CHAT_FILE_TYPE_LINK = \"LINK\";\n}" ]
import android.os.Handler; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.rance.chatui.adapter.holder.BaseViewHolder; import com.rance.chatui.adapter.holder.ChatAcceptViewHolder; import com.rance.chatui.adapter.holder.ChatSendViewHolder; import com.rance.chatui.enity.MessageInfo; import com.rance.chatui.util.Constants; import java.util.ArrayList; import java.util.List;
package com.rance.chatui.adapter; /** * 作者:Rance on 2016/11/29 10:46 * 邮箱:[email protected] */ public class ChatAdapter extends RecyclerView.Adapter<BaseViewHolder> { private onItemClickListener onItemClickListener; public Handler handler; private List<MessageInfo> messageInfoList; public ChatAdapter(List<MessageInfo> messageInfoList) { handler = new Handler(); this.messageInfoList = messageInfoList; } // @Override // public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { // BaseViewHolder viewHolder = null; // switch (viewType) { // case Constants.CHAT_ITEM_TYPE_LEFT: // viewHolder = new ChatAcceptViewHolder(parent, onItemClickListener, handler); // break; // case Constants.CHAT_ITEM_TYPE_RIGHT: // viewHolder = new ChatSendViewHolder(parent, onItemClickListener, handler); // break; // } // return viewHolder; // } // // @Override // public int getViewType(int position) { // return getAllData().get(position).getType(); // } public void addItemClickListener(onItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } @Override public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { BaseViewHolder viewHolder = null; switch (viewType) { case Constants.CHAT_ITEM_TYPE_LEFT: viewHolder = new ChatAcceptViewHolder(parent, onItemClickListener, handler); break; case Constants.CHAT_ITEM_TYPE_RIGHT:
viewHolder = new ChatSendViewHolder(parent, onItemClickListener, handler);
2
rubenlagus/Tsupport
TMessagesProj/src/main/java/org/telegram/ui/ChangeChatNameActivity.java
[ "public class AndroidUtilities {\n\n private static final Hashtable<String, Typeface> typefaceCache = new Hashtable<>();\n private static int prevOrientation = -10;\n private static boolean waitingForSms = false;\n private static final Object smsLock = new Object();\n\n public static int statusBarHeight = 0;\n public static float density = 1;\n public static Point displaySize = new Point();\n public static Integer photoSize = null;\n public static DisplayMetrics displayMetrics = new DisplayMetrics();\n private static Boolean isTablet = null;\n\n static {\n density = ApplicationLoader.applicationContext.getResources().getDisplayMetrics().density;\n checkDisplaySize();\n }\n\n public static void lockOrientation(Activity activity) {\n if (activity == null || prevOrientation != -10 || Build.VERSION.SDK_INT < 9) {\n return;\n }\n try {\n prevOrientation = activity.getRequestedOrientation();\n WindowManager manager = (WindowManager)activity.getSystemService(Activity.WINDOW_SERVICE);\n if (manager != null && manager.getDefaultDisplay() != null) {\n int rotation = manager.getDefaultDisplay().getRotation();\n int orientation = activity.getResources().getConfiguration().orientation;\n int SCREEN_ORIENTATION_REVERSE_LANDSCAPE = 8;\n int SCREEN_ORIENTATION_REVERSE_PORTRAIT = 9;\n if (Build.VERSION.SDK_INT < 9) {\n SCREEN_ORIENTATION_REVERSE_LANDSCAPE = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;\n SCREEN_ORIENTATION_REVERSE_PORTRAIT = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;\n }\n\n if (rotation == Surface.ROTATION_270) {\n if (orientation == Configuration.ORIENTATION_PORTRAIT) {\n activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);\n } else {\n activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_LANDSCAPE);\n }\n } else if (rotation == Surface.ROTATION_90) {\n if (orientation == Configuration.ORIENTATION_PORTRAIT) {\n activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_PORTRAIT);\n } else {\n activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);\n }\n } else if (rotation == Surface.ROTATION_0) {\n if (orientation == Configuration.ORIENTATION_LANDSCAPE) {\n activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);\n } else {\n activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);\n }\n } else {\n if (orientation == Configuration.ORIENTATION_LANDSCAPE) {\n activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_LANDSCAPE);\n } else {\n activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_PORTRAIT);\n }\n }\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n\n public static void unlockOrientation(Activity activity) {\n if (activity == null || Build.VERSION.SDK_INT < 9) {\n return;\n }\n try {\n if (prevOrientation != -10) {\n activity.setRequestedOrientation(prevOrientation);\n prevOrientation = -10;\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n\n public static Typeface getTypeface(String assetPath) {\n synchronized (typefaceCache) {\n if (!typefaceCache.containsKey(assetPath)) {\n try {\n Typeface t = Typeface.createFromAsset(ApplicationLoader.applicationContext.getAssets(), assetPath);\n typefaceCache.put(assetPath, t);\n } catch (Exception e) {\n FileLog.e(\"Typefaces\", \"Could not get typeface '\" + assetPath + \"' because \" + e.getMessage());\n return null;\n }\n }\n return typefaceCache.get(assetPath);\n }\n }\n\n public static boolean isWaitingForSms() {\n boolean value = false;\n synchronized (smsLock) {\n value = waitingForSms;\n }\n return value;\n }\n\n public static void setWaitingForSms(boolean value) {\n synchronized (smsLock) {\n waitingForSms = value;\n }\n }\n\n public static void showKeyboard(View view) {\n if (view == null) {\n return;\n }\n InputMethodManager inputManager = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);\n }\n\n public static boolean isKeyboardShowed(View view) {\n if (view == null) {\n return false;\n }\n InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n return inputManager.isActive(view);\n }\n\n public static void hideKeyboard(View view) {\n if (view == null) {\n return;\n }\n InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n if (!imm.isActive()) {\n return;\n }\n imm.hideSoftInputFromWindow(view.getWindowToken(), 0);\n }\n\n public static File getCacheDir() {\n String state = null;\n try {\n state = Environment.getExternalStorageState();\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n if (state == null || state.startsWith(Environment.MEDIA_MOUNTED)) {\n try {\n File file = ApplicationLoader.applicationContext.getExternalCacheDir();\n if (file != null) {\n return file;\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n try {\n File file = ApplicationLoader.applicationContext.getCacheDir();\n if (file != null) {\n return file;\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n return new File(\"\");\n }\n\n public static int dp(float value) {\n return (int)Math.ceil(density * value);\n }\n\n public static float dpf2(float value) {\n return density * value;\n }\n\n public static void checkDisplaySize() {\n try {\n WindowManager manager = (WindowManager)ApplicationLoader.applicationContext.getSystemService(Context.WINDOW_SERVICE);\n if (manager != null) {\n Display display = manager.getDefaultDisplay();\n if (display != null) {\n display.getMetrics(displayMetrics);\n if(android.os.Build.VERSION.SDK_INT < 13) {\n displaySize.set(display.getWidth(), display.getHeight());\n } else {\n display.getSize(displaySize);\n }\n FileLog.e(\"tmessages\", \"display size = \" + displaySize.x + \" \" + displaySize.y + \" \" + displayMetrics.xdpi + \"x\" + displayMetrics.ydpi);\n }\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n\n public static float getPixelsInCM(float cm, boolean isX) {\n return (cm / 2.54f) * (isX ? displayMetrics.xdpi : displayMetrics.ydpi);\n }\n\n public static long makeBroadcastId(int id) {\n return 0x0000000100000000L | ((long)id & 0x00000000FFFFFFFFL);\n }\n\n public static int getMyLayerVersion(int layer) {\n return layer & 0xffff;\n }\n\n public static int getPeerLayerVersion(int layer) {\n return (layer >> 16) & 0xffff;\n }\n\n public static int setMyLayerVersion(int layer, int version) {\n return layer & 0xffff0000 | version;\n }\n\n public static int setPeerLayerVersion(int layer, int version) {\n return layer & 0x0000ffff | (version << 16);\n }\n\n public static void runOnUIThread(Runnable runnable) {\n runOnUIThread(runnable, 0);\n }\n\n public static void runOnUIThread(Runnable runnable, long delay) {\n if (delay == 0) {\n ApplicationLoader.applicationHandler.post(runnable);\n } else {\n ApplicationLoader.applicationHandler.postDelayed(runnable, delay);\n }\n }\n\n public static void cancelRunOnUIThread(Runnable runnable) {\n ApplicationLoader.applicationHandler.removeCallbacks(runnable);\n }\n\n public static boolean isTablet() {\n if (isTablet == null) {\n isTablet = ApplicationLoader.applicationContext.getResources().getBoolean(R.bool.isTablet);\n }\n return isTablet;\n }\n\n public static boolean isSmallTablet() {\n float minSide = Math.min(displaySize.x, displaySize.y) / density;\n return minSide <= 700;\n }\n\n public static int getMinTabletSide() {\n if (!isSmallTablet()) {\n int smallSide = Math.min(displaySize.x, displaySize.y);\n int leftSide = smallSide * 35 / 100;\n if (leftSide < dp(320)) {\n leftSide = dp(320);\n }\n return smallSide - leftSide;\n } else {\n int smallSide = Math.min(displaySize.x, displaySize.y);\n int maxSide = Math.max(displaySize.x, displaySize.y);\n int leftSide = maxSide * 35 / 100;\n if (leftSide < dp(320)) {\n leftSide = dp(320);\n }\n return Math.min(smallSide, maxSide - leftSide);\n }\n }\n\n public static int getPhotoSize() {\n if (photoSize == null) {\n if (Build.VERSION.SDK_INT >= 16) {\n photoSize = 1280;\n } else {\n photoSize = 800;\n }\n }\n return photoSize;\n }\n\n public static String formatTTLString(int ttl) {\n if (ttl < 60) {\n return LocaleController.formatPluralString(\"Seconds\", ttl);\n } else if (ttl < 60 * 60) {\n return LocaleController.formatPluralString(\"Minutes\", ttl / 60);\n } else if (ttl < 60 * 60 * 24) {\n return LocaleController.formatPluralString(\"Hours\", ttl / 60 / 60);\n } else if (ttl < 60 * 60 * 24 * 7) {\n return LocaleController.formatPluralString(\"Days\", ttl / 60 / 60 / 24);\n } else {\n int days = ttl / 60 / 60 / 24;\n if (ttl % 7 == 0) {\n return LocaleController.formatPluralString(\"Weeks\", days / 7);\n } else {\n return String.format(\"%s %s\", LocaleController.formatPluralString(\"Weeks\", days / 7), LocaleController.formatPluralString(\"Days\", days % 7));\n }\n }\n }\n\n public static AlertDialog.Builder buildTTLAlert(final Context context, final TLRPC.EncryptedChat encryptedChat) {\n AlertDialog.Builder builder = new AlertDialog.Builder(context);\n builder.setTitle(LocaleController.getString(\"MessageLifetime\", R.string.MessageLifetime));\n final NumberPicker numberPicker = new NumberPicker(context);\n numberPicker.setMinValue(0);\n numberPicker.setMaxValue(20);\n if (encryptedChat.ttl > 0 && encryptedChat.ttl < 16) {\n numberPicker.setValue(encryptedChat.ttl);\n } else if (encryptedChat.ttl == 30) {\n numberPicker.setValue(16);\n } else if (encryptedChat.ttl == 60) {\n numberPicker.setValue(17);\n } else if (encryptedChat.ttl == 60 * 60) {\n numberPicker.setValue(18);\n } else if (encryptedChat.ttl == 60 * 60 * 24) {\n numberPicker.setValue(19);\n } else if (encryptedChat.ttl == 60 * 60 * 24 * 7) {\n numberPicker.setValue(20);\n } else if (encryptedChat.ttl == 0) {\n numberPicker.setValue(0);\n }\n numberPicker.setFormatter(new NumberPicker.Formatter() {\n @Override\n public String format(int value) {\n if (value == 0) {\n return LocaleController.getString(\"ShortMessageLifetimeForever\", R.string.ShortMessageLifetimeForever);\n } else if (value >= 1 && value < 16) {\n return AndroidUtilities.formatTTLString(value);\n } else if (value == 16) {\n return AndroidUtilities.formatTTLString(30);\n } else if (value == 17) {\n return AndroidUtilities.formatTTLString(60);\n } else if (value == 18) {\n return AndroidUtilities.formatTTLString(60 * 60);\n } else if (value == 19) {\n return AndroidUtilities.formatTTLString(60 * 60 * 24);\n } else if (value == 20) {\n return AndroidUtilities.formatTTLString(60 * 60 * 24 * 7);\n }\n return \"\";\n }\n });\n builder.setView(numberPicker);\n builder.setNegativeButton(LocaleController.getString(\"Done\", R.string.Done), new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n int oldValue = encryptedChat.ttl;\n which = numberPicker.getValue();\n if (which >= 0 && which < 16) {\n encryptedChat.ttl = which;\n } else if (which == 16) {\n encryptedChat.ttl = 30;\n } else if (which == 17) {\n encryptedChat.ttl = 60;\n } else if (which == 18) {\n encryptedChat.ttl = 60 * 60;\n } else if (which == 19) {\n encryptedChat.ttl = 60 * 60 * 24;\n } else if (which == 20) {\n encryptedChat.ttl = 60 * 60 * 24 * 7;\n }\n if (oldValue != encryptedChat.ttl) {\n SecretChatHelper.getInstance().sendTTLMessage(encryptedChat, null);\n MessagesStorage.getInstance().updateEncryptedChatTTL(encryptedChat);\n }\n }\n });\n return builder;\n }\n\n public static void clearCursorDrawable(EditText editText) {\n if (editText == null || Build.VERSION.SDK_INT < 12) {\n return;\n }\n try {\n Field mCursorDrawableRes = TextView.class.getDeclaredField(\"mCursorDrawableRes\");\n mCursorDrawableRes.setAccessible(true);\n mCursorDrawableRes.setInt(editText, 0);\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n\n public static void setProgressBarAnimationDuration(ProgressBar progressBar, int duration) {\n if (progressBar == null) {\n return;\n }\n try {\n Field mCursorDrawableRes = ProgressBar.class.getDeclaredField(\"mDuration\");\n mCursorDrawableRes.setAccessible(true);\n mCursorDrawableRes.setInt(progressBar, duration);\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n\n public static int getViewInset(View view) {\n if (view == null || Build.VERSION.SDK_INT < 21) {\n return 0;\n }\n try {\n Field mAttachInfoField = View.class.getDeclaredField(\"mAttachInfo\");\n mAttachInfoField.setAccessible(true);\n Object mAttachInfo = mAttachInfoField.get(view);\n if (mAttachInfo != null) {\n Field mStableInsetsField = mAttachInfo.getClass().getDeclaredField(\"mStableInsets\");\n mStableInsetsField.setAccessible(true);\n Rect insets = (Rect)mStableInsetsField.get(mAttachInfo);\n return insets.bottom;\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n return 0;\n }\n\n public static int getCurrentActionBarHeight() {\n if (isTablet()) {\n return dp(64);\n } else if (ApplicationLoader.applicationContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {\n return dp(48);\n } else {\n return dp(56);\n }\n }\n\n public static Point getRealScreenSize() {\n Point size = new Point();\n try {\n WindowManager windowManager = (WindowManager) ApplicationLoader.applicationContext.getSystemService(Context.WINDOW_SERVICE);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {\n windowManager.getDefaultDisplay().getRealSize(size);\n } else {\n try {\n Method mGetRawW = Display.class.getMethod(\"getRawWidth\");\n Method mGetRawH = Display.class.getMethod(\"getRawHeight\");\n size.set((Integer) mGetRawW.invoke(windowManager.getDefaultDisplay()), (Integer) mGetRawH.invoke(windowManager.getDefaultDisplay()));\n } catch (Exception e) {\n size.set(windowManager.getDefaultDisplay().getWidth(), windowManager.getDefaultDisplay().getHeight());\n FileLog.e(\"tmessages\", e);\n }\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n return size;\n }\n\n public static void setListViewEdgeEffectColor(AbsListView listView, int color) {\n if (Build.VERSION.SDK_INT >= 21) {\n try {\n Field field = AbsListView.class.getDeclaredField(\"mEdgeGlowTop\");\n field.setAccessible(true);\n EdgeEffect mEdgeGlowTop = (EdgeEffect) field.get(listView);\n if (mEdgeGlowTop != null) {\n mEdgeGlowTop.setColor(color);\n }\n\n field = AbsListView.class.getDeclaredField(\"mEdgeGlowBottom\");\n field.setAccessible(true);\n EdgeEffect mEdgeGlowBottom = (EdgeEffect) field.get(listView);\n if (mEdgeGlowBottom != null) {\n mEdgeGlowBottom.setColor(color);\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n }\n\n public static void clearDrawableAnimation(View view) {\n if (Build.VERSION.SDK_INT < 21 || view == null) {\n return;\n }\n Drawable drawable = null;\n if (view instanceof ListView) {\n drawable = ((ListView) view).getSelector();\n if (drawable != null) {\n drawable.setState(StateSet.NOTHING);\n }\n } else {\n drawable = view.getBackground();\n if (drawable != null) {\n drawable.setState(StateSet.NOTHING);\n drawable.jumpToCurrentState();\n }\n }\n }\n\n public static Spannable replaceBold(String str) {\n int start;\n ArrayList<Integer> bolds = new ArrayList<>();\n while ((start = str.indexOf(\"<b>\")) != -1) {\n int end = str.indexOf(\"</b>\") - 3;\n str = str.replaceFirst(\"<b>\", \"\").replaceFirst(\"</b>\", \"\");\n bolds.add(start);\n bolds.add(end);\n }\n SpannableStringBuilder stringBuilder = new SpannableStringBuilder(str);\n for (int a = 0; a < bolds.size() / 2; a++) {\n TypefaceSpan span = new TypefaceSpan(AndroidUtilities.getTypeface(\"fonts/rmedium.ttf\"));\n stringBuilder.setSpan(span, bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_INCLUSIVE_INCLUSIVE);\n }\n return stringBuilder;\n }\n\n public static boolean needShowPasscode(boolean reset) {\n boolean wasInBackground;\n if (Build.VERSION.SDK_INT >= 14) {\n wasInBackground = ForegroundDetector.getInstance().isWasInBackground(reset);\n if (reset) {\n ForegroundDetector.getInstance().resetBackgroundVar();\n }\n } else {\n wasInBackground = UserConfig.lastPauseTime != 0;\n }\n return UserConfig.passcodeHash.length() > 0 && wasInBackground &&\n (UserConfig.appLocked || UserConfig.autoLockIn != 0 && UserConfig.lastPauseTime != 0 && !UserConfig.appLocked && (UserConfig.lastPauseTime + UserConfig.autoLockIn) <= ConnectionsManager.getInstance().getCurrentTime());\n }\n\n /*public static void turnOffHardwareAcceleration(Window window) {\n if (window == null || Build.MODEL == null || Build.VERSION.SDK_INT < 11) {\n return;\n }\n if (Build.MODEL.contains(\"GT-S5301\") ||\n Build.MODEL.contains(\"GT-S5303\") ||\n Build.MODEL.contains(\"GT-B5330\") ||\n Build.MODEL.contains(\"GT-S5302\") ||\n Build.MODEL.contains(\"GT-S6012B\") ||\n Build.MODEL.contains(\"MegaFon_SP-AI\")) {\n window.clearFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);\n }\n }*/\n}", "public class LocaleController {\n\n static final int QUANTITY_OTHER = 0x0000;\n static final int QUANTITY_ZERO = 0x0001;\n static final int QUANTITY_ONE = 0x0002;\n static final int QUANTITY_TWO = 0x0004;\n static final int QUANTITY_FEW = 0x0008;\n static final int QUANTITY_MANY = 0x0010;\n\n public static boolean isRTL = false;\n public static int nameDisplayOrder = 1;\n private static boolean is24HourFormat = false;\n public static FastDateFormat formatterDay;\n public static FastDateFormat formatterWeek;\n public static FastDateFormat formatterMonth;\n public static FastDateFormat formatterYear;\n public static FastDateFormat formatterMonthYear;\n public static FastDateFormat formatterYearMax;\n public static FastDateFormat chatDate;\n public static FastDateFormat chatFullDate;\n\n private HashMap<String, PluralRules> allRules = new HashMap<>();\n\n private Locale currentLocale;\n private Locale systemDefaultLocale;\n private PluralRules currentPluralRules;\n private LocaleInfo currentLocaleInfo;\n private LocaleInfo defaultLocalInfo;\n private HashMap<String, String> localeValues = new HashMap<>();\n private String languageOverride;\n private boolean changingConfiguration = false;\n\n private HashMap<String, String> translitChars;\n\n private class TimeZoneChangedReceiver extends BroadcastReceiver {\n @Override\n public void onReceive(Context context, Intent intent) {\n ApplicationLoader.applicationHandler.post(new Runnable() {\n @Override\n public void run() {\n if (!formatterMonth.getTimeZone().equals(TimeZone.getDefault())) {\n LocaleController.getInstance().recreateFormatters();\n }\n }\n });\n }\n }\n\n public static class LocaleInfo {\n public String name;\n public String nameEnglish;\n public String shortName;\n public String pathToFile;\n\n public String getSaveString() {\n return name + \"|\" + nameEnglish + \"|\" + shortName + \"|\" + pathToFile;\n }\n\n public static LocaleInfo createWithString(String string) {\n if (string == null || string.length() == 0) {\n return null;\n }\n String[] args = string.split(\"\\\\|\");\n if (args.length != 4) {\n return null;\n }\n LocaleInfo localeInfo = new LocaleInfo();\n localeInfo.name = args[0];\n localeInfo.nameEnglish = args[1];\n localeInfo.shortName = args[2];\n localeInfo.pathToFile = args[3];\n return localeInfo;\n }\n }\n\n public ArrayList<LocaleInfo> sortedLanguages = new ArrayList<>();\n public HashMap<String, LocaleInfo> languagesDict = new HashMap<>();\n\n private ArrayList<LocaleInfo> otherLanguages = new ArrayList<>();\n\n private static volatile LocaleController Instance = null;\n public static LocaleController getInstance() {\n LocaleController localInstance = Instance;\n if (localInstance == null) {\n synchronized (LocaleController.class) {\n localInstance = Instance;\n if (localInstance == null) {\n Instance = localInstance = new LocaleController();\n }\n }\n }\n return localInstance;\n }\n\n public LocaleController() {\n addRules(new String[]{\"bem\", \"brx\", \"da\", \"de\", \"el\", \"en\", \"eo\", \"es\", \"et\", \"fi\", \"fo\", \"gl\", \"he\", \"iw\", \"it\", \"nb\",\n \"nl\", \"nn\", \"no\", \"sv\", \"af\", \"bg\", \"bn\", \"ca\", \"eu\", \"fur\", \"fy\", \"gu\", \"ha\", \"is\", \"ku\",\n \"lb\", \"ml\", \"mr\", \"nah\", \"ne\", \"om\", \"or\", \"pa\", \"pap\", \"ps\", \"so\", \"sq\", \"sw\", \"ta\", \"te\",\n \"tk\", \"ur\", \"zu\", \"mn\", \"gsw\", \"chr\", \"rm\", \"pt\", \"an\", \"ast\"}, new PluralRules_One());\n addRules(new String[]{\"cs\", \"sk\"}, new PluralRules_Czech());\n addRules(new String[]{\"ff\", \"fr\", \"kab\"}, new PluralRules_French());\n addRules(new String[]{\"hr\", \"ru\", \"sr\", \"uk\", \"be\", \"bs\", \"sh\"}, new PluralRules_Balkan());\n addRules(new String[]{\"lv\"}, new PluralRules_Latvian());\n addRules(new String[]{\"lt\"}, new PluralRules_Lithuanian());\n addRules(new String[]{\"pl\"}, new PluralRules_Polish());\n addRules(new String[]{\"ro\", \"mo\"}, new PluralRules_Romanian());\n addRules(new String[]{\"sl\"}, new PluralRules_Slovenian());\n addRules(new String[]{\"ar\"}, new PluralRules_Arabic());\n addRules(new String[]{\"mk\"}, new PluralRules_Macedonian());\n addRules(new String[]{\"cy\"}, new PluralRules_Welsh());\n addRules(new String[]{\"br\"}, new PluralRules_Breton());\n addRules(new String[]{\"lag\"}, new PluralRules_Langi());\n addRules(new String[]{\"shi\"}, new PluralRules_Tachelhit());\n addRules(new String[]{\"mt\"}, new PluralRules_Maltese());\n addRules(new String[]{\"ga\", \"se\", \"sma\", \"smi\", \"smj\", \"smn\", \"sms\"}, new PluralRules_Two());\n addRules(new String[]{\"ak\", \"am\", \"bh\", \"fil\", \"tl\", \"guw\", \"hi\", \"ln\", \"mg\", \"nso\", \"ti\", \"wa\"}, new PluralRules_Zero());\n addRules(new String[]{\"az\", \"bm\", \"fa\", \"ig\", \"hu\", \"ja\", \"kde\", \"kea\", \"ko\", \"my\", \"ses\", \"sg\", \"to\",\n \"tr\", \"vi\", \"wo\", \"yo\", \"zh\", \"bo\", \"dz\", \"id\", \"jv\", \"ka\", \"km\", \"kn\", \"ms\", \"th\"}, new PluralRules_None());\n\n LocaleInfo localeInfo = new LocaleInfo();\n localeInfo.name = \"English\";\n localeInfo.nameEnglish = \"English\";\n localeInfo.shortName = \"en\";\n localeInfo.pathToFile = null;\n sortedLanguages.add(localeInfo);\n languagesDict.put(localeInfo.shortName, localeInfo);\n\n localeInfo = new LocaleInfo();\n localeInfo.name = \"Italiano\";\n localeInfo.nameEnglish = \"Italian\";\n localeInfo.shortName = \"it\";\n localeInfo.pathToFile = null;\n sortedLanguages.add(localeInfo);\n languagesDict.put(localeInfo.shortName, localeInfo);\n\n localeInfo = new LocaleInfo();\n localeInfo.name = \"Español\";\n localeInfo.nameEnglish = \"Spanish\";\n localeInfo.shortName = \"es\";\n sortedLanguages.add(localeInfo);\n languagesDict.put(localeInfo.shortName, localeInfo);\n\n localeInfo = new LocaleInfo();\n localeInfo.name = \"Deutsch\";\n localeInfo.nameEnglish = \"German\";\n localeInfo.shortName = \"de\";\n localeInfo.pathToFile = null;\n sortedLanguages.add(localeInfo);\n languagesDict.put(localeInfo.shortName, localeInfo);\n\n localeInfo = new LocaleInfo();\n localeInfo.name = \"Nederlands\";\n localeInfo.nameEnglish = \"Dutch\";\n localeInfo.shortName = \"nl\";\n localeInfo.pathToFile = null;\n sortedLanguages.add(localeInfo);\n languagesDict.put(localeInfo.shortName, localeInfo);\n\n localeInfo = new LocaleInfo();\n localeInfo.name = \"العربية\";\n localeInfo.nameEnglish = \"Arabic\";\n localeInfo.shortName = \"ar\";\n localeInfo.pathToFile = null;\n sortedLanguages.add(localeInfo);\n languagesDict.put(localeInfo.shortName, localeInfo);\n\n localeInfo = new LocaleInfo();\n localeInfo.name = \"Português (Brasil)\";\n localeInfo.nameEnglish = \"Portuguese (Brazil)\";\n localeInfo.shortName = \"pt_BR\";\n localeInfo.pathToFile = null;\n sortedLanguages.add(localeInfo);\n languagesDict.put(localeInfo.shortName, localeInfo);\n\n localeInfo = new LocaleInfo();\n localeInfo.name = \"Português (Portugal)\";\n localeInfo.nameEnglish = \"Portuguese (Portugal)\";\n localeInfo.shortName = \"pt_PT\";\n localeInfo.pathToFile = null;\n sortedLanguages.add(localeInfo);\n languagesDict.put(localeInfo.shortName, localeInfo);\n\n localeInfo = new LocaleInfo();\n localeInfo.name = \"한국어\";\n localeInfo.nameEnglish = \"Korean\";\n localeInfo.shortName = \"ko\";\n localeInfo.pathToFile = null;\n sortedLanguages.add(localeInfo);\n languagesDict.put(localeInfo.shortName, localeInfo);\n\n loadOtherLanguages();\n\n for (LocaleInfo locale : otherLanguages) {\n sortedLanguages.add(locale);\n languagesDict.put(locale.shortName, locale);\n }\n\n Collections.sort(sortedLanguages, new Comparator<LocaleInfo>() {\n @Override\n public int compare(LocaleController.LocaleInfo o, LocaleController.LocaleInfo o2) {\n return o.name.compareTo(o2.name);\n }\n });\n\n defaultLocalInfo = localeInfo = new LocaleController.LocaleInfo();\n localeInfo.name = \"System default\";\n localeInfo.nameEnglish = \"System default\";\n localeInfo.shortName = null;\n localeInfo.pathToFile = null;\n sortedLanguages.add(0, localeInfo);\n\n systemDefaultLocale = Locale.getDefault();\n is24HourFormat = DateFormat.is24HourFormat(ApplicationLoader.applicationContext);\n LocaleInfo currentInfo = null;\n boolean override = false;\n\n try {\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"mainconfig\", Activity.MODE_PRIVATE);\n String lang = preferences.getString(\"language\", null);\n if (lang != null) {\n currentInfo = languagesDict.get(lang);\n if (currentInfo != null) {\n override = true;\n }\n }\n\n if (currentInfo == null && systemDefaultLocale.getLanguage() != null) {\n currentInfo = languagesDict.get(systemDefaultLocale.getLanguage());\n }\n if (currentInfo == null) {\n currentInfo = languagesDict.get(getLocaleString(systemDefaultLocale));\n }\n if (currentInfo == null) {\n currentInfo = languagesDict.get(\"en\");\n }\n applyLanguage(currentInfo, override);\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n\n try {\n IntentFilter timezoneFilter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);\n ApplicationLoader.applicationContext.registerReceiver(new TimeZoneChangedReceiver(), timezoneFilter);\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n\n private void addRules(String[] languages, PluralRules rules) {\n for (String language : languages) {\n allRules.put(language, rules);\n }\n }\n\n private String stringForQuantity(int quantity) {\n switch (quantity) {\n case QUANTITY_ZERO:\n return \"zero\";\n case QUANTITY_ONE:\n return \"one\";\n case QUANTITY_TWO:\n return \"two\";\n case QUANTITY_FEW:\n return \"few\";\n case QUANTITY_MANY:\n return \"many\";\n default:\n return \"other\";\n }\n }\n\n public static String getLocaleString(Locale locale) {\n if (locale == null) {\n return \"en\";\n }\n String languageCode = locale.getLanguage();\n String countryCode = locale.getCountry();\n String variantCode = locale.getVariant();\n if (languageCode.length() == 0 && countryCode.length() == 0) {\n return \"en\";\n }\n StringBuilder result = new StringBuilder(11);\n result.append(languageCode);\n if (countryCode.length() > 0 || variantCode.length() > 0) {\n result.append('_');\n }\n result.append(countryCode);\n if (variantCode.length() > 0) {\n result.append('_');\n }\n result.append(variantCode);\n return result.toString();\n }\n\n public boolean applyLanguageFile(File file) {\n try {\n HashMap<String, String> stringMap = getLocaleFileStrings(file);\n\n String languageName = stringMap.get(\"LanguageName\");\n String languageNameInEnglish = stringMap.get(\"LanguageNameInEnglish\");\n String languageCode = stringMap.get(\"LanguageCode\");\n\n if (languageName != null && languageName.length() > 0 &&\n languageNameInEnglish != null && languageNameInEnglish.length() > 0 &&\n languageCode != null && languageCode.length() > 0) {\n\n if (languageName.contains(\"&\") || languageName.contains(\"|\")) {\n return false;\n }\n if (languageNameInEnglish.contains(\"&\") || languageNameInEnglish.contains(\"|\")) {\n return false;\n }\n if (languageCode.contains(\"&\") || languageCode.contains(\"|\")) {\n return false;\n }\n\n File finalFile = new File(ApplicationLoader.applicationContext.getFilesDir(), languageCode + \".xml\");\n if (!Utilities.copyFile(file, finalFile)) {\n return false;\n }\n\n LocaleInfo localeInfo = languagesDict.get(languageCode);\n if (localeInfo == null) {\n localeInfo = new LocaleInfo();\n localeInfo.name = languageName;\n localeInfo.nameEnglish = languageNameInEnglish;\n localeInfo.shortName = languageCode;\n\n localeInfo.pathToFile = finalFile.getAbsolutePath();\n sortedLanguages.add(localeInfo);\n languagesDict.put(localeInfo.shortName, localeInfo);\n otherLanguages.add(localeInfo);\n\n Collections.sort(sortedLanguages, new Comparator<LocaleInfo>() {\n @Override\n public int compare(LocaleController.LocaleInfo o, LocaleController.LocaleInfo o2) {\n if (o.shortName == null) {\n return -1;\n } else if (o2.shortName == null) {\n return 1;\n }\n return o.name.compareTo(o2.name);\n }\n });\n saveOtherLanguages();\n }\n localeValues = stringMap;\n applyLanguage(localeInfo, true, true);\n return true;\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n return false;\n }\n\n private void saveOtherLanguages() {\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"langconfig\", Activity.MODE_PRIVATE);\n SharedPreferences.Editor editor = preferences.edit();\n String locales = \"\";\n for (LocaleInfo localeInfo : otherLanguages) {\n String loc = localeInfo.getSaveString();\n if (loc != null) {\n if (locales.length() != 0) {\n locales += \"&\";\n }\n locales += loc;\n }\n }\n editor.putString(\"locales\", locales);\n editor.commit();\n }\n\n public boolean deleteLanguage(LocaleInfo localeInfo) {\n if (localeInfo.pathToFile == null) {\n return false;\n }\n if (currentLocaleInfo == localeInfo) {\n applyLanguage(defaultLocalInfo, true);\n }\n\n otherLanguages.remove(localeInfo);\n sortedLanguages.remove(localeInfo);\n languagesDict.remove(localeInfo.shortName);\n File file = new File(localeInfo.pathToFile);\n file.delete();\n saveOtherLanguages();\n return true;\n }\n\n private void loadOtherLanguages() {\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"langconfig\", Activity.MODE_PRIVATE);\n String locales = preferences.getString(\"locales\", null);\n if (locales == null || locales.length() == 0) {\n return;\n }\n String[] localesArr = locales.split(\"&\");\n for (String locale : localesArr) {\n LocaleInfo localeInfo = LocaleInfo.createWithString(locale);\n if (localeInfo != null) {\n otherLanguages.add(localeInfo);\n }\n }\n }\n\n private HashMap<String, String> getLocaleFileStrings(File file) {\n FileInputStream stream = null;\n try {\n HashMap<String, String> stringMap = new HashMap<>();\n XmlPullParser parser = Xml.newPullParser();\n stream = new FileInputStream(file);\n parser.setInput(stream, \"UTF-8\");\n int eventType = parser.getEventType();\n String name = null;\n String value = null;\n String attrName = null;\n while (eventType != XmlPullParser.END_DOCUMENT) {\n if(eventType == XmlPullParser.START_TAG) {\n name = parser.getName();\n int c = parser.getAttributeCount();\n if (c > 0) {\n attrName = parser.getAttributeValue(0);\n }\n } else if(eventType == XmlPullParser.TEXT) {\n if (attrName != null) {\n value = parser.getText();\n if (value != null) {\n value = value.trim();\n value = value.replace(\"\\\\n\", \"\\n\");\n value = value.replace(\"\\\\\", \"\");\n }\n }\n } else if (eventType == XmlPullParser.END_TAG) {\n value = null;\n attrName = null;\n name = null;\n }\n if (name != null && name.equals(\"string\") && value != null && attrName != null && value.length() != 0 && attrName.length() != 0) {\n stringMap.put(attrName, value);\n name = null;\n value = null;\n attrName = null;\n }\n eventType = parser.next();\n }\n return stringMap;\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n } finally {\n try {\n if (stream != null) {\n stream.close();\n stream = null;\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n return null;\n }\n\n public void applyLanguage(LocaleInfo localeInfo, boolean override) {\n applyLanguage(localeInfo, override, false);\n }\n\n public void applyLanguage(LocaleInfo localeInfo, boolean override, boolean fromFile) {\n if (localeInfo == null) {\n return;\n }\n try {\n Locale newLocale = null;\n if (localeInfo.shortName != null) {\n String[] args = localeInfo.shortName.split(\"_\");\n if (args.length == 1) {\n newLocale = new Locale(localeInfo.shortName);\n } else {\n newLocale = new Locale(args[0], args[1]);\n }\n if (newLocale != null) {\n if (override) {\n languageOverride = localeInfo.shortName;\n\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"mainconfig\", Activity.MODE_PRIVATE);\n SharedPreferences.Editor editor = preferences.edit();\n editor.putString(\"language\", localeInfo.shortName);\n editor.commit();\n }\n }\n } else {\n newLocale = systemDefaultLocale;\n languageOverride = null;\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"mainconfig\", Activity.MODE_PRIVATE);\n SharedPreferences.Editor editor = preferences.edit();\n editor.remove(\"language\");\n editor.commit();\n\n if (newLocale != null) {\n LocaleInfo info = null;\n if (newLocale.getLanguage() != null) {\n info = languagesDict.get(newLocale.getLanguage());\n }\n if (info == null) {\n info = languagesDict.get(getLocaleString(newLocale));\n }\n if (info == null) {\n newLocale = Locale.US;\n }\n }\n }\n if (newLocale != null) {\n if (localeInfo.pathToFile == null) {\n localeValues.clear();\n } else if (!fromFile) {\n localeValues = getLocaleFileStrings(new File(localeInfo.pathToFile));\n }\n currentLocale = newLocale;\n currentLocaleInfo = localeInfo;\n currentPluralRules = allRules.get(currentLocale.getLanguage());\n if (currentPluralRules == null) {\n currentPluralRules = allRules.get(\"en\");\n }\n changingConfiguration = true;\n Locale.setDefault(currentLocale);\n android.content.res.Configuration config = new android.content.res.Configuration();\n config.locale = currentLocale;\n ApplicationLoader.applicationContext.getResources().updateConfiguration(config, ApplicationLoader.applicationContext.getResources().getDisplayMetrics());\n changingConfiguration = false;\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n changingConfiguration = false;\n }\n recreateFormatters();\n }\n\n private void loadCurrentLocale() {\n localeValues.clear();\n }\n\n public static String getCurrentLanguageName() {\n return getString(\"LanguageName\", R.string.LanguageName);\n }\n\n private String getStringInternal(String key, int res) {\n String value = localeValues.get(key);\n if (value == null) {\n value = ApplicationLoader.applicationContext.getString(res);\n }\n if (value == null) {\n value = \"LOC_ERR:\" + key;\n }\n return value;\n }\n\n public static String getCurrentLanguageCode() {\n return getString(\"LanguageCode\", R.string.LanguageCode);\n }\n\n public static String getString(String key, int res) {\n return getInstance().getStringInternal(key, res);\n }\n\n public static String formatPluralString(String key, int plural) {\n if (key == null || key.length() == 0 || getInstance().currentPluralRules == null) {\n return \"LOC_ERR:\" + key;\n }\n String param = getInstance().stringForQuantity(getInstance().currentPluralRules.quantityForNumber(plural));\n param = key + \"_\" + param;\n int resourceId = ApplicationLoader.applicationContext.getResources().getIdentifier(param, \"string\", ApplicationLoader.applicationContext.getPackageName());\n return formatString(param, resourceId, plural);\n }\n\n public static String formatString(String key, int res, Object... args) {\n String value = getInstance().localeValues.get(key);\n if (value == null) {\n value = ApplicationLoader.applicationContext.getString(res);\n }\n try {\n if (getInstance().currentLocale != null) {\n return String.format(getInstance().currentLocale, value, args);\n } else {\n return String.format(value, args);\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n return \"LOC_ERR: \" + key;\n }\n }\n\n public static String formatStringSimple(String string, Object... args) {\n try {\n if (getInstance().currentLocale != null) {\n return String.format(getInstance().currentLocale, string, args);\n } else {\n return String.format(string, args);\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n return \"LOC_ERR: \" + string;\n }\n }\n\n public void onDeviceConfigurationChange(Configuration newConfig) {\n if (changingConfiguration) {\n return;\n }\n is24HourFormat = DateFormat.is24HourFormat(ApplicationLoader.applicationContext);\n systemDefaultLocale = newConfig.locale;\n if (languageOverride != null) {\n LocaleInfo toSet = currentLocaleInfo;\n currentLocaleInfo = null;\n applyLanguage(toSet, false);\n } else {\n Locale newLocale = newConfig.locale;\n if (newLocale != null) {\n String d1 = newLocale.getDisplayName();\n String d2 = currentLocale.getDisplayName();\n if (d1 != null && d2 != null && !d1.equals(d2)) {\n recreateFormatters();\n }\n currentLocale = newLocale;\n currentPluralRules = allRules.get(currentLocale.getLanguage());\n if (currentPluralRules == null) {\n currentPluralRules = allRules.get(\"en\");\n }\n }\n }\n }\n\n public static String formatDateChat(long date) {\n Calendar rightNow = Calendar.getInstance();\n int year = rightNow.get(Calendar.YEAR);\n\n rightNow.setTimeInMillis(date * 1000);\n int dateYear = rightNow.get(Calendar.YEAR);\n\n if (year == dateYear) {\n return chatDate.format(date * 1000);\n }\n return chatFullDate.format(date * 1000);\n }\n\n public static String formatDate(long date) {\n Calendar rightNow = Calendar.getInstance();\n int day = rightNow.get(Calendar.DAY_OF_YEAR);\n int year = rightNow.get(Calendar.YEAR);\n rightNow.setTimeInMillis(date * 1000);\n int dateDay = rightNow.get(Calendar.DAY_OF_YEAR);\n int dateYear = rightNow.get(Calendar.YEAR);\n\n if (dateDay == day && year == dateYear) {\n return formatterDay.format(new Date(date * 1000));\n } else if (dateDay + 1 == day && year == dateYear) {\n return getString(\"Yesterday\", R.string.Yesterday);\n } else if (year == dateYear) {\n return formatterMonth.format(new Date(date * 1000));\n } else {\n return formatterYear.format(new Date(date * 1000));\n }\n }\n\n public static String formatDateOnline(long date) {\n Calendar rightNow = Calendar.getInstance();\n int day = rightNow.get(Calendar.DAY_OF_YEAR);\n int year = rightNow.get(Calendar.YEAR);\n rightNow.setTimeInMillis(date * 1000);\n int dateDay = rightNow.get(Calendar.DAY_OF_YEAR);\n int dateYear = rightNow.get(Calendar.YEAR);\n\n if (dateDay == day && year == dateYear) {\n return String.format(\"%s %s %s\", LocaleController.getString(\"LastSeen\", R.string.LastSeen), LocaleController.getString(\"TodayAt\", R.string.TodayAt), formatterDay.format(new Date(date * 1000)));\n } else if (dateDay + 1 == day && year == dateYear) {\n return String.format(\"%s %s %s\", LocaleController.getString(\"LastSeen\", R.string.LastSeen), LocaleController.getString(\"YesterdayAt\", R.string.YesterdayAt), formatterDay.format(new Date(date * 1000)));\n } else if (year == dateYear) {\n String format = LocaleController.formatString(\"formatDateAtTime\", R.string.formatDateAtTime, formatterMonth.format(new Date(date * 1000)), formatterDay.format(new Date(date * 1000)));\n return String.format(\"%s %s\", LocaleController.getString(\"LastSeenDate\", R.string.LastSeenDate), format);\n } else {\n String format = LocaleController.formatString(\"formatDateAtTime\", R.string.formatDateAtTime, formatterYear.format(new Date(date * 1000)), formatterDay.format(new Date(date * 1000)));\n return String.format(\"%s %s\", LocaleController.getString(\"LastSeenDate\", R.string.LastSeenDate), format);\n }\n }\n\n private FastDateFormat createFormatter(Locale locale, String format, String defaultFormat) {\n if (format == null || format.length() == 0) {\n format = defaultFormat;\n }\n FastDateFormat formatter = null;\n try {\n formatter = FastDateFormat.getInstance(format, locale);\n } catch (Exception e) {\n format = defaultFormat;\n formatter = FastDateFormat.getInstance(format, locale);\n }\n return formatter;\n }\n\n public void recreateFormatters() {\n Locale locale = currentLocale;\n if (locale == null) {\n locale = Locale.getDefault();\n }\n String lang = locale.getLanguage();\n if (lang == null) {\n lang = \"en\";\n }\n isRTL = lang.toLowerCase().equals(\"ar\");\n nameDisplayOrder = lang.toLowerCase().equals(\"ko\") ? 2 : 1;\n\n formatterMonth = createFormatter(locale, getStringInternal(\"formatterMonth\", R.string.formatterMonth), \"dd MMM\");\n formatterYear = createFormatter(locale, getStringInternal(\"formatterYear\", R.string.formatterYear), \"dd.MM.yy\");\n formatterYearMax = createFormatter(locale, getStringInternal(\"formatterYearMax\", R.string.formatterYearMax), \"dd.MM.yyyy\");\n chatDate = createFormatter(locale, getStringInternal(\"chatDate\", R.string.chatDate), \"d MMMM\");\n chatFullDate = createFormatter(locale, getStringInternal(\"chatFullDate\", R.string.chatFullDate), \"d MMMM yyyy\");\n formatterWeek = createFormatter(locale, getStringInternal(\"formatterWeek\", R.string.formatterWeek), \"EEE\");\n formatterMonthYear = createFormatter(locale, getStringInternal(\"formatterMonthYear\", R.string.formatterMonthYear), \"MMMM yyyy\");\n formatterDay = createFormatter(lang.toLowerCase().equals(\"ar\") || lang.toLowerCase().equals(\"ko\") ? locale : Locale.US, is24HourFormat ? getStringInternal(\"formatterDay24H\", R.string.formatterDay24H) : getStringInternal(\"formatterDay12H\", R.string.formatterDay12H), is24HourFormat ? \"HH:mm\" : \"h:mm a\");\n }\n\n public static String stringForMessageListDate(long date) {\n Calendar rightNow = Calendar.getInstance();\n int day = rightNow.get(Calendar.DAY_OF_YEAR);\n int year = rightNow.get(Calendar.YEAR);\n rightNow.setTimeInMillis(date * 1000);\n int dateDay = rightNow.get(Calendar.DAY_OF_YEAR);\n int dateYear = rightNow.get(Calendar.YEAR);\n\n if (year != dateYear) {\n return formatterYear.format(new Date(date * 1000));\n } else {\n int dayDiff = dateDay - day;\n if(dayDiff == 0 || dayDiff == -1 && (int)(System.currentTimeMillis() / 1000) - date < 60 * 60 * 8) {\n return formatterDay.format(new Date(date * 1000));\n } else if(dayDiff > -7 && dayDiff <= -1) {\n return formatterWeek.format(new Date(date * 1000));\n } else {\n return formatterMonth.format(new Date(date * 1000));\n }\n }\n }\n\n public static String formatUserStatus(TLRPC.User user) {\n if (user != null && user.status != null && user.status.expires == 0) {\n if (user.status instanceof TLRPC.TL_userStatusRecently) {\n user.status.expires = -100;\n } else if (user.status instanceof TLRPC.TL_userStatusLastWeek) {\n user.status.expires = -101;\n } else if (user.status instanceof TLRPC.TL_userStatusLastMonth) {\n user.status.expires = -102;\n }\n }\n if (user != null && user.status != null && user.status.expires <= 0) {\n if (MessagesController.getInstance().onlinePrivacy.containsKey(user.id)) {\n return getString(\"Online\", R.string.Online);\n }\n }\n if (user == null || user.status == null || user.status.expires == 0 || user instanceof TLRPC.TL_userDeleted || user instanceof TLRPC.TL_userEmpty) {\n return getString(\"ALongTimeAgo\", R.string.ALongTimeAgo);\n } else {\n int currentTime = ConnectionsManager.getInstance().getCurrentTime();\n if (user.status.expires > currentTime) {\n return getString(\"Online\", R.string.Online);\n } else {\n if (user.status.expires == -1) {\n return getString(\"Invisible\", R.string.Invisible);\n } else if (user.status.expires == -100) {\n return getString(\"Lately\", R.string.Lately);\n } else if (user.status.expires == -101) {\n return getString(\"WithinAWeek\", R.string.WithinAWeek);\n } else if (user.status.expires == -102) {\n return getString(\"WithinAMonth\", R.string.WithinAMonth);\n } else {\n return formatDateOnline(user.status.expires);\n }\n }\n }\n }\n\n public String getTranslitString(String src) {\n if (translitChars == null) {\n translitChars = new HashMap<>(520);\n translitChars.put(\"ȼ\", \"c\");\n translitChars.put(\"ᶇ\", \"n\");\n translitChars.put(\"ɖ\", \"d\");\n translitChars.put(\"ỿ\", \"y\");\n translitChars.put(\"ᴓ\", \"o\");\n translitChars.put(\"ø\", \"o\");\n translitChars.put(\"ḁ\", \"a\");\n translitChars.put(\"ʯ\", \"h\");\n translitChars.put(\"ŷ\", \"y\");\n translitChars.put(\"ʞ\", \"k\");\n translitChars.put(\"ừ\", \"u\");\n translitChars.put(\"ꜳ\", \"aa\");\n translitChars.put(\"ij\", \"ij\");\n translitChars.put(\"ḽ\", \"l\");\n translitChars.put(\"ɪ\", \"i\");\n translitChars.put(\"ḇ\", \"b\");\n translitChars.put(\"ʀ\", \"r\");\n translitChars.put(\"ě\", \"e\");\n translitChars.put(\"ffi\", \"ffi\");\n translitChars.put(\"ơ\", \"o\");\n translitChars.put(\"ⱹ\", \"r\");\n translitChars.put(\"ồ\", \"o\");\n translitChars.put(\"ǐ\", \"i\");\n translitChars.put(\"ꝕ\", \"p\");\n translitChars.put(\"ý\", \"y\");\n translitChars.put(\"ḝ\", \"e\");\n translitChars.put(\"ₒ\", \"o\");\n translitChars.put(\"ⱥ\", \"a\");\n translitChars.put(\"ʙ\", \"b\");\n translitChars.put(\"ḛ\", \"e\");\n translitChars.put(\"ƈ\", \"c\");\n translitChars.put(\"ɦ\", \"h\");\n translitChars.put(\"ᵬ\", \"b\");\n translitChars.put(\"ṣ\", \"s\");\n translitChars.put(\"đ\", \"d\");\n translitChars.put(\"ỗ\", \"o\");\n translitChars.put(\"ɟ\", \"j\");\n translitChars.put(\"ẚ\", \"a\");\n translitChars.put(\"ɏ\", \"y\");\n translitChars.put(\"л\", \"l\");\n translitChars.put(\"ʌ\", \"v\");\n translitChars.put(\"ꝓ\", \"p\");\n translitChars.put(\"fi\", \"fi\");\n translitChars.put(\"ᶄ\", \"k\");\n translitChars.put(\"ḏ\", \"d\");\n translitChars.put(\"ᴌ\", \"l\");\n translitChars.put(\"ė\", \"e\");\n translitChars.put(\"ё\", \"yo\");\n translitChars.put(\"ᴋ\", \"k\");\n translitChars.put(\"ċ\", \"c\");\n translitChars.put(\"ʁ\", \"r\");\n translitChars.put(\"ƕ\", \"hv\");\n translitChars.put(\"ƀ\", \"b\");\n translitChars.put(\"ṍ\", \"o\");\n translitChars.put(\"ȣ\", \"ou\");\n translitChars.put(\"ǰ\", \"j\");\n translitChars.put(\"ᶃ\", \"g\");\n translitChars.put(\"ṋ\", \"n\");\n translitChars.put(\"ɉ\", \"j\");\n translitChars.put(\"ǧ\", \"g\");\n translitChars.put(\"dz\", \"dz\");\n translitChars.put(\"ź\", \"z\");\n translitChars.put(\"ꜷ\", \"au\");\n translitChars.put(\"ǖ\", \"u\");\n translitChars.put(\"ᵹ\", \"g\");\n translitChars.put(\"ȯ\", \"o\");\n translitChars.put(\"ɐ\", \"a\");\n translitChars.put(\"ą\", \"a\");\n translitChars.put(\"õ\", \"o\");\n translitChars.put(\"ɻ\", \"r\");\n translitChars.put(\"ꝍ\", \"o\");\n translitChars.put(\"ǟ\", \"a\");\n translitChars.put(\"ȴ\", \"l\");\n translitChars.put(\"ʂ\", \"s\");\n translitChars.put(\"fl\", \"fl\");\n translitChars.put(\"ȉ\", \"i\");\n translitChars.put(\"ⱻ\", \"e\");\n translitChars.put(\"ṉ\", \"n\");\n translitChars.put(\"ï\", \"i\");\n translitChars.put(\"ñ\", \"n\");\n translitChars.put(\"ᴉ\", \"i\");\n translitChars.put(\"ʇ\", \"t\");\n translitChars.put(\"ẓ\", \"z\");\n translitChars.put(\"ỷ\", \"y\");\n translitChars.put(\"ȳ\", \"y\");\n translitChars.put(\"ṩ\", \"s\");\n translitChars.put(\"ɽ\", \"r\");\n translitChars.put(\"ĝ\", \"g\");\n translitChars.put(\"в\", \"v\");\n translitChars.put(\"ᴝ\", \"u\");\n translitChars.put(\"ḳ\", \"k\");\n translitChars.put(\"ꝫ\", \"et\");\n translitChars.put(\"ī\", \"i\");\n translitChars.put(\"ť\", \"t\");\n translitChars.put(\"ꜿ\", \"c\");\n translitChars.put(\"ʟ\", \"l\");\n translitChars.put(\"ꜹ\", \"av\");\n translitChars.put(\"û\", \"u\");\n translitChars.put(\"æ\", \"ae\");\n translitChars.put(\"и\", \"i\");\n translitChars.put(\"ă\", \"a\");\n translitChars.put(\"ǘ\", \"u\");\n translitChars.put(\"ꞅ\", \"s\");\n translitChars.put(\"ᵣ\", \"r\");\n translitChars.put(\"ᴀ\", \"a\");\n translitChars.put(\"ƃ\", \"b\");\n translitChars.put(\"ḩ\", \"h\");\n translitChars.put(\"ṧ\", \"s\");\n translitChars.put(\"ₑ\", \"e\");\n translitChars.put(\"ʜ\", \"h\");\n translitChars.put(\"ẋ\", \"x\");\n translitChars.put(\"ꝅ\", \"k\");\n translitChars.put(\"ḋ\", \"d\");\n translitChars.put(\"ƣ\", \"oi\");\n translitChars.put(\"ꝑ\", \"p\");\n translitChars.put(\"ħ\", \"h\");\n translitChars.put(\"ⱴ\", \"v\");\n translitChars.put(\"ẇ\", \"w\");\n translitChars.put(\"ǹ\", \"n\");\n translitChars.put(\"ɯ\", \"m\");\n translitChars.put(\"ɡ\", \"g\");\n translitChars.put(\"ɴ\", \"n\");\n translitChars.put(\"ᴘ\", \"p\");\n translitChars.put(\"ᵥ\", \"v\");\n translitChars.put(\"ū\", \"u\");\n translitChars.put(\"ḃ\", \"b\");\n translitChars.put(\"ṗ\", \"p\");\n translitChars.put(\"ь\", \"\");\n translitChars.put(\"å\", \"a\");\n translitChars.put(\"ɕ\", \"c\");\n translitChars.put(\"ọ\", \"o\");\n translitChars.put(\"ắ\", \"a\");\n translitChars.put(\"ƒ\", \"f\");\n translitChars.put(\"ǣ\", \"ae\");\n translitChars.put(\"ꝡ\", \"vy\");\n translitChars.put(\"ff\", \"ff\");\n translitChars.put(\"ᶉ\", \"r\");\n translitChars.put(\"ô\", \"o\");\n translitChars.put(\"ǿ\", \"o\");\n translitChars.put(\"ṳ\", \"u\");\n translitChars.put(\"ȥ\", \"z\");\n translitChars.put(\"ḟ\", \"f\");\n translitChars.put(\"ḓ\", \"d\");\n translitChars.put(\"ȇ\", \"e\");\n translitChars.put(\"ȕ\", \"u\");\n translitChars.put(\"п\", \"p\");\n translitChars.put(\"ȵ\", \"n\");\n translitChars.put(\"ʠ\", \"q\");\n translitChars.put(\"ấ\", \"a\");\n translitChars.put(\"ǩ\", \"k\");\n translitChars.put(\"ĩ\", \"i\");\n translitChars.put(\"ṵ\", \"u\");\n translitChars.put(\"ŧ\", \"t\");\n translitChars.put(\"ɾ\", \"r\");\n translitChars.put(\"ƙ\", \"k\");\n translitChars.put(\"ṫ\", \"t\");\n translitChars.put(\"ꝗ\", \"q\");\n translitChars.put(\"ậ\", \"a\");\n translitChars.put(\"н\", \"n\");\n translitChars.put(\"ʄ\", \"j\");\n translitChars.put(\"ƚ\", \"l\");\n translitChars.put(\"ᶂ\", \"f\");\n translitChars.put(\"д\", \"d\");\n translitChars.put(\"ᵴ\", \"s\");\n translitChars.put(\"ꞃ\", \"r\");\n translitChars.put(\"ᶌ\", \"v\");\n translitChars.put(\"ɵ\", \"o\");\n translitChars.put(\"ḉ\", \"c\");\n translitChars.put(\"ᵤ\", \"u\");\n translitChars.put(\"ẑ\", \"z\");\n translitChars.put(\"ṹ\", \"u\");\n translitChars.put(\"ň\", \"n\");\n translitChars.put(\"ʍ\", \"w\");\n translitChars.put(\"ầ\", \"a\");\n translitChars.put(\"lj\", \"lj\");\n translitChars.put(\"ɓ\", \"b\");\n translitChars.put(\"ɼ\", \"r\");\n translitChars.put(\"ò\", \"o\");\n translitChars.put(\"ẘ\", \"w\");\n translitChars.put(\"ɗ\", \"d\");\n translitChars.put(\"ꜽ\", \"ay\");\n translitChars.put(\"ư\", \"u\");\n translitChars.put(\"ᶀ\", \"b\");\n translitChars.put(\"ǜ\", \"u\");\n translitChars.put(\"ẹ\", \"e\");\n translitChars.put(\"ǡ\", \"a\");\n translitChars.put(\"ɥ\", \"h\");\n translitChars.put(\"ṏ\", \"o\");\n translitChars.put(\"ǔ\", \"u\");\n translitChars.put(\"ʎ\", \"y\");\n translitChars.put(\"ȱ\", \"o\");\n translitChars.put(\"ệ\", \"e\");\n translitChars.put(\"ế\", \"e\");\n translitChars.put(\"ĭ\", \"i\");\n translitChars.put(\"ⱸ\", \"e\");\n translitChars.put(\"ṯ\", \"t\");\n translitChars.put(\"ᶑ\", \"d\");\n translitChars.put(\"ḧ\", \"h\");\n translitChars.put(\"ṥ\", \"s\");\n translitChars.put(\"ë\", \"e\");\n translitChars.put(\"ᴍ\", \"m\");\n translitChars.put(\"ö\", \"o\");\n translitChars.put(\"é\", \"e\");\n translitChars.put(\"ı\", \"i\");\n translitChars.put(\"ď\", \"d\");\n translitChars.put(\"ᵯ\", \"m\");\n translitChars.put(\"ỵ\", \"y\");\n translitChars.put(\"я\", \"ya\");\n translitChars.put(\"ŵ\", \"w\");\n translitChars.put(\"ề\", \"e\");\n translitChars.put(\"ứ\", \"u\");\n translitChars.put(\"ƶ\", \"z\");\n translitChars.put(\"ĵ\", \"j\");\n translitChars.put(\"ḍ\", \"d\");\n translitChars.put(\"ŭ\", \"u\");\n translitChars.put(\"ʝ\", \"j\");\n translitChars.put(\"ж\", \"zh\");\n translitChars.put(\"ê\", \"e\");\n translitChars.put(\"ǚ\", \"u\");\n translitChars.put(\"ġ\", \"g\");\n translitChars.put(\"ṙ\", \"r\");\n translitChars.put(\"ƞ\", \"n\");\n translitChars.put(\"ъ\", \"\");\n translitChars.put(\"ḗ\", \"e\");\n translitChars.put(\"ẝ\", \"s\");\n translitChars.put(\"ᶁ\", \"d\");\n translitChars.put(\"ķ\", \"k\");\n translitChars.put(\"ᴂ\", \"ae\");\n translitChars.put(\"ɘ\", \"e\");\n translitChars.put(\"ợ\", \"o\");\n translitChars.put(\"ḿ\", \"m\");\n translitChars.put(\"ꜰ\", \"f\");\n translitChars.put(\"а\", \"a\");\n translitChars.put(\"ẵ\", \"a\");\n translitChars.put(\"ꝏ\", \"oo\");\n translitChars.put(\"ᶆ\", \"m\");\n translitChars.put(\"ᵽ\", \"p\");\n translitChars.put(\"ц\", \"ts\");\n translitChars.put(\"ữ\", \"u\");\n translitChars.put(\"ⱪ\", \"k\");\n translitChars.put(\"ḥ\", \"h\");\n translitChars.put(\"ţ\", \"t\");\n translitChars.put(\"ᵱ\", \"p\");\n translitChars.put(\"ṁ\", \"m\");\n translitChars.put(\"á\", \"a\");\n translitChars.put(\"ᴎ\", \"n\");\n translitChars.put(\"ꝟ\", \"v\");\n translitChars.put(\"è\", \"e\");\n translitChars.put(\"ᶎ\", \"z\");\n translitChars.put(\"ꝺ\", \"d\");\n translitChars.put(\"ᶈ\", \"p\");\n translitChars.put(\"м\", \"m\");\n translitChars.put(\"ɫ\", \"l\");\n translitChars.put(\"ᴢ\", \"z\");\n translitChars.put(\"ɱ\", \"m\");\n translitChars.put(\"ṝ\", \"r\");\n translitChars.put(\"ṽ\", \"v\");\n translitChars.put(\"ũ\", \"u\");\n translitChars.put(\"ß\", \"ss\");\n translitChars.put(\"т\", \"t\");\n translitChars.put(\"ĥ\", \"h\");\n translitChars.put(\"ᵵ\", \"t\");\n translitChars.put(\"ʐ\", \"z\");\n translitChars.put(\"ṟ\", \"r\");\n translitChars.put(\"ɲ\", \"n\");\n translitChars.put(\"à\", \"a\");\n translitChars.put(\"ẙ\", \"y\");\n translitChars.put(\"ỳ\", \"y\");\n translitChars.put(\"ᴔ\", \"oe\");\n translitChars.put(\"ы\", \"i\");\n translitChars.put(\"ₓ\", \"x\");\n translitChars.put(\"ȗ\", \"u\");\n translitChars.put(\"ⱼ\", \"j\");\n translitChars.put(\"ẫ\", \"a\");\n translitChars.put(\"ʑ\", \"z\");\n translitChars.put(\"ẛ\", \"s\");\n translitChars.put(\"ḭ\", \"i\");\n translitChars.put(\"ꜵ\", \"ao\");\n translitChars.put(\"ɀ\", \"z\");\n translitChars.put(\"ÿ\", \"y\");\n translitChars.put(\"ǝ\", \"e\");\n translitChars.put(\"ǭ\", \"o\");\n translitChars.put(\"ᴅ\", \"d\");\n translitChars.put(\"ᶅ\", \"l\");\n translitChars.put(\"ù\", \"u\");\n translitChars.put(\"ạ\", \"a\");\n translitChars.put(\"ḅ\", \"b\");\n translitChars.put(\"ụ\", \"u\");\n translitChars.put(\"к\", \"k\");\n translitChars.put(\"ằ\", \"a\");\n translitChars.put(\"ᴛ\", \"t\");\n translitChars.put(\"ƴ\", \"y\");\n translitChars.put(\"ⱦ\", \"t\");\n translitChars.put(\"з\", \"z\");\n translitChars.put(\"ⱡ\", \"l\");\n translitChars.put(\"ȷ\", \"j\");\n translitChars.put(\"ᵶ\", \"z\");\n translitChars.put(\"ḫ\", \"h\");\n translitChars.put(\"ⱳ\", \"w\");\n translitChars.put(\"ḵ\", \"k\");\n translitChars.put(\"ờ\", \"o\");\n translitChars.put(\"î\", \"i\");\n translitChars.put(\"ģ\", \"g\");\n translitChars.put(\"ȅ\", \"e\");\n translitChars.put(\"ȧ\", \"a\");\n translitChars.put(\"ẳ\", \"a\");\n translitChars.put(\"щ\", \"sch\");\n translitChars.put(\"ɋ\", \"q\");\n translitChars.put(\"ṭ\", \"t\");\n translitChars.put(\"ꝸ\", \"um\");\n translitChars.put(\"ᴄ\", \"c\");\n translitChars.put(\"ẍ\", \"x\");\n translitChars.put(\"ủ\", \"u\");\n translitChars.put(\"ỉ\", \"i\");\n translitChars.put(\"ᴚ\", \"r\");\n translitChars.put(\"ś\", \"s\");\n translitChars.put(\"ꝋ\", \"o\");\n translitChars.put(\"ỹ\", \"y\");\n translitChars.put(\"ṡ\", \"s\");\n translitChars.put(\"nj\", \"nj\");\n translitChars.put(\"ȁ\", \"a\");\n translitChars.put(\"ẗ\", \"t\");\n translitChars.put(\"ĺ\", \"l\");\n translitChars.put(\"ž\", \"z\");\n translitChars.put(\"ᵺ\", \"th\");\n translitChars.put(\"ƌ\", \"d\");\n translitChars.put(\"ș\", \"s\");\n translitChars.put(\"š\", \"s\");\n translitChars.put(\"ᶙ\", \"u\");\n translitChars.put(\"ẽ\", \"e\");\n translitChars.put(\"ẜ\", \"s\");\n translitChars.put(\"ɇ\", \"e\");\n translitChars.put(\"ṷ\", \"u\");\n translitChars.put(\"ố\", \"o\");\n translitChars.put(\"ȿ\", \"s\");\n translitChars.put(\"ᴠ\", \"v\");\n translitChars.put(\"ꝭ\", \"is\");\n translitChars.put(\"ᴏ\", \"o\");\n translitChars.put(\"ɛ\", \"e\");\n translitChars.put(\"ǻ\", \"a\");\n translitChars.put(\"ffl\", \"ffl\");\n translitChars.put(\"ⱺ\", \"o\");\n translitChars.put(\"ȋ\", \"i\");\n translitChars.put(\"ᵫ\", \"ue\");\n translitChars.put(\"ȡ\", \"d\");\n translitChars.put(\"ⱬ\", \"z\");\n translitChars.put(\"ẁ\", \"w\");\n translitChars.put(\"ᶏ\", \"a\");\n translitChars.put(\"ꞇ\", \"t\");\n translitChars.put(\"ğ\", \"g\");\n translitChars.put(\"ɳ\", \"n\");\n translitChars.put(\"ʛ\", \"g\");\n translitChars.put(\"ᴜ\", \"u\");\n translitChars.put(\"ф\", \"f\");\n translitChars.put(\"ẩ\", \"a\");\n translitChars.put(\"ṅ\", \"n\");\n translitChars.put(\"ɨ\", \"i\");\n translitChars.put(\"ᴙ\", \"r\");\n translitChars.put(\"ǎ\", \"a\");\n translitChars.put(\"ſ\", \"s\");\n translitChars.put(\"у\", \"u\");\n translitChars.put(\"ȫ\", \"o\");\n translitChars.put(\"ɿ\", \"r\");\n translitChars.put(\"ƭ\", \"t\");\n translitChars.put(\"ḯ\", \"i\");\n translitChars.put(\"ǽ\", \"ae\");\n translitChars.put(\"ⱱ\", \"v\");\n translitChars.put(\"ɶ\", \"oe\");\n translitChars.put(\"ṃ\", \"m\");\n translitChars.put(\"ż\", \"z\");\n translitChars.put(\"ĕ\", \"e\");\n translitChars.put(\"ꜻ\", \"av\");\n translitChars.put(\"ở\", \"o\");\n translitChars.put(\"ễ\", \"e\");\n translitChars.put(\"ɬ\", \"l\");\n translitChars.put(\"ị\", \"i\");\n translitChars.put(\"ᵭ\", \"d\");\n translitChars.put(\"st\", \"st\");\n translitChars.put(\"ḷ\", \"l\");\n translitChars.put(\"ŕ\", \"r\");\n translitChars.put(\"ᴕ\", \"ou\");\n translitChars.put(\"ʈ\", \"t\");\n translitChars.put(\"ā\", \"a\");\n translitChars.put(\"э\", \"e\");\n translitChars.put(\"ḙ\", \"e\");\n translitChars.put(\"ᴑ\", \"o\");\n translitChars.put(\"ç\", \"c\");\n translitChars.put(\"ᶊ\", \"s\");\n translitChars.put(\"ặ\", \"a\");\n translitChars.put(\"ų\", \"u\");\n translitChars.put(\"ả\", \"a\");\n translitChars.put(\"ǥ\", \"g\");\n translitChars.put(\"р\", \"r\");\n translitChars.put(\"ꝁ\", \"k\");\n translitChars.put(\"ẕ\", \"z\");\n translitChars.put(\"ŝ\", \"s\");\n translitChars.put(\"ḕ\", \"e\");\n translitChars.put(\"ɠ\", \"g\");\n translitChars.put(\"ꝉ\", \"l\");\n translitChars.put(\"ꝼ\", \"f\");\n translitChars.put(\"ᶍ\", \"x\");\n translitChars.put(\"х\", \"h\");\n translitChars.put(\"ǒ\", \"o\");\n translitChars.put(\"ę\", \"e\");\n translitChars.put(\"ổ\", \"o\");\n translitChars.put(\"ƫ\", \"t\");\n translitChars.put(\"ǫ\", \"o\");\n translitChars.put(\"i̇\", \"i\");\n translitChars.put(\"ṇ\", \"n\");\n translitChars.put(\"ć\", \"c\");\n translitChars.put(\"ᵷ\", \"g\");\n translitChars.put(\"ẅ\", \"w\");\n translitChars.put(\"ḑ\", \"d\");\n translitChars.put(\"ḹ\", \"l\");\n translitChars.put(\"ч\", \"ch\");\n translitChars.put(\"œ\", \"oe\");\n translitChars.put(\"ᵳ\", \"r\");\n translitChars.put(\"ļ\", \"l\");\n translitChars.put(\"ȑ\", \"r\");\n translitChars.put(\"ȭ\", \"o\");\n translitChars.put(\"ᵰ\", \"n\");\n translitChars.put(\"ᴁ\", \"ae\");\n translitChars.put(\"ŀ\", \"l\");\n translitChars.put(\"ä\", \"a\");\n translitChars.put(\"ƥ\", \"p\");\n translitChars.put(\"ỏ\", \"o\");\n translitChars.put(\"į\", \"i\");\n translitChars.put(\"ȓ\", \"r\");\n translitChars.put(\"dž\", \"dz\");\n translitChars.put(\"ḡ\", \"g\");\n translitChars.put(\"ṻ\", \"u\");\n translitChars.put(\"ō\", \"o\");\n translitChars.put(\"ľ\", \"l\");\n translitChars.put(\"ẃ\", \"w\");\n translitChars.put(\"ț\", \"t\");\n translitChars.put(\"ń\", \"n\");\n translitChars.put(\"ɍ\", \"r\");\n translitChars.put(\"ȃ\", \"a\");\n translitChars.put(\"ü\", \"u\");\n translitChars.put(\"ꞁ\", \"l\");\n translitChars.put(\"ᴐ\", \"o\");\n translitChars.put(\"ớ\", \"o\");\n translitChars.put(\"ᴃ\", \"b\");\n translitChars.put(\"ɹ\", \"r\");\n translitChars.put(\"ᵲ\", \"r\");\n translitChars.put(\"ʏ\", \"y\");\n translitChars.put(\"ᵮ\", \"f\");\n translitChars.put(\"ⱨ\", \"h\");\n translitChars.put(\"ŏ\", \"o\");\n translitChars.put(\"ú\", \"u\");\n translitChars.put(\"ṛ\", \"r\");\n translitChars.put(\"ʮ\", \"h\");\n translitChars.put(\"ó\", \"o\");\n translitChars.put(\"ů\", \"u\");\n translitChars.put(\"ỡ\", \"o\");\n translitChars.put(\"ṕ\", \"p\");\n translitChars.put(\"ᶖ\", \"i\");\n translitChars.put(\"ự\", \"u\");\n translitChars.put(\"ã\", \"a\");\n translitChars.put(\"ᵢ\", \"i\");\n translitChars.put(\"ṱ\", \"t\");\n translitChars.put(\"ể\", \"e\");\n translitChars.put(\"ử\", \"u\");\n translitChars.put(\"í\", \"i\");\n translitChars.put(\"ɔ\", \"o\");\n translitChars.put(\"с\", \"s\");\n translitChars.put(\"й\", \"i\");\n translitChars.put(\"ɺ\", \"r\");\n translitChars.put(\"ɢ\", \"g\");\n translitChars.put(\"ř\", \"r\");\n translitChars.put(\"ẖ\", \"h\");\n translitChars.put(\"ű\", \"u\");\n translitChars.put(\"ȍ\", \"o\");\n translitChars.put(\"ш\", \"sh\");\n translitChars.put(\"ḻ\", \"l\");\n translitChars.put(\"ḣ\", \"h\");\n translitChars.put(\"ȶ\", \"t\");\n translitChars.put(\"ņ\", \"n\");\n translitChars.put(\"ᶒ\", \"e\");\n translitChars.put(\"ì\", \"i\");\n translitChars.put(\"ẉ\", \"w\");\n translitChars.put(\"б\", \"b\");\n translitChars.put(\"ē\", \"e\");\n translitChars.put(\"ᴇ\", \"e\");\n translitChars.put(\"ł\", \"l\");\n translitChars.put(\"ộ\", \"o\");\n translitChars.put(\"ɭ\", \"l\");\n translitChars.put(\"ẏ\", \"y\");\n translitChars.put(\"ᴊ\", \"j\");\n translitChars.put(\"ḱ\", \"k\");\n translitChars.put(\"ṿ\", \"v\");\n translitChars.put(\"ȩ\", \"e\");\n translitChars.put(\"â\", \"a\");\n translitChars.put(\"ş\", \"s\");\n translitChars.put(\"ŗ\", \"r\");\n translitChars.put(\"ʋ\", \"v\");\n translitChars.put(\"ₐ\", \"a\");\n translitChars.put(\"ↄ\", \"c\");\n translitChars.put(\"ᶓ\", \"e\");\n translitChars.put(\"ɰ\", \"m\");\n translitChars.put(\"е\", \"e\");\n translitChars.put(\"ᴡ\", \"w\");\n translitChars.put(\"ȏ\", \"o\");\n translitChars.put(\"č\", \"c\");\n translitChars.put(\"ǵ\", \"g\");\n translitChars.put(\"ĉ\", \"c\");\n translitChars.put(\"ю\", \"yu\");\n translitChars.put(\"ᶗ\", \"o\");\n translitChars.put(\"ꝃ\", \"k\");\n translitChars.put(\"ꝙ\", \"q\");\n translitChars.put(\"г\", \"g\");\n translitChars.put(\"ṑ\", \"o\");\n translitChars.put(\"ꜱ\", \"s\");\n translitChars.put(\"ṓ\", \"o\");\n translitChars.put(\"ȟ\", \"h\");\n translitChars.put(\"ő\", \"o\");\n translitChars.put(\"ꜩ\", \"tz\");\n translitChars.put(\"ẻ\", \"e\");\n translitChars.put(\"о\", \"o\");\n }\n StringBuilder dst = new StringBuilder(src.length());\n int len = src.length();\n for (int a = 0; a < len; a++) {\n String ch = src.substring(a, a + 1);\n String tch = translitChars.get(ch);\n if (tch != null) {\n dst.append(tch);\n } else {\n dst.append(ch);\n }\n }\n return dst.toString();\n }\n\n abstract public static class PluralRules {\n abstract int quantityForNumber(int n);\n }\n\n public static class PluralRules_Zero extends PluralRules {\n public int quantityForNumber(int count) {\n if (count == 0 || count == 1) {\n return QUANTITY_ONE;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Welsh extends PluralRules {\n public int quantityForNumber(int count) {\n if (count == 0) {\n return QUANTITY_ZERO;\n } else if (count == 1) {\n return QUANTITY_ONE;\n } else if (count == 2) {\n return QUANTITY_TWO;\n } else if (count == 3) {\n return QUANTITY_FEW;\n } else if (count == 6) {\n return QUANTITY_MANY;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Two extends PluralRules {\n public int quantityForNumber(int count) {\n if (count == 1) {\n return QUANTITY_ONE;\n } else if (count == 2) {\n return QUANTITY_TWO;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Tachelhit extends PluralRules {\n public int quantityForNumber(int count) {\n if (count >= 0 && count <= 1) {\n return QUANTITY_ONE;\n } else if (count >= 2 && count <= 10) {\n return QUANTITY_FEW;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Slovenian extends PluralRules {\n public int quantityForNumber(int count) {\n int rem100 = count % 100;\n if (rem100 == 1) {\n return QUANTITY_ONE;\n } else if (rem100 == 2) {\n return QUANTITY_TWO;\n } else if (rem100 >= 3 && rem100 <= 4) {\n return QUANTITY_FEW;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Romanian extends PluralRules {\n public int quantityForNumber(int count) {\n int rem100 = count % 100;\n if (count == 1) {\n return QUANTITY_ONE;\n } else if ((count == 0 || (rem100 >= 1 && rem100 <= 19))) {\n return QUANTITY_FEW;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Polish extends PluralRules {\n public int quantityForNumber(int count) {\n int rem100 = count % 100;\n int rem10 = count % 10;\n if (count == 1) {\n return QUANTITY_ONE;\n } else if (rem10 >= 2 && rem10 <= 4 && !(rem100 >= 12 && rem100 <= 14) && !(rem100 >= 22 && rem100 <= 24)) {\n return QUANTITY_FEW;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_One extends PluralRules {\n public int quantityForNumber(int count) {\n return count == 1 ? QUANTITY_ONE : QUANTITY_OTHER;\n }\n }\n\n public static class PluralRules_None extends PluralRules {\n public int quantityForNumber(int count) {\n return QUANTITY_OTHER;\n }\n }\n\n public static class PluralRules_Maltese extends PluralRules {\n public int quantityForNumber(int count) {\n int rem100 = count % 100;\n if (count == 1) {\n return QUANTITY_ONE;\n } else if (count == 0 || (rem100 >= 2 && rem100 <= 10)) {\n return QUANTITY_FEW;\n } else if (rem100 >= 11 && rem100 <= 19) {\n return QUANTITY_MANY;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Macedonian extends PluralRules {\n public int quantityForNumber(int count) {\n if (count % 10 == 1 && count != 11) {\n return QUANTITY_ONE;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Lithuanian extends PluralRules {\n public int quantityForNumber(int count) {\n int rem100 = count % 100;\n int rem10 = count % 10;\n if (rem10 == 1 && !(rem100 >= 11 && rem100 <= 19)) {\n return QUANTITY_ONE;\n } else if (rem10 >= 2 && rem10 <= 9 && !(rem100 >= 11 && rem100 <= 19)) {\n return QUANTITY_FEW;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Latvian extends PluralRules {\n public int quantityForNumber(int count) {\n if (count == 0) {\n return QUANTITY_ZERO;\n } else if (count % 10 == 1 && count % 100 != 11) {\n return QUANTITY_ONE;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Langi extends PluralRules {\n public int quantityForNumber(int count) {\n if (count == 0) {\n return QUANTITY_ZERO;\n } else if (count > 0 && count < 2) {\n return QUANTITY_ONE;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_French extends PluralRules {\n public int quantityForNumber(int count) {\n if (count >= 0 && count < 2) {\n return QUANTITY_ONE;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Czech extends PluralRules {\n public int quantityForNumber(int count) {\n if (count == 1) {\n return QUANTITY_ONE;\n } else if (count >= 2 && count <= 4) {\n return QUANTITY_FEW;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Breton extends PluralRules {\n public int quantityForNumber(int count) {\n if (count == 0) {\n return QUANTITY_ZERO;\n } else if (count == 1) {\n return QUANTITY_ONE;\n } else if (count == 2) {\n return QUANTITY_TWO;\n } else if (count == 3) {\n return QUANTITY_FEW;\n } else if (count == 6) {\n return QUANTITY_MANY;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Balkan extends PluralRules {\n public int quantityForNumber(int count) {\n int rem100 = count % 100;\n int rem10 = count % 10;\n if (rem10 == 1 && rem100 != 11) {\n return QUANTITY_ONE;\n } else if (rem10 >= 2 && rem10 <= 4 && !(rem100 >= 12 && rem100 <= 14)) {\n return QUANTITY_FEW;\n } else if ((rem10 == 0 || (rem10 >= 5 && rem10 <= 9) || (rem100 >= 11 && rem100 <= 14))) {\n return QUANTITY_MANY;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n\n public static class PluralRules_Arabic extends PluralRules {\n public int quantityForNumber(int count) {\n int rem100 = count % 100;\n if (count == 0) {\n return QUANTITY_ZERO;\n } else if (count == 1) {\n return QUANTITY_ONE;\n } else if (count == 2) {\n return QUANTITY_TWO;\n } else if (rem100 >= 3 && rem100 <= 10) {\n return QUANTITY_FEW;\n } else if (rem100 >= 11 && rem100 <= 99) {\n return QUANTITY_MANY;\n } else {\n return QUANTITY_OTHER;\n }\n }\n }\n}", "public class ApplicationLoader extends Application {\n\n private GoogleCloudMessaging gcm;\n private AtomicInteger msgId = new AtomicInteger();\n private String regid;\n public static final String EXTRA_MESSAGE = \"message\";\n public static final String PROPERTY_REG_ID = \"registration_id\";\n private static final String PROPERTY_APP_VERSION = \"appVersion\";\n private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;\n private static Drawable cachedWallpaper;\n private static int selectedColor;\n private static boolean isCustomTheme;\n private static final Object sync = new Object();\n\n public static volatile Context applicationContext;\n public static volatile Handler applicationHandler;\n private static volatile boolean applicationInited = false;\n\n public static volatile boolean isScreenOn = false;\n public static volatile boolean mainInterfacePaused = true;\n\n public static boolean isCustomTheme() {\n return isCustomTheme;\n }\n\n public static int getSelectedColor() {\n return selectedColor;\n }\n\n public static void reloadWallpaper() {\n cachedWallpaper = null;\n loadWallpaper();\n }\n\n public static void loadWallpaper() {\n if (cachedWallpaper != null) {\n return;\n }\n Utilities.searchQueue.postRunnable(new Runnable() {\n @Override\n public void run() {\n synchronized (sync) {\n int selectedColor = 0;\n try {\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"mainconfig\", Activity.MODE_PRIVATE);\n int selectedBackground = preferences.getInt(\"selectedBackground\", 1000001);\n selectedColor = preferences.getInt(\"selectedColor\", 0);\n int cacheColorHint = 0;\n if (selectedColor == 0) {\n if (selectedBackground == 1000001) {\n cachedWallpaper = applicationContext.getResources().getDrawable(R.drawable.background_hd);\n isCustomTheme = false;\n } else {\n File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), \"wallpaper.jpg\");\n if (toFile.exists()) {\n cachedWallpaper = Drawable.createFromPath(toFile.getAbsolutePath());\n isCustomTheme = true;\n } else {\n cachedWallpaper = applicationContext.getResources().getDrawable(R.drawable.background_hd);\n isCustomTheme = false;\n }\n }\n }\n } catch (Throwable throwable) {\n //ignore\n }\n if (cachedWallpaper == null) {\n if (selectedColor == 0) {\n selectedColor = -2693905;\n }\n cachedWallpaper = new ColorDrawable(selectedColor);\n }\n }\n }\n });\n }\n\n public static Drawable getCachedWallpaper() {\n synchronized (sync) {\n return cachedWallpaper;\n }\n }\n\n public static void postInitApplication() {\n if (applicationInited) {\n return;\n }\n\n applicationInited = true;\n\n try {\n TemplateSupport.getInstance();\n LocaleController.getInstance();\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n try {\n final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);\n filter.addAction(Intent.ACTION_SCREEN_OFF);\n final BroadcastReceiver mReceiver = new ScreenReceiver();\n applicationContext.registerReceiver(mReceiver, filter);\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n try {\n PowerManager pm = (PowerManager)ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE);\n isScreenOn = pm.isScreenOn();\n FileLog.e(\"tmessages\", \"screen state = \" + isScreenOn);\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n\n UserConfig.loadConfig();\n if (UserConfig.getCurrentUser() != null) {\n MessagesController.getInstance().putUser(UserConfig.getCurrentUser(), true);\n ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone);\n ConnectionsManager.getInstance().initPushConnection();\n MessagesController.getInstance().getBlockedUsers(true);\n SendMessagesHelper.getInstance().checkUnsentMessages();\n }\n\n ApplicationLoader app = (ApplicationLoader)ApplicationLoader.applicationContext;\n app.initPlayServices();\n FileLog.e(\"tmessages\", \"app initied\");\n\n ContactsController.getInstance().checkAppAccount();\n MediaController.getInstance();\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n if (Build.VERSION.SDK_INT < 11) {\n java.lang.System.setProperty(\"java.net.preferIPv4Stack\", \"true\");\n java.lang.System.setProperty(\"java.net.preferIPv6Addresses\", \"false\");\n }\n\n applicationContext = getApplicationContext();\n NativeLoader.initNativeLibs(ApplicationLoader.applicationContext);\n\n if (Build.VERSION.SDK_INT >= 14) {\n new ForegroundDetector(this);\n }\n\n applicationHandler = new Handler(applicationContext.getMainLooper());\n\n SharedPreferences preferences = applicationContext.getSharedPreferences(\"Notifications\", MODE_PRIVATE);\n if (preferences.getBoolean(\"pushService\", false)) {\n startPushService();\n }\n }\n\n public static void startPushService() {\n SharedPreferences preferences = applicationContext.getSharedPreferences(\"Notifications\", MODE_PRIVATE);\n\n if (preferences.getBoolean(\"pushService\", false)) {\n applicationContext.startService(new Intent(applicationContext, NotificationsService.class));\n\n if (android.os.Build.VERSION.SDK_INT >= 19) {\n// Calendar cal = Calendar.getInstance();\n// PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0);\n// AlarmManager alarm = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE);\n// alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30000, pintent);\n\n PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0);\n AlarmManager alarm = (AlarmManager)applicationContext.getSystemService(Context.ALARM_SERVICE);\n alarm.cancel(pintent);\n }\n } else {\n stopPushService();\n }\n }\n\n public static void stopPushService() {\n applicationContext.stopService(new Intent(applicationContext, NotificationsService.class));\n\n PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0);\n AlarmManager alarm = (AlarmManager)applicationContext.getSystemService(Context.ALARM_SERVICE);\n alarm.cancel(pintent);\n }\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n try {\n LocaleController.getInstance().onDeviceConfigurationChange(newConfig);\n AndroidUtilities.checkDisplaySize();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private void initPlayServices() {\n if (checkPlayServices()) {\n gcm = GoogleCloudMessaging.getInstance(this);\n regid = getRegistrationId();\n\n if (regid.length() == 0) {\n registerInBackground();\n } else {\n sendRegistrationIdToBackend(false);\n }\n } else {\n FileLog.d(\"tmessages\", \"No valid Google Play Services APK found.\");\n }\n }\n\n private boolean checkPlayServices() {\n int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);\n return resultCode == ConnectionResult.SUCCESS;\n /*if (resultCode != ConnectionResult.SUCCESS) {\n if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {\n GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();\n } else {\n Log.i(\"tmessages\", \"This device is not supported.\");\n }\n return false;\n }\n return true;*/\n }\n\n private String getRegistrationId() {\n final SharedPreferences prefs = getGCMPreferences(applicationContext);\n String registrationId = prefs.getString(PROPERTY_REG_ID, \"\");\n if (registrationId.length() == 0) {\n FileLog.d(\"tmessages\", \"Registration not found.\");\n return \"\";\n }\n int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);\n int currentVersion = getAppVersion();\n if (registeredVersion != currentVersion) {\n FileLog.d(\"tmessages\", \"App version changed.\");\n return \"\";\n }\n return registrationId;\n }\n\n private SharedPreferences getGCMPreferences(Context context) {\n return getSharedPreferences(ApplicationLoader.class.getSimpleName(), Context.MODE_PRIVATE);\n }\n\n public static int getAppVersion() {\n try {\n PackageInfo packageInfo = applicationContext.getPackageManager().getPackageInfo(applicationContext.getPackageName(), 0);\n return packageInfo.versionCode;\n } catch (PackageManager.NameNotFoundException e) {\n throw new RuntimeException(\"Could not get package name: \" + e);\n }\n }\n\n private void registerInBackground() {\n AsyncTask<String, String, Boolean> task = new AsyncTask<String, String, Boolean>() {\n @Override\n protected Boolean doInBackground(String... objects) {\n if (gcm == null) {\n gcm = GoogleCloudMessaging.getInstance(applicationContext);\n }\n int count = 0;\n while (count < 1000) {\n try {\n count++;\n regid = gcm.register(BuildVars.GCM_SENDER_ID);\n sendRegistrationIdToBackend(true);\n storeRegistrationId(applicationContext, regid);\n return true;\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n try {\n if (count % 20 == 0) {\n Thread.sleep(60000 * 30);\n } else {\n Thread.sleep(5000);\n }\n } catch (InterruptedException e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n return false;\n }\n };\n\n if (android.os.Build.VERSION.SDK_INT >= 11) {\n task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);\n } else {\n task.execute(null, null, null);\n }\n }\n\n private void sendRegistrationIdToBackend(final boolean isNew) {\n Utilities.stageQueue.postRunnable(new Runnable() {\n @Override\n public void run() {\n UserConfig.pushString = regid;\n UserConfig.registeredForPush = !isNew;\n UserConfig.saveConfig(false);\n if (UserConfig.getClientUserId() != 0) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n MessagesController.getInstance().registerForPush(regid);\n }\n });\n }\n }\n });\n }\n\n private void storeRegistrationId(Context context, String regId) {\n final SharedPreferences prefs = getGCMPreferences(context);\n int appVersion = getAppVersion();\n FileLog.e(\"tmessages\", \"Saving regId on app version \" + appVersion);\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(PROPERTY_REG_ID, regId);\n editor.putInt(PROPERTY_APP_VERSION, appVersion);\n editor.commit();\n }\n}", "public class MessagesController implements NotificationCenter.NotificationCenterDelegate {\n\n private ConcurrentHashMap<Integer, TLRPC.Chat> chats = new ConcurrentHashMap<>(100, 1.0f, 2);\n private ConcurrentHashMap<Integer, TLRPC.EncryptedChat> encryptedChats = new ConcurrentHashMap<>(10, 1.0f, 2);\n private ConcurrentHashMap<Integer, TLRPC.User> users = new ConcurrentHashMap<>(100, 1.0f, 2);\n private ConcurrentHashMap<String, TLRPC.User> usersByUsernames = new ConcurrentHashMap<>(100, 1.0f, 2);\n\n public ArrayList<TLRPC.TL_dialog> dialogs = new ArrayList<>();\n public ArrayList<TLRPC.TL_dialog> dialogsServerOnly = new ArrayList<>();\n public ConcurrentHashMap<Long, TLRPC.TL_dialog> dialogs_dict = new ConcurrentHashMap<>(100, 1.0f, 2);\n public HashMap<Integer, MessageObject> dialogMessage = new HashMap<>();\n public ConcurrentHashMap<Long, ArrayList<PrintingUser>> printingUsers = new ConcurrentHashMap<>(20, 1.0f, 2);\n public HashMap<Long, CharSequence> printingStrings = new HashMap<>();\n public HashMap<Long, Boolean> sendingTypings = new HashMap<>();\n public ConcurrentHashMap<Integer, Integer> onlinePrivacy = new ConcurrentHashMap<>(20, 1.0f, 2);\n private int lastPrintingStringCount = 0;\n\n public boolean loadingBlockedUsers = false;\n public ArrayList<Integer> blockedUsers = new ArrayList<>();\n\n private ArrayList<TLRPC.Updates> updatesQueueSeq = new ArrayList<>();\n private ArrayList<TLRPC.Updates> updatesQueuePts = new ArrayList<>();\n private ArrayList<TLRPC.Updates> updatesQueueQts = new ArrayList<>();\n private long updatesStartWaitTimeSeq = 0;\n private long updatesStartWaitTimePts = 0;\n private long updatesStartWaitTimeQts = 0;\n private ArrayList<Integer> loadingFullUsers = new ArrayList<>();\n private ArrayList<Integer> loadedFullUsers = new ArrayList<>();\n private ArrayList<Integer> loadingFullChats = new ArrayList<>();\n private ArrayList<Integer> loadedFullChats = new ArrayList<>();\n\n private ArrayList<Integer> reloadingMessages = new ArrayList<>();\n\n private boolean gettingNewDeleteTask = false;\n private int currentDeletingTaskTime = 0;\n private ArrayList<Integer> currentDeletingTaskMids = null;\n private Runnable currentDeleteTaskRunnable = null;\n\n public int totalDialogsCount = 0;\n public boolean loadingDialogs = false;\n public boolean dialogsEndReached = false;\n public boolean gettingDifference = false;\n public boolean gettingDifferenceAgain = false;\n public boolean updatingState = false;\n public boolean firstGettingTask = false;\n public boolean registeringForPush = false;\n\n private long lastStatusUpdateTime = 0;\n private long statusRequest = 0;\n private int statusSettingState = 0;\n private boolean offlineSent = false;\n private String uploadingAvatar = null;\n\n public boolean enableJoined = true;\n public int fontSize = AndroidUtilities.dp(16);\n public int maxGroupCount = 200;\n public int maxBroadcastCount = 100;\n public int groupBigSize;\n private ArrayList<TLRPC.TL_disabledFeature> disabledFeatures = new ArrayList<>();\n\n private class UserActionUpdatesSeq extends TLRPC.Updates {\n\n }\n\n private class UserActionUpdatesPts extends TLRPC.Updates {\n\n }\n\n public static final int UPDATE_MASK_NAME = 1;\n public static final int UPDATE_MASK_AVATAR = 2;\n public static final int UPDATE_MASK_STATUS = 4;\n public static final int UPDATE_MASK_CHAT_AVATAR = 8;\n public static final int UPDATE_MASK_CHAT_NAME = 16;\n public static final int UPDATE_MASK_CHAT_MEMBERS = 32;\n public static final int UPDATE_MASK_USER_PRINT = 64;\n public static final int UPDATE_MASK_USER_PHONE = 128;\n public static final int UPDATE_MASK_READ_DIALOG_MESSAGE = 256;\n public static final int UPDATE_MASK_SELECT_DIALOG = 512;\n public static final int UPDATE_MASK_PHONE = 1024;\n public static final int UPDATE_MASK_NEW_MESSAGE = 2048;\n public static final int UPDATE_MASK_SEND_STATE = 4096;\n public static final int UPDATE_MASK_ALL = UPDATE_MASK_AVATAR | UPDATE_MASK_STATUS | UPDATE_MASK_NAME | UPDATE_MASK_CHAT_AVATAR | UPDATE_MASK_CHAT_NAME | UPDATE_MASK_CHAT_MEMBERS | UPDATE_MASK_USER_PRINT | UPDATE_MASK_USER_PHONE | UPDATE_MASK_READ_DIALOG_MESSAGE | UPDATE_MASK_PHONE;\n\n public static class PrintingUser {\n public long lastTime;\n public int userId;\n }\n\n private static volatile MessagesController Instance = null;\n public static MessagesController getInstance() {\n MessagesController localInstance = Instance;\n if (localInstance == null) {\n synchronized (MessagesController.class) {\n localInstance = Instance;\n if (localInstance == null) {\n Instance = localInstance = new MessagesController();\n }\n }\n }\n return localInstance;\n }\n\n public MessagesController() {\n ImageLoader.getInstance();\n MessagesStorage.getInstance();\n NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidUpload);\n NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailUpload);\n NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded);\n NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad);\n NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByServer);\n addSupportUser();\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"Notifications\", Activity.MODE_PRIVATE);\n enableJoined = preferences.getBoolean(\"EnableContactJoined\", false);\n\n preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"mainconfig\", Activity.MODE_PRIVATE);\n maxGroupCount = preferences.getInt(\"maxGroupCount\", 200);\n maxBroadcastCount = preferences.getInt(\"maxBroadcastCount\", 100);\n groupBigSize = preferences.getInt(\"groupBigSize\", 10);\n fontSize = preferences.getInt(\"fons_size\", AndroidUtilities.isTablet() ? 18 : 16);\n String disabledFeaturesString = preferences.getString(\"disabledFeatures\", null);\n if (disabledFeaturesString != null && disabledFeaturesString.length() != 0) {\n try {\n byte[] bytes = Base64.decode(disabledFeaturesString, Base64.DEFAULT);\n if (bytes != null) {\n SerializedData data = new SerializedData(bytes);\n int count = data.readInt32();\n for (int a = 0; a < count; a++) {\n TLRPC.TL_disabledFeature feature = (TLRPC.TL_disabledFeature) TLClassStore.Instance().TLdeserialize(data, data.readInt32());\n if (feature != null && feature.feature != null && feature.description != null) {\n disabledFeatures.add(feature);\n }\n }\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n }\n\n public void updateConfig(final TLRPC.TL_config config) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n maxBroadcastCount = config.broadcast_size_max;\n maxGroupCount = config.chat_size_max;\n groupBigSize = config.chat_big_size;\n disabledFeatures = config.disabled_features;\n\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"mainconfig\", Activity.MODE_PRIVATE);\n SharedPreferences.Editor editor = preferences.edit();\n editor.putInt(\"maxGroupCount\", maxGroupCount);\n editor.putInt(\"maxBroadcastCount\", maxBroadcastCount);\n editor.putInt(\"groupBigSize\", groupBigSize);\n try {\n SerializedData data = new SerializedData();\n data.writeInt32(disabledFeatures.size());\n for (TLRPC.TL_disabledFeature disabledFeature : disabledFeatures) {\n disabledFeature.serializeToStream(data);\n }\n String string = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT);\n if (string != null && string.length() != 0) {\n editor.putString(\"disabledFeatures\", string);\n }\n } catch (Exception e) {\n editor.remove(\"disabledFeatures\");\n FileLog.e(\"tmessages\", e);\n }\n editor.commit();\n }\n });\n }\n\n public static boolean isFeatureEnabled(String feature, BaseFragment fragment) {\n if (feature == null || feature.length() == 0 || getInstance().disabledFeatures.isEmpty() || fragment == null) {\n return true;\n }\n for (TLRPC.TL_disabledFeature disabledFeature : getInstance().disabledFeatures) {\n if (disabledFeature.feature.equals(feature)) {\n if (fragment.getParentActivity() != null) {\n AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity());\n builder.setTitle(\"Oops!\");\n builder.setPositiveButton(LocaleController.getString(\"OK\", R.string.OK), null);\n builder.setMessage(disabledFeature.description);\n fragment.showAlertDialog(builder);\n }\n return false;\n }\n }\n return true;\n }\n\n public void addSupportUser() {\n TLRPC.TL_userForeign user = new TLRPC.TL_userForeign();\n user.phone = \"333\";\n user.id = 333000;\n user.first_name = \"Telegram\";\n user.last_name = \"\";\n user.status = null;\n user.photo = new TLRPC.TL_userProfilePhotoEmpty();\n putUser(user, true);\n\n user = new TLRPC.TL_userForeign();\n user.phone = \"42777\";\n user.id = 777000;\n user.first_name = \"Telegram\";\n user.last_name = \"Notifications\";\n user.status = null;\n user.photo = new TLRPC.TL_userProfilePhotoEmpty();\n putUser(user, true);\n }\n\n public static TLRPC.InputUser getInputUser(TLRPC.User user) {\n if (user == null) {\n return null;\n }\n TLRPC.InputUser inputUser = null;\n if (user.id == UserConfig.getClientUserId()) {\n inputUser = new TLRPC.TL_inputUserSelf();\n } else if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) {\n inputUser = new TLRPC.TL_inputUserForeign();\n inputUser.user_id = user.id;\n inputUser.access_hash = user.access_hash;\n } else {\n inputUser = new TLRPC.TL_inputUserContact();\n inputUser.user_id = user.id;\n }\n return inputUser;\n }\n\n @Override\n public void didReceivedNotification(int id, Object... args) {\n if (id == NotificationCenter.FileDidUpload) {\n final String location = (String)args[0];\n final TLRPC.InputFile file = (TLRPC.InputFile)args[1];\n final TLRPC.InputEncryptedFile encryptedFile = (TLRPC.InputEncryptedFile)args[2];\n\n if (uploadingAvatar != null && uploadingAvatar.equals(location)) {\n TLRPC.TL_photos_uploadProfilePhoto req = new TLRPC.TL_photos_uploadProfilePhoto();\n req.caption = \"\";\n req.crop = new TLRPC.TL_inputPhotoCropAuto();\n req.file = file;\n req.geo_point = new TLRPC.TL_inputGeoPointEmpty();\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n TLRPC.User user = getUser(UserConfig.getClientUserId());\n if (user == null) {\n user = UserConfig.getCurrentUser();\n putUser(user, true);\n } else {\n UserConfig.setCurrentUser(user);\n }\n if (user == null) {\n return;\n }\n TLRPC.TL_photos_photo photo = (TLRPC.TL_photos_photo) response;\n ArrayList<TLRPC.PhotoSize> sizes = photo.photo.sizes;\n TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 100);\n TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 1000);\n user.photo = new TLRPC.TL_userProfilePhoto();\n user.photo.photo_id = photo.photo.id;\n if (smallSize != null) {\n user.photo.photo_small = smallSize.location;\n }\n if (bigSize != null) {\n user.photo.photo_big = bigSize.location;\n } else if (smallSize != null) {\n user.photo.photo_small = smallSize.location;\n }\n MessagesStorage.getInstance().clearUserPhotos(user.id);\n ArrayList<TLRPC.User> users = new ArrayList<>();\n users.add(user);\n MessagesStorage.getInstance().putUsersAndChats(users, null, false, true);\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_AVATAR);\n UserConfig.saveConfig(true);\n }\n });\n }\n }\n });\n }\n } else if (id == NotificationCenter.FileDidFailUpload) {\n final String location = (String) args[0];\n final boolean enc = (Boolean) args[1];\n\n if (uploadingAvatar != null && uploadingAvatar.equals(location)) {\n uploadingAvatar = null;\n }\n } else if (id == NotificationCenter.messageReceivedByServer) {\n Integer msgId = (Integer)args[0];\n MessageObject obj = dialogMessage.get(msgId);\n if (obj != null) {\n Integer newMsgId = (Integer)args[1];\n dialogMessage.remove(msgId);\n dialogMessage.put(newMsgId, obj);\n obj.messageOwner.id = newMsgId;\n obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;\n\n long uid;\n if (obj.messageOwner.to_id.chat_id != 0) {\n uid = -obj.messageOwner.to_id.chat_id;\n } else {\n if (obj.messageOwner.to_id.user_id == UserConfig.getClientUserId()) {\n obj.messageOwner.to_id.user_id = obj.messageOwner.from_id;\n }\n uid = obj.messageOwner.to_id.user_id;\n }\n\n TLRPC.TL_dialog dialog = dialogs_dict.get(uid);\n if (dialog != null) {\n if (dialog.top_message == msgId) {\n dialog.top_message = newMsgId;\n }\n }\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n }\n } else {\n NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded);\n NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad);\n }\n }\n\n public void cleanUp() {\n ContactsController.getInstance().cleanup();\n MediaController.getInstance().cleanup();\n NotificationsController.getInstance().cleanup();\n SendMessagesHelper.getInstance().cleanUp();\n SecretChatHelper.getInstance().cleanUp();\n\n dialogs_dict.clear();\n dialogs.clear();\n dialogsServerOnly.clear();\n users.clear();\n usersByUsernames.clear();\n chats.clear();\n dialogMessage.clear();\n printingUsers.clear();\n printingStrings.clear();\n onlinePrivacy.clear();\n totalDialogsCount = 0;\n lastPrintingStringCount = 0;\n updatesQueueSeq.clear();\n updatesQueuePts.clear();\n updatesQueueQts.clear();\n blockedUsers.clear();\n sendingTypings.clear();\n loadingFullUsers.clear();\n loadedFullUsers.clear();\n reloadingMessages.clear();\n loadingFullChats.clear();\n loadedFullChats.clear();\n\n updatesStartWaitTimeSeq = 0;\n updatesStartWaitTimePts = 0;\n updatesStartWaitTimeQts = 0;\n currentDeletingTaskTime = 0;\n currentDeletingTaskMids = null;\n gettingNewDeleteTask = false;\n loadingDialogs = false;\n dialogsEndReached = false;\n gettingDifference = false;\n gettingDifferenceAgain = false;\n loadingBlockedUsers = false;\n firstGettingTask = false;\n updatingState = false;\n lastStatusUpdateTime = 0;\n offlineSent = false;\n registeringForPush = false;\n uploadingAvatar = null;\n statusRequest = 0;\n statusSettingState = 0;\n\n if (currentDeleteTaskRunnable != null) {\n Utilities.stageQueue.cancelRunnable(currentDeleteTaskRunnable);\n currentDeleteTaskRunnable = null;\n }\n\n addSupportUser();\n }\n\n public TLRPC.User getUser(Integer id) {\n return users.get(id);\n }\n\n public TLRPC.User getUser(String username) {\n return usersByUsernames.get(username);\n }\n\n public ConcurrentHashMap<Integer, TLRPC.User> getUsers() {\n return users;\n }\n\n public TLRPC.Chat getChat(Integer id) {\n return chats.get(id);\n }\n\n public TLRPC.EncryptedChat getEncryptedChat(Integer id) {\n return encryptedChats.get(id);\n }\n\n public TLRPC.EncryptedChat getEncryptedChatDB(int chat_id) {\n TLRPC.EncryptedChat chat = encryptedChats.get(chat_id);\n if (chat == null) {\n Semaphore semaphore = new Semaphore(0);\n ArrayList<TLObject> result = new ArrayList<>();\n MessagesStorage.getInstance().getEncryptedChat(chat_id, semaphore, result);\n try {\n semaphore.acquire();\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n if (result.size() == 2) {\n chat = (TLRPC.EncryptedChat)result.get(0);\n TLRPC.User user = (TLRPC.User)result.get(1);\n putEncryptedChat(chat, false);\n putUser(user, true);\n }\n }\n return chat;\n }\n\n public boolean putUser(TLRPC.User user, boolean fromCache) {\n if (user == null) {\n return false;\n }\n fromCache = fromCache && user.id / 1000 != 333 && user.id != 777000;\n TLRPC.User oldUser = users.get(user.id);\n if (oldUser != null && oldUser.username != null && oldUser.username.length() > 0) {\n usersByUsernames.remove(oldUser.username);\n }\n if (user.username != null && user.username.length() > 0) {\n usersByUsernames.put(user.username, user);\n }\n if (!fromCache) {\n users.put(user.id, user);\n if (user.id == UserConfig.getClientUserId()) {\n UserConfig.setCurrentUser(user);\n UserConfig.saveConfig(true);\n }\n if (oldUser != null && user.status != null && oldUser.status != null && user.status.expires != oldUser.status.expires) {\n return true;\n }\n } else if (oldUser == null) {\n users.put(user.id, user);\n }\n return false;\n }\n\n public void putUsers(ArrayList<TLRPC.User> users, boolean fromCache) {\n if (users == null || users.isEmpty()) {\n return;\n }\n boolean updateStatus = false;\n for (TLRPC.User user : users) {\n if (putUser(user, fromCache)) {\n updateStatus = true;\n }\n }\n if (updateStatus) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_STATUS);\n }\n });\n }\n }\n\n public void putChat(TLRPC.Chat chat, boolean fromCache) {\n if (chat == null) {\n return;\n }\n if (fromCache) {\n chats.putIfAbsent(chat.id, chat);\n } else {\n chats.put(chat.id, chat);\n }\n }\n\n public void putChats(ArrayList<TLRPC.Chat> chats, boolean fromCache) {\n if (chats == null || chats.isEmpty()) {\n return;\n }\n for (TLRPC.Chat chat : chats) {\n putChat(chat, fromCache);\n }\n }\n\n public void putEncryptedChat(TLRPC.EncryptedChat encryptedChat, boolean fromCache) {\n if (encryptedChat == null) {\n return;\n }\n if (fromCache) {\n encryptedChats.putIfAbsent(encryptedChat.id, encryptedChat);\n } else {\n encryptedChats.put(encryptedChat.id, encryptedChat);\n }\n }\n\n public void putEncryptedChats(ArrayList<TLRPC.EncryptedChat> encryptedChats, boolean fromCache) {\n if (encryptedChats == null || encryptedChats.isEmpty()) {\n return;\n }\n for (TLRPC.EncryptedChat encryptedChat : encryptedChats) {\n putEncryptedChat(encryptedChat, fromCache);\n }\n }\n\n public void cancelLoadFullUser(int uid) {\n loadingFullUsers.remove((Integer) uid);\n }\n\n public void cancelLoadFullChat(int cid) {\n loadingFullChats.remove((Integer) cid);\n }\n\n protected void clearFullUsers() {\n loadedFullUsers.clear();\n loadedFullChats.clear();\n }\n\n public void loadFullChat(final int chat_id, final int classGuid) {\n if (loadingFullChats.contains(chat_id) || loadedFullChats.contains(chat_id)) {\n return;\n }\n loadingFullChats.add(chat_id);\n TLRPC.TL_messages_getFullChat req = new TLRPC.TL_messages_getFullChat();\n req.chat_id = chat_id;\n long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n final TLRPC.TL_messages_chatFull res = (TLRPC.TL_messages_chatFull) response;\n MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);\n MessagesStorage.getInstance().updateChatInfo(chat_id, res.full_chat.participants, false);\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n loadingFullChats.remove((Integer)chat_id);\n loadedFullChats.add(chat_id);\n\n putUsers(res.users, false);\n putChats(res.chats, false);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, chat_id, res.full_chat.participants);\n }\n });\n } else {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n loadingFullChats.remove((Integer) chat_id);\n }\n });\n }\n }\n });\n if (classGuid != 0) {\n ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);\n }\n }\n\n public void loadFullUser(final TLRPC.User user, final int classGuid) {\n if (user == null || loadingFullUsers.contains(user.id) || loadedFullUsers.contains(user.id)) {\n return;\n }\n loadingFullUsers.add(user.id);\n TLRPC.TL_users_getFullUser req = new TLRPC.TL_users_getFullUser();\n req.id = getInputUser(user);\n long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(final TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n loadingFullUsers.remove((Integer)user.id);\n loadedFullUsers.add(user.id);\n String names = user.first_name + user.last_name + user.username;\n TLRPC.TL_userFull userFull = (TLRPC.TL_userFull)response;\n ArrayList<TLRPC.User> users = new ArrayList<>();\n users.add(userFull.user);\n putUsers(users, false);\n MessagesStorage.getInstance().putUsersAndChats(users, null, false, true);\n if (!names.equals(userFull.user.first_name + userFull.user.last_name + userFull.user.username)) {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_NAME);\n }\n }\n });\n } else {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n loadingFullUsers.remove((Integer)user.id);\n }\n });\n }\n }\n });\n ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);\n }\n\n private void reloadMessages(final ArrayList<Integer> mids, final long dialog_id) {\n final TLRPC.TL_messages_getMessages req = new TLRPC.TL_messages_getMessages();\n for (Integer mid : mids) {\n if (reloadingMessages.contains(mid)) {\n continue;\n }\n req.id.add(mid);\n }\n if (req.id.isEmpty()) {\n return;\n }\n reloadingMessages.addAll(req.id);\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n TLRPC.messages_Messages messagesRes = (TLRPC.messages_Messages) response;\n ImageLoader.saveMessagesThumbs(messagesRes.messages);\n MessagesStorage.getInstance().putMessages(messagesRes, dialog_id);\n\n final ArrayList<MessageObject> objects = new ArrayList<>();\n ArrayList<Integer> messagesToReload = null;\n for (TLRPC.Message message : messagesRes.messages) {\n message.dialog_id = dialog_id;\n final HashMap<Integer, TLRPC.User> usersLocal = new HashMap<>();\n for (TLRPC.User u : messagesRes.users) {\n usersLocal.put(u.id, u);\n }\n objects.add(new MessageObject(message, usersLocal, true));\n }\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.replaceMessagesObjects, dialog_id, objects);\n }\n });\n }\n reloadingMessages.removeAll(req.id);\n }\n });\n }\n\n protected void processNewDifferenceParams(int seq, int pts, int date, int pts_count) {\n FileLog.e(\"tmessages\", \"processNewDifferenceParams seq = \" + seq + \" pts = \" + pts + \" date = \" + date + \" pts_count = \" + pts_count);\n if (pts != -1) {\n if (MessagesStorage.lastPtsValue + pts_count == pts) {\n FileLog.e(\"tmessages\", \"APPLY PTS\");\n MessagesStorage.lastPtsValue = pts;\n MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);\n } else if (MessagesStorage.lastPtsValue != pts) {\n if (gettingDifference || updatesStartWaitTimePts == 0 || updatesStartWaitTimePts != 0 && updatesStartWaitTimePts + 1500 > System.currentTimeMillis()) {\n FileLog.e(\"tmessages\", \"ADD UPDATE TO QUEUE pts = \" + pts + \" pts_count = \" + pts_count);\n if (updatesStartWaitTimePts == 0) {\n updatesStartWaitTimePts = System.currentTimeMillis();\n }\n UserActionUpdatesPts updates = new UserActionUpdatesPts();\n updates.pts = pts;\n updates.pts_count = pts_count;\n updatesQueuePts.add(updates);\n } else {\n getDifference();\n }\n }\n }\n if (seq != -1) {\n if (MessagesStorage.lastSeqValue + 1 == seq) {\n FileLog.e(\"tmessages\", \"APPLY SEQ\");\n MessagesStorage.lastSeqValue = seq;\n if (date != -1) {\n MessagesStorage.lastDateValue = date;\n }\n MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);\n } else if (MessagesStorage.lastSeqValue != seq) {\n if (gettingDifference || updatesStartWaitTimeSeq == 0 || updatesStartWaitTimeSeq != 0 && updatesStartWaitTimeSeq + 1500 > System.currentTimeMillis()) {\n FileLog.e(\"tmessages\", \"ADD UPDATE TO QUEUE seq = \" + seq);\n if (updatesStartWaitTimeSeq == 0) {\n updatesStartWaitTimeSeq = System.currentTimeMillis();\n }\n UserActionUpdatesSeq updates = new UserActionUpdatesSeq();\n updates.seq = seq;\n updatesQueueSeq.add(updates);\n } else {\n getDifference();\n }\n }\n }\n }\n\n public void didAddedNewTask(final int minDate, final SparseArray<ArrayList<Integer>> mids) {\n Utilities.stageQueue.postRunnable(new Runnable() {\n @Override\n public void run() {\n if (currentDeletingTaskMids == null && !gettingNewDeleteTask || currentDeletingTaskTime != 0 && minDate < currentDeletingTaskTime) {\n getNewDeleteTask(null);\n }\n }\n });\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.didCreatedNewDeleteTask, mids);\n }\n });\n }\n\n public void getNewDeleteTask(final ArrayList<Integer> oldTask) {\n Utilities.stageQueue.postRunnable(new Runnable() {\n @Override\n public void run() {\n gettingNewDeleteTask = true;\n MessagesStorage.getInstance().getNewTask(oldTask);\n }\n });\n }\n\n private boolean checkDeletingTask(boolean runnable) {\n int currentServerTime = ConnectionsManager.getInstance().getCurrentTime();\n\n if (currentDeletingTaskMids != null && (runnable || currentDeletingTaskTime != 0 && currentDeletingTaskTime <= currentServerTime)) {\n currentDeletingTaskTime = 0;\n if (currentDeleteTaskRunnable != null && !runnable) {\n Utilities.stageQueue.cancelRunnable(currentDeleteTaskRunnable);\n }\n currentDeleteTaskRunnable = null;\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n deleteMessages(currentDeletingTaskMids, null, null);\n\n Utilities.stageQueue.postRunnable(new Runnable() {\n @Override\n public void run() {\n getNewDeleteTask(currentDeletingTaskMids);\n currentDeletingTaskTime = 0;\n currentDeletingTaskMids = null;\n }\n });\n }\n });\n return true;\n }\n return false;\n }\n\n public void processLoadedDeleteTask(final int taskTime, final ArrayList<Integer> messages) {\n Utilities.stageQueue.postRunnable(new Runnable() {\n @Override\n public void run() {\n gettingNewDeleteTask = false;\n if (messages != null) {\n currentDeletingTaskTime = taskTime;\n currentDeletingTaskMids = messages;\n\n if (currentDeleteTaskRunnable != null) {\n Utilities.stageQueue.cancelRunnable(currentDeleteTaskRunnable);\n currentDeleteTaskRunnable = null;\n }\n\n if (!checkDeletingTask(false)) {\n currentDeleteTaskRunnable = new Runnable() {\n @Override\n public void run() {\n checkDeletingTask(true);\n }\n };\n int currentServerTime = ConnectionsManager.getInstance().getCurrentTime();\n Utilities.stageQueue.postRunnable(currentDeleteTaskRunnable, (long)Math.abs(currentServerTime - currentDeletingTaskTime) * 1000);\n }\n } else {\n currentDeletingTaskTime = 0;\n currentDeletingTaskMids = null;\n }\n }\n });\n }\n\n public void loadUserPhotos(final int uid, final int offset, final int count, final long max_id, final boolean fromCache, final int classGuid) {\n if (fromCache) {\n MessagesStorage.getInstance().getUserPhotos(uid, offset, count, max_id, classGuid);\n } else {\n TLRPC.User user = getUser(uid);\n if (user == null) {\n return;\n }\n TLRPC.TL_photos_getUserPhotos req = new TLRPC.TL_photos_getUserPhotos();\n req.limit = count;\n req.offset = offset;\n req.max_id = (int)max_id;\n req.user_id = getInputUser(user);\n long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n TLRPC.photos_Photos res = (TLRPC.photos_Photos) response;\n processLoadedUserPhotos(res, uid, offset, count, max_id, fromCache, classGuid);\n }\n }\n });\n ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);\n }\n }\n\n public void blockUser(int user_id) {\n final TLRPC.User user = getUser(user_id);\n if (user == null || MessagesController.getInstance().blockedUsers.contains(user_id)) {\n return;\n }\n blockedUsers.add(user_id);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded);\n TLRPC.TL_contacts_block req = new TLRPC.TL_contacts_block();\n req.id = MessagesController.getInputUser(user);\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n ArrayList<Integer> ids = new ArrayList<>();\n ids.add(user.id);\n MessagesStorage.getInstance().putBlockedUsers(ids, false);\n }\n }\n });\n }\n\n public void unblockUser(int user_id) {\n TLRPC.TL_contacts_unblock req = new TLRPC.TL_contacts_unblock();\n final TLRPC.User user = MessagesController.getInstance().getUser(user_id);\n if (user == null) {\n return;\n }\n blockedUsers.remove((Integer) user.id);\n req.id = MessagesController.getInputUser(user);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded);\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n MessagesStorage.getInstance().deleteBlockedUser(user.id);\n }\n });\n }\n\n public void getBlockedUsers(boolean cache) {\n if (!UserConfig.isClientActivated() || loadingBlockedUsers) {\n return;\n }\n loadingBlockedUsers = true;\n if (cache) {\n MessagesStorage.getInstance().getBlockedUsers();\n } else {\n TLRPC.TL_contacts_getBlocked req = new TLRPC.TL_contacts_getBlocked();\n req.offset = 0;\n req.limit = 200;\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n ArrayList<Integer> blocked = new ArrayList<>();\n ArrayList<TLRPC.User> users = null;\n if (error == null) {\n final TLRPC.contacts_Blocked res = (TLRPC.contacts_Blocked)response;\n for (TLRPC.TL_contactBlocked contactBlocked : res.blocked) {\n blocked.add(contactBlocked.user_id);\n }\n users = res.users;\n MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true);\n MessagesStorage.getInstance().putBlockedUsers(blocked, true);\n }\n processLoadedBlockedUsers(blocked, users, false);\n }\n });\n }\n }\n\n public void processLoadedBlockedUsers(final ArrayList<Integer> ids, final ArrayList<TLRPC.User> users, final boolean cache) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n if (users != null) {\n MessagesController.getInstance().putUsers(users, cache);\n }\n loadingBlockedUsers = false;\n if (ids.isEmpty() && cache && !UserConfig.blockedUsersLoaded) {\n getBlockedUsers(false);\n return;\n } else if (!cache) {\n UserConfig.blockedUsersLoaded = true;\n UserConfig.saveConfig(false);\n }\n blockedUsers = ids;\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded);\n }\n });\n }\n\n public void deleteUserPhoto(TLRPC.InputPhoto photo) {\n if (photo == null) {\n TLRPC.TL_photos_updateProfilePhoto req = new TLRPC.TL_photos_updateProfilePhoto();\n req.id = new TLRPC.TL_inputPhotoEmpty();\n req.crop = new TLRPC.TL_inputPhotoCropAuto();\n UserConfig.getCurrentUser().photo = new TLRPC.TL_userProfilePhotoEmpty();\n TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());\n if (user == null) {\n user = UserConfig.getCurrentUser();\n }\n if (user == null) {\n return;\n }\n if (user != null) {\n user.photo = UserConfig.getCurrentUser().photo;\n }\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL);\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());\n if (user == null) {\n user = UserConfig.getCurrentUser();\n MessagesController.getInstance().putUser(user, false);\n } else {\n UserConfig.setCurrentUser(user);\n }\n if (user == null) {\n return;\n }\n MessagesStorage.getInstance().clearUserPhotos(user.id);\n ArrayList<TLRPC.User> users = new ArrayList<>();\n users.add(user);\n MessagesStorage.getInstance().putUsersAndChats(users, null, false, true);\n user.photo = (TLRPC.UserProfilePhoto) response;\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL);\n UserConfig.saveConfig(true);\n }\n });\n }\n }\n });\n } else {\n TLRPC.TL_photos_deletePhotos req = new TLRPC.TL_photos_deletePhotos();\n req.id.add(photo);\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n\n }\n });\n }\n }\n\n public void processLoadedUserPhotos(final TLRPC.photos_Photos res, final int uid, final int offset, final int count, final long max_id, final boolean fromCache, final int classGuid) {\n if (!fromCache) {\n MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true);\n MessagesStorage.getInstance().putUserPhotos(uid, res);\n } else if (res == null || res.photos.isEmpty()) {\n loadUserPhotos(uid, offset, count, max_id, false, classGuid);\n return;\n }\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(res.users, fromCache);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.userPhotosLoaded, uid, offset, count, fromCache, classGuid, res.photos);\n }\n });\n }\n\n public void uploadAndApplyUserAvatar(TLRPC.PhotoSize bigPhoto) {\n if (bigPhoto != null) {\n uploadingAvatar = FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE) + \"/\" + bigPhoto.location.volume_id + \"_\" + bigPhoto.location.local_id + \".jpg\";\n FileLoader.getInstance().uploadFile(uploadingAvatar, false, true);\n }\n }\n\n public void deleteMessages(ArrayList<Integer> messages, ArrayList<Long> randoms, TLRPC.EncryptedChat encryptedChat) {\n if (messages == null) {\n return;\n }\n for (Integer id : messages) {\n MessageObject obj = dialogMessage.get(id);\n if (obj != null) {\n obj.deleted = true;\n }\n }\n MessagesStorage.getInstance().markMessagesAsDeleted(messages, true);\n MessagesStorage.getInstance().updateDialogsWithDeletedMessages(messages, true);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesDeleted, messages);\n\n if (randoms != null && encryptedChat != null && !randoms.isEmpty()) {\n SecretChatHelper.getInstance().sendMessagesDeleteMessage(encryptedChat, randoms, null);\n }\n\n ArrayList<Integer> toSend = new ArrayList<>();\n for (Integer mid : messages) {\n if (mid > 0) {\n toSend.add(mid);\n }\n }\n if (toSend.isEmpty()) {\n return;\n }\n TLRPC.TL_messages_deleteMessages req = new TLRPC.TL_messages_deleteMessages();\n req.id = messages;\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n TLRPC.TL_messages_affectedMessages res = (TLRPC.TL_messages_affectedMessages) response;\n processNewDifferenceParams(-1, res.pts, -1, res.pts_count);\n }\n }\n });\n }\n\n public void deleteDialog(final long did, int offset, final boolean onlyHistory) {\n int lower_part = (int)did;\n int high_id = (int)(did >> 32);\n\n if (offset == 0) {\n TLRPC.TL_dialog dialog = dialogs_dict.get(did);\n if (dialog != null) {\n if (!onlyHistory) {\n dialogs.remove(dialog);\n dialogsServerOnly.remove(dialog);\n dialogs_dict.remove(did);\n totalDialogsCount--;\n } else {\n dialog.unread_count = 0;\n }\n dialogMessage.remove(dialog.top_message);\n dialog.top_message = 0;\n }\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);\n MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {\n @Override\n public void run() {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationsController.getInstance().processReadMessages(null, did, 0, Integer.MAX_VALUE, false);\n HashMap<Long, Integer> dialogsToUpdate = new HashMap<>();\n dialogsToUpdate.put(did, 0);\n NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);\n }\n });\n }\n });\n\n MessagesStorage.getInstance().deleteDialog(did, onlyHistory);\n }\n\n if (high_id == 1) {\n return;\n }\n\n if (lower_part != 0) {\n TLRPC.TL_messages_deleteHistory req = new TLRPC.TL_messages_deleteHistory();\n req.offset = offset;\n if (did < 0) {\n req.peer = new TLRPC.TL_inputPeerChat();\n req.peer.chat_id = -lower_part;\n } else {\n TLRPC.User user = getUser(lower_part);\n if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) {\n req.peer = new TLRPC.TL_inputPeerForeign();\n req.peer.access_hash = user.access_hash;\n } else {\n req.peer = new TLRPC.TL_inputPeerContact();\n }\n req.peer.user_id = lower_part;\n }\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n TLRPC.TL_messages_affectedHistory res = (TLRPC.TL_messages_affectedHistory) response;\n if (res.offset > 0) {\n deleteDialog(did, res.offset, onlyHistory);\n }\n processNewDifferenceParams(-1, res.pts, -1, res.pts_count);\n }\n }\n });\n } else {\n if (onlyHistory) {\n SecretChatHelper.getInstance().sendClearHistoryMessage(getEncryptedChat(high_id), null);\n } else {\n SecretChatHelper.getInstance().declineSecretChat(high_id);\n }\n }\n }\n\n public void loadChatInfo(final int chat_id, Semaphore semaphore) {\n MessagesStorage.getInstance().loadChatInfo(chat_id, semaphore);\n }\n\n public void processChatInfo(final int chat_id, final TLRPC.ChatParticipants info, final ArrayList<TLRPC.User> usersArr, final boolean fromCache) {\n if (fromCache && chat_id > 0) {\n loadFullChat(chat_id, 0);\n }\n if (info != null) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(usersArr, fromCache);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, chat_id, info);\n }\n });\n }\n }\n\n public void updateTimerProc() {\n long currentTime = System.currentTimeMillis();\n\n checkDeletingTask(false);\n\n if (UserConfig.isClientActivated()) {\n if (ConnectionsManager.getInstance().getPauseTime() == 0 && ApplicationLoader.isScreenOn && !ApplicationLoader.mainInterfacePaused) {\n if (statusSettingState != 1 && (lastStatusUpdateTime == 0 || lastStatusUpdateTime <= System.currentTimeMillis() - 55000 || offlineSent)) {\n statusSettingState = 1;\n\n if (statusRequest != 0) {\n ConnectionsManager.getInstance().cancelRpc(statusRequest, true);\n }\n\n TLRPC.TL_account_updateStatus req = new TLRPC.TL_account_updateStatus();\n req.offline = false;\n statusRequest = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n lastStatusUpdateTime = System.currentTimeMillis();\n offlineSent = false;\n statusSettingState = 0;\n } else {\n if (lastStatusUpdateTime != 0) {\n lastStatusUpdateTime += 5000;\n }\n }\n statusRequest = 0;\n }\n });\n }\n } else if (statusSettingState != 2 && !offlineSent && ConnectionsManager.getInstance().getPauseTime() <= System.currentTimeMillis() - 2000) {\n statusSettingState = 2;\n if (statusRequest != 0) {\n ConnectionsManager.getInstance().cancelRpc(statusRequest, true);\n }\n TLRPC.TL_account_updateStatus req = new TLRPC.TL_account_updateStatus();\n req.offline = true;\n statusRequest = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n offlineSent = true;\n } else {\n if (lastStatusUpdateTime != 0) {\n lastStatusUpdateTime += 5000;\n }\n }\n statusRequest = 0;\n }\n });\n }\n\n for (int a = 0; a < 3; a++) {\n if (getUpdatesStartTime(a) != 0 && getUpdatesStartTime(a) + 1500 < currentTime) {\n FileLog.e(\"tmessages\", a + \" QUEUE UPDATES WAIT TIMEOUT - CHECK QUEUE\");\n processUpdatesQueue(a, 0);\n }\n }\n }\n if (!onlinePrivacy.isEmpty()) {\n ArrayList<Integer> toRemove = null;\n int currentServerTime = ConnectionsManager.getInstance().getCurrentTime();\n for (ConcurrentHashMap.Entry<Integer, Integer> entry : onlinePrivacy.entrySet()) {\n if (entry.getValue() < currentServerTime - 30) {\n if (toRemove == null) {\n toRemove = new ArrayList<>();\n }\n toRemove.add(entry.getKey());\n }\n }\n if (toRemove != null) {\n for (Integer uid : toRemove) {\n onlinePrivacy.remove(uid);\n }\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_STATUS);\n }\n });\n }\n }\n if (!printingUsers.isEmpty() || lastPrintingStringCount != printingUsers.size()) {\n boolean updated = false;\n ArrayList<Long> keys = new ArrayList<>(printingUsers.keySet());\n for (int b = 0; b < keys.size(); b++) {\n Long key = keys.get(b);\n ArrayList<PrintingUser> arr = printingUsers.get(key);\n for (int a = 0; a < arr.size(); a++) {\n PrintingUser user = arr.get(a);\n if (user.lastTime + 5900 < currentTime) {\n updated = true;\n arr.remove(user);\n a--;\n }\n }\n if (arr.isEmpty()) {\n printingUsers.remove(key);\n keys.remove(b);\n b--;\n }\n }\n\n updatePrintingStrings();\n\n if (updated) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT);\n }\n });\n }\n }\n }\n\n public void updatePrintingStrings() {\n final HashMap<Long, CharSequence> newPrintingStrings = new HashMap<>();\n\n ArrayList<Long> keys = new ArrayList<>(printingUsers.keySet());\n for (Long key : keys) {\n if (key > 0 || key.intValue() == 0) {\n newPrintingStrings.put(key, LocaleController.getString(\"Typing\", R.string.Typing));\n } else {\n ArrayList<PrintingUser> arr = printingUsers.get(key);\n int count = 0;\n String label = \"\";\n for (PrintingUser pu : arr) {\n TLRPC.User user = getUser(pu.userId);\n if (user != null) {\n if (label.length() != 0) {\n label += \", \";\n }\n label += ContactsController.formatName(user.first_name, user.last_name);\n count++;\n }\n if (count == 2) {\n break;\n }\n }\n if (label.length() != 0) {\n if (count > 1) {\n if (arr.size() > 2) {\n newPrintingStrings.put(key, Html.fromHtml(String.format(\"%s %s\", label, LocaleController.formatPluralString(\"AndMoreTyping\", arr.size() - 2))));\n } else {\n newPrintingStrings.put(key, Html.fromHtml(String.format(\"%s %s\", label, LocaleController.getString(\"AreTyping\", R.string.AreTyping))));\n }\n } else {\n newPrintingStrings.put(key, Html.fromHtml(String.format(\"%s %s\", label, LocaleController.getString(\"IsTyping\", R.string.IsTyping))));\n }\n }\n }\n }\n\n lastPrintingStringCount = newPrintingStrings.size();\n\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n printingStrings = newPrintingStrings;\n }\n });\n }\n\n public void cancelTyping(long dialog_id) {\n sendingTypings.remove(dialog_id);\n }\n\n public void sendTyping(final long dialog_id, int classGuid) {\n if (dialog_id == 0) {\n return;\n }\n if (sendingTypings.get(dialog_id) != null) {\n return;\n }\n int lower_part = (int)dialog_id;\n int high_id = (int)(dialog_id >> 32);\n if (lower_part != 0) {\n if (high_id == 1) {\n return;\n }\n\n TLRPC.TL_messages_setTyping req = new TLRPC.TL_messages_setTyping();\n if (lower_part < 0) {\n req.peer = new TLRPC.TL_inputPeerChat();\n req.peer.chat_id = -lower_part;\n } else {\n TLRPC.User user = getUser(lower_part);\n if (user != null) {\n if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) {\n req.peer = new TLRPC.TL_inputPeerForeign();\n req.peer.user_id = user.id;\n req.peer.access_hash = user.access_hash;\n } else {\n req.peer = new TLRPC.TL_inputPeerContact();\n req.peer.user_id = user.id;\n }\n } else {\n return;\n }\n }\n req.action = new TLRPC.TL_sendMessageTypingAction();\n sendingTypings.put(dialog_id, true);\n long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n sendingTypings.remove(dialog_id);\n }\n });\n }\n }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);\n ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);\n } else {\n TLRPC.EncryptedChat chat = getEncryptedChat(high_id);\n if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) {\n TLRPC.TL_messages_setEncryptedTyping req = new TLRPC.TL_messages_setEncryptedTyping();\n req.peer = new TLRPC.TL_inputEncryptedChat();\n req.peer.chat_id = chat.id;\n req.peer.access_hash = chat.access_hash;\n req.typing = true;\n sendingTypings.put(dialog_id, true);\n long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n sendingTypings.remove(dialog_id);\n }\n }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);\n ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);\n }\n }\n }\n\n public void loadMessages(final long dialog_id, final int count, final int max_id, boolean fromCache, int midDate, final int classGuid, final int load_type, final int last_message_id, final int first_message_id, final boolean allowCache) {\n int lower_part = (int)dialog_id;\n if (fromCache || lower_part == 0) {\n MessagesStorage.getInstance().getMessages(dialog_id, count, max_id, midDate, classGuid, load_type);\n } else {\n TLRPC.TL_messages_getHistory req = new TLRPC.TL_messages_getHistory();\n if (lower_part < 0) {\n req.peer = new TLRPC.TL_inputPeerChat();\n req.peer.chat_id = -lower_part;\n } else {\n TLRPC.User user = getUser(lower_part);\n if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) {\n req.peer = new TLRPC.TL_inputPeerForeign();\n req.peer.user_id = user.id;\n req.peer.access_hash = user.access_hash;\n } else {\n req.peer = new TLRPC.TL_inputPeerContact();\n req.peer.user_id = user.id;\n }\n }\n if (load_type == 3) {\n req.offset = -count / 2;\n } else if (load_type == 1) {\n req.offset = -count - 1;\n } else {\n req.offset = 0;\n }\n req.limit = count;\n req.max_id = max_id;\n long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;\n processLoadedMessages(res, dialog_id, count, max_id, false, classGuid, 0, last_message_id, first_message_id, 0, 0, load_type, allowCache);\n }\n }\n });\n ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);\n }\n }\n\n public void processLoadedMessages(final TLRPC.messages_Messages messagesRes, final long dialog_id, final int count, final int max_id, final boolean isCache, final int classGuid,\n final int first_unread, final int last_message_id, final int first_message_id, final int unread_count, final int last_date, final int load_type, final boolean allowCache) {\n Utilities.stageQueue.postRunnable(new Runnable() {\n @Override\n public void run() {\n int lower_id = (int) dialog_id;\n int high_id = (int) (dialog_id >> 32);\n if (!isCache) {\n ImageLoader.saveMessagesThumbs(messagesRes.messages);\n }\n if (!isCache && allowCache) {\n MessagesStorage.getInstance().putMessages(messagesRes, dialog_id);\n }\n if (high_id != 1 && lower_id != 0 && isCache && messagesRes.messages.size() == 0 && (load_type == 0 || load_type == 2 || load_type == 3)) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n loadMessages(dialog_id, count, max_id, false, 0, classGuid, load_type, last_message_id, first_message_id, allowCache);\n }\n });\n return;\n }\n final HashMap<Integer, TLRPC.User> usersLocal = new HashMap<>();\n for (TLRPC.User u : messagesRes.users) {\n usersLocal.put(u.id, u);\n }\n final ArrayList<MessageObject> objects = new ArrayList<>();\n ArrayList<Integer> messagesToReload = null;\n for (TLRPC.Message message : messagesRes.messages) {\n message.dialog_id = dialog_id;\n objects.add(new MessageObject(message, usersLocal, true));\n if (isCache && message.media instanceof TLRPC.TL_messageMediaUnsupported) {\n if (message.media.bytes.length == 0 || message.media.bytes.length == 1 && message.media.bytes[0] < TLRPC.LAYER) {\n if (messagesToReload == null) {\n messagesToReload = new ArrayList<>();\n }\n messagesToReload.add(message.id);\n }\n }\n }\n if (messagesToReload != null) {\n reloadMessages(messagesToReload, dialog_id);\n }\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(messagesRes.users, isCache);\n putChats(messagesRes.chats, isCache);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesDidLoaded, dialog_id, count, objects, isCache, first_unread, last_message_id, first_message_id, unread_count, last_date, load_type);\n }\n });\n }\n });\n }\n\n public void loadDialogs(final int offset, final int serverOffset, final int count, boolean fromCache) {\n if (loadingDialogs) {\n return;\n }\n loadingDialogs = true;\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n\n if (fromCache) {\n MessagesStorage.getInstance().getDialogs(offset, serverOffset, count);\n } else {\n TLRPC.TL_messages_getDialogs req = new TLRPC.TL_messages_getDialogs();\n req.offset = serverOffset;\n req.limit = count;\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n final TLRPC.messages_Dialogs dialogsRes = (TLRPC.messages_Dialogs) response;\n processLoadedDialogs(dialogsRes, null, offset, serverOffset, count, false, false);\n for (TLRPC.TL_dialog dialog : dialogsRes.dialogs) {\n MessagesController.getInstance().loadMessages(dialog.id,20, dialog.top_message, false, -1, 0, 3, -1, -1, false);\n }\n }\n }\n });\n }\n }\n\n private void applyDialogsNotificationsSettings(ArrayList<TLRPC.TL_dialog> dialogs) {\n SharedPreferences.Editor editor = null;\n for (TLRPC.TL_dialog dialog : dialogs) {\n if (dialog.peer != null && dialog.notify_settings instanceof TLRPC.TL_peerNotifySettings) {\n if (editor == null) {\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"Notifications\", Activity.MODE_PRIVATE);\n editor = preferences.edit();\n }\n int dialog_id = dialog.peer.user_id;\n if (dialog_id == 0) {\n dialog_id = -dialog.peer.chat_id;\n }\n if (dialog.notify_settings.mute_until != 0) {\n if (dialog.notify_settings.mute_until > ConnectionsManager.getInstance().getCurrentTime() + 60 * 60 * 24 * 365) {\n editor.putInt(\"notify2_\" + dialog_id, 2);\n dialog.notify_settings.mute_until = Integer.MAX_VALUE;\n } else {\n editor.putInt(\"notify2_\" + dialog_id, 3);\n editor.putInt(\"notifyuntil_\" + dialog_id, dialog.notify_settings.mute_until);\n }\n }\n }\n }\n if (editor != null) {\n editor.commit();\n }\n }\n\n public void processDialogsUpdateRead(final HashMap<Long, Integer> dialogsToUpdate) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n for (HashMap.Entry<Long, Integer> entry : dialogsToUpdate.entrySet()) {\n TLRPC.TL_dialog currentDialog = dialogs_dict.get(entry.getKey());\n if (currentDialog != null) {\n currentDialog.unread_count = entry.getValue();\n }\n }\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);\n }\n });\n }\n\n public void processDialogsUpdate(final TLRPC.messages_Dialogs dialogsRes, ArrayList<TLRPC.EncryptedChat> encChats) {\n Utilities.stageQueue.postRunnable(new Runnable() {\n @Override\n public void run() {\n final HashMap<Long, TLRPC.TL_dialog> new_dialogs_dict = new HashMap<>();\n final HashMap<Integer, MessageObject> new_dialogMessage = new HashMap<>();\n final HashMap<Integer, TLRPC.User> usersLocal = new HashMap<>();\n final HashMap<Long, Integer> dialogsToUpdate = new HashMap<>();\n\n for (TLRPC.User u : dialogsRes.users) {\n usersLocal.put(u.id, u);\n }\n\n for (TLRPC.Message m : dialogsRes.messages) {\n new_dialogMessage.put(m.id, new MessageObject(m, usersLocal, false));\n }\n for (TLRPC.TL_dialog d : dialogsRes.dialogs) {\n if (d.last_message_date == 0) {\n MessageObject mess = new_dialogMessage.get(d.top_message);\n if (mess != null) {\n d.last_message_date = mess.messageOwner.date;\n }\n }\n if (d.id == 0) {\n if (d.peer instanceof TLRPC.TL_peerUser) {\n d.id = d.peer.user_id;\n } else if (d.peer instanceof TLRPC.TL_peerChat) {\n d.id = -d.peer.chat_id;\n }\n }\n new_dialogs_dict.put(d.id, d);\n dialogsToUpdate.put(d.id, d.unread_count);\n }\n\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(dialogsRes.users, true);\n putChats(dialogsRes.chats, true);\n\n for (HashMap.Entry<Long, TLRPC.TL_dialog> pair : new_dialogs_dict.entrySet()) {\n long key = pair.getKey();\n TLRPC.TL_dialog value = pair.getValue();\n TLRPC.TL_dialog currentDialog = dialogs_dict.get(key);\n if (currentDialog == null) {\n dialogs_dict.put(key, value);\n dialogMessage.put(value.top_message, new_dialogMessage.get(value.top_message));\n } else {\n currentDialog.unread_count = value.unread_count;\n MessageObject oldMsg = dialogMessage.get(currentDialog.top_message);\n if (oldMsg == null || currentDialog.top_message > 0) {\n if (oldMsg != null && oldMsg.deleted || value.top_message > currentDialog.top_message) {\n dialogs_dict.put(key, value);\n if (oldMsg != null) {\n dialogMessage.remove(oldMsg.getId());\n }\n dialogMessage.put(value.top_message, new_dialogMessage.get(value.top_message));\n }\n } else {\n MessageObject newMsg = new_dialogMessage.get(value.top_message);\n if (oldMsg.deleted || newMsg == null || newMsg.messageOwner.date > oldMsg.messageOwner.date) {\n dialogs_dict.put(key, value);\n dialogMessage.remove(oldMsg.getId());\n dialogMessage.put(value.top_message, new_dialogMessage.get(value.top_message));\n }\n }\n }\n }\n\n dialogs.clear();\n dialogsServerOnly.clear();\n dialogs.addAll(dialogs_dict.values());\n Collections.sort(dialogs, new Comparator<TLRPC.TL_dialog>() {\n @Override\n public int compare(TLRPC.TL_dialog tl_dialog, TLRPC.TL_dialog tl_dialog2) {\n if (tl_dialog.unread_count > 0 && tl_dialog2.unread_count <= 0) {\n return -1;\n } else if (tl_dialog.unread_count <= 0 && tl_dialog2.unread_count > 0) {\n return 1;\n } else {\n if (tl_dialog.last_message_date == tl_dialog2.last_message_date) {\n return 0;\n } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) {\n return 1;\n } else {\n return -1;\n }\n }\n }\n });\n for (TLRPC.TL_dialog d : dialogs) {\n int high_id = (int) (d.id >> 32);\n if ((int) d.id != 0 && high_id != 1) {\n dialogsServerOnly.add(d);\n }\n }\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);\n }\n });\n }\n });\n }\n\n public void processLoadedDialogs(final TLRPC.messages_Dialogs dialogsRes, final ArrayList<TLRPC.EncryptedChat> encChats, final int offset, final int serverOffset, final int count, final boolean isCache, final boolean resetEnd) {\n Utilities.stageQueue.postRunnable(new Runnable() {\n @Override\n public void run() {\n if (isCache && dialogsRes.dialogs.size() == 0) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(dialogsRes.users, isCache);\n loadingDialogs = false;\n if (resetEnd) {\n dialogsEndReached = false;\n }\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n loadDialogs(offset, serverOffset, count, false);\n }\n });\n return;\n }\n final HashMap<Long, TLRPC.TL_dialog> new_dialogs_dict = new HashMap<>();\n final HashMap<Integer, MessageObject> new_dialogMessage = new HashMap<>();\n final HashMap<Integer, TLRPC.User> usersLocal = new HashMap<>();\n int new_totalDialogsCount;\n\n if (!isCache) {\n ImageLoader.saveMessagesThumbs(dialogsRes.messages);\n MessagesStorage.getInstance().putDialogs(dialogsRes);\n }\n\n if (dialogsRes instanceof TLRPC.TL_messages_dialogsSlice) {\n TLRPC.TL_messages_dialogsSlice slice = (TLRPC.TL_messages_dialogsSlice) dialogsRes;\n new_totalDialogsCount = slice.count;\n } else {\n new_totalDialogsCount = dialogsRes.dialogs.size();\n }\n\n for (TLRPC.User u : dialogsRes.users) {\n usersLocal.put(u.id, u);\n }\n\n for (TLRPC.Message m : dialogsRes.messages) {\n new_dialogMessage.put(m.id, new MessageObject(m, usersLocal, false));\n }\n for (TLRPC.TL_dialog d : dialogsRes.dialogs) {\n if (d.last_message_date == 0) {\n MessageObject mess = new_dialogMessage.get(d.top_message);\n if (mess != null) {\n d.last_message_date = mess.messageOwner.date;\n }\n }\n if (d.id == 0) {\n if (d.peer instanceof TLRPC.TL_peerUser) {\n d.id = d.peer.user_id;\n } else if (d.peer instanceof TLRPC.TL_peerChat) {\n d.id = -d.peer.chat_id;\n }\n }\n new_dialogs_dict.put(d.id, d);\n }\n\n final int arg1 = new_totalDialogsCount;\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n if (!isCache) {\n applyDialogsNotificationsSettings(dialogsRes.dialogs);\n }\n putUsers(dialogsRes.users, isCache);\n putChats(dialogsRes.chats, isCache);\n if (encChats != null) {\n for (TLRPC.EncryptedChat encryptedChat : encChats) {\n if (encryptedChat instanceof TLRPC.TL_encryptedChat && AndroidUtilities.getMyLayerVersion(encryptedChat.layer) < SecretChatHelper.CURRENT_SECRET_CHAT_LAYER) {\n SecretChatHelper.getInstance().sendNotifyLayerMessage(encryptedChat, null);\n }\n putEncryptedChat(encryptedChat, true);\n }\n }\n loadingDialogs = false;\n totalDialogsCount = arg1;\n\n for (HashMap.Entry<Long, TLRPC.TL_dialog> pair : new_dialogs_dict.entrySet()) {\n long key = pair.getKey();\n TLRPC.TL_dialog value = pair.getValue();\n TLRPC.TL_dialog currentDialog = dialogs_dict.get(key);\n if (currentDialog == null) {\n dialogs_dict.put(key, value);\n dialogMessage.put(value.top_message, new_dialogMessage.get(value.top_message));\n } else {\n MessageObject oldMsg = dialogMessage.get(value.top_message);\n if (oldMsg == null || currentDialog.top_message > 0) {\n if (oldMsg != null && oldMsg.deleted || value.top_message > currentDialog.top_message) {\n if (oldMsg != null) {\n dialogMessage.remove(oldMsg.getId());\n }\n dialogs_dict.put(key, value);\n dialogMessage.put(value.top_message, new_dialogMessage.get(value.top_message));\n }\n } else {\n MessageObject newMsg = new_dialogMessage.get(value.top_message);\n if (oldMsg.deleted || newMsg == null || newMsg.messageOwner.date > oldMsg.messageOwner.date) {\n dialogMessage.remove(oldMsg.getId());\n dialogs_dict.put(key, value);\n dialogMessage.put(value.top_message, new_dialogMessage.get(value.top_message));\n }\n }\n }\n }\n\n dialogs.clear();\n dialogsServerOnly.clear();\n dialogs.addAll(dialogs_dict.values());\n Collections.sort(dialogs, new Comparator<TLRPC.TL_dialog>() {\n @Override\n public int compare(TLRPC.TL_dialog tl_dialog, TLRPC.TL_dialog tl_dialog2) {\n if (tl_dialog.unread_count > 0 && tl_dialog2.unread_count <= 0) {\n return -1;\n } else if (tl_dialog.unread_count <= 0 && tl_dialog2.unread_count > 0) {\n return 1;\n } else {\n if (tl_dialog.last_message_date == tl_dialog2.last_message_date) {\n return 0;\n } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) {\n return 1;\n } else {\n return -1;\n }\n }\n }\n });\n for (TLRPC.TL_dialog d : dialogs) {\n int high_id = (int) (d.id >> 32);\n if ((int) d.id != 0 && high_id != 1) {\n dialogsServerOnly.add(d);\n }\n }\n\n dialogsEndReached = (dialogsRes.dialogs.size() == 0 || dialogsRes.dialogs.size() != count) && !isCache;\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n }\n });\n }\n });\n }\n\n public void markMessageAsRead(final long dialog_id, final long random_id, int ttl) {\n if (random_id == 0 || dialog_id == 0 || ttl <= 0) {\n return;\n }\n int lower_part = (int)dialog_id;\n int high_id = (int)(dialog_id >> 32);\n if (lower_part != 0) {\n return;\n }\n TLRPC.EncryptedChat chat = getEncryptedChat(high_id);\n if (chat == null) {\n return;\n }\n ArrayList<Long> random_ids = new ArrayList<>();\n random_ids.add(random_id);\n SecretChatHelper.getInstance().sendMessagesReadMessage(chat, random_ids, null);\n int time = ConnectionsManager.getInstance().getCurrentTime();\n MessagesStorage.getInstance().createTaskForSecretChat(chat.id, time, time, 0, random_ids);\n }\n\n public void markDialogAsRead(final long dialog_id, final int max_id, final int max_positive_id, final int offset, final int max_date, final boolean was, final boolean popup) {\n int lower_part = (int)dialog_id;\n int high_id = (int)(dialog_id >> 32);\n\n if (lower_part != 0) {\n if (max_positive_id == 0 && offset == 0 || high_id == 1) {\n return;\n }\n TLRPC.TL_messages_readHistory req = new TLRPC.TL_messages_readHistory();\n if (lower_part < 0) {\n req.peer = new TLRPC.TL_inputPeerChat();\n req.peer.chat_id = -lower_part;\n } else {\n TLRPC.User user = getUser(lower_part);\n if (user == null) {\n return;\n }\n if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) {\n req.peer = new TLRPC.TL_inputPeerForeign();\n req.peer.user_id = user.id;\n req.peer.access_hash = user.access_hash;\n } else {\n req.peer = new TLRPC.TL_inputPeerContact();\n req.peer.user_id = user.id;\n }\n }\n req.max_id = max_positive_id;\n req.offset = offset;\n if (offset == 0) {\n MessagesStorage.getInstance().processPendingRead(dialog_id, max_positive_id, max_date, false);\n MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {\n @Override\n public void run() {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);\n if (dialog != null) {\n dialog.unread_count = 0;\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_READ_DIALOG_MESSAGE);\n }\n if (!popup) {\n NotificationsController.getInstance().processReadMessages(null, dialog_id, 0, max_positive_id, false);\n HashMap<Long, Integer> dialogsToUpdate = new HashMap<>();\n dialogsToUpdate.put(dialog_id, 0);\n NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);\n } else {\n NotificationsController.getInstance().processReadMessages(null, dialog_id, 0, max_positive_id, true);\n HashMap<Long, Integer> dialogsToUpdate = new HashMap<>();\n dialogsToUpdate.put(dialog_id, -1);\n NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);\n }\n }\n });\n }\n });\n }\n if (req.max_id != Integer.MAX_VALUE) {\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n MessagesStorage.getInstance().processPendingRead(dialog_id, max_positive_id, max_date, true);\n TLRPC.TL_messages_affectedHistory res = (TLRPC.TL_messages_affectedHistory) response;\n if (res.offset > 0) {\n markDialogAsRead(dialog_id, 0, max_positive_id, res.offset, max_date, was, popup);\n }\n processNewDifferenceParams(-1, res.pts, -1, res.pts_count);\n }\n }\n });\n }\n } else {\n if (max_date == 0) {\n return;\n }\n TLRPC.EncryptedChat chat = getEncryptedChat(high_id);\n if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) {\n TLRPC.TL_messages_readEncryptedHistory req = new TLRPC.TL_messages_readEncryptedHistory();\n req.peer = new TLRPC.TL_inputEncryptedChat();\n req.peer.chat_id = chat.id;\n req.peer.access_hash = chat.access_hash;\n req.max_date = max_date;\n\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n //MessagesStorage.getInstance().processPendingRead(dialog_id, max_id, max_date, true);\n }\n });\n }\n MessagesStorage.getInstance().processPendingRead(dialog_id, max_id, max_date, false);\n\n MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {\n @Override\n public void run() {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationsController.getInstance().processReadMessages(null, dialog_id, max_date, 0, popup);\n TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);\n if (dialog != null) {\n dialog.unread_count = 0;\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_READ_DIALOG_MESSAGE);\n }\n HashMap<Long, Integer> dialogsToUpdate = new HashMap<>();\n dialogsToUpdate.put(dialog_id, 0);\n NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);\n }\n });\n }\n });\n\n if (chat.ttl > 0 && was) {\n int serverTime = Math.max(ConnectionsManager.getInstance().getCurrentTime(), max_date);\n MessagesStorage.getInstance().createTaskForSecretChat(chat.id, serverTime, serverTime, 0, null);\n }\n }\n }\n\n public long createChat(String title, ArrayList<Integer> selectedContacts, final TLRPC.InputFile uploadedAvatar, boolean isBroadcast) {\n if (isBroadcast) {\n TLRPC.TL_chat chat = new TLRPC.TL_chat();\n chat.id = UserConfig.lastBroadcastId;\n chat.title = title;\n chat.photo = new TLRPC.TL_chatPhotoEmpty();\n chat.participants_count = selectedContacts.size();\n chat.date = (int)(System.currentTimeMillis() / 1000);\n chat.left = false;\n chat.version = 1;\n UserConfig.lastBroadcastId--;\n putChat(chat, false);\n ArrayList<TLRPC.Chat> chatsArrays = new ArrayList<>();\n chatsArrays.add(chat);\n MessagesStorage.getInstance().putUsersAndChats(null, chatsArrays, true, true);\n\n TLRPC.TL_chatParticipants participants = new TLRPC.TL_chatParticipants();\n participants.chat_id = chat.id;\n participants.admin_id = UserConfig.getClientUserId();\n participants.version = 1;\n for (Integer id : selectedContacts) {\n TLRPC.TL_chatParticipant participant = new TLRPC.TL_chatParticipant();\n participant.user_id = id;\n participant.inviter_id = UserConfig.getClientUserId();\n participant.date = (int)(System.currentTimeMillis() / 1000);\n participants.participants.add(participant);\n }\n MessagesStorage.getInstance().updateChatInfo(chat.id, participants, false);\n\n TLRPC.TL_messageService newMsg = new TLRPC.TL_messageService();\n newMsg.action = new TLRPC.TL_messageActionCreatedBroadcastList();\n newMsg.local_id = newMsg.id = UserConfig.getNewMessageId();\n newMsg.from_id = UserConfig.getClientUserId();\n newMsg.dialog_id = AndroidUtilities.makeBroadcastId(chat.id);\n newMsg.to_id = new TLRPC.TL_peerChat();\n newMsg.to_id.chat_id = chat.id;\n newMsg.date = ConnectionsManager.getInstance().getCurrentTime();\n newMsg.random_id = 0;\n UserConfig.saveConfig(false);\n MessageObject newMsgObj = new MessageObject(newMsg, users, true);\n newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;\n\n ArrayList<MessageObject> objArr = new ArrayList<>();\n objArr.add(newMsgObj);\n ArrayList<TLRPC.Message> arr = new ArrayList<>();\n arr.add(newMsg);\n MessagesStorage.getInstance().putMessages(arr, false, true, false, 0);\n updateInterfaceWithMessages(newMsg.dialog_id, objArr);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);\n\n return 0;\n } else {\n TLRPC.TL_messages_createChat req = new TLRPC.TL_messages_createChat();\n req.title = title;\n for (Integer uid : selectedContacts) {\n TLRPC.User user = getUser(uid);\n if (user == null) {\n continue;\n }\n req.users.add(getInputUser(user));\n }\n return ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error != null) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidFailCreate);\n }\n });\n return;\n }\n final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response;\n MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);\n\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(res.users, false);\n putChats(res.chats, false);\n final ArrayList<MessageObject> messagesObj = new ArrayList<>();\n messagesObj.add(new MessageObject(res.message, users, true));\n TLRPC.Chat chat = res.chats.get(0);\n updateInterfaceWithMessages(-chat.id, messagesObj);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);\n if (uploadedAvatar != null) {\n changeChatAvatar(chat.id, uploadedAvatar);\n }\n }\n });\n\n final ArrayList<TLRPC.Message> messages = new ArrayList<>();\n messages.add(res.message);\n MessagesStorage.getInstance().putMessages(messages, true, true, false, 0);\n\n if (res instanceof TLRPC.TL_messages_statedMessage) {\n MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.message.date, res.pts_count);\n } else if (res instanceof TLRPC.TL_messages_statedMessageLink) {\n MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date, res.pts_count);\n }\n }\n });\n }\n }\n\n public void addUserToChat(int chat_id, final TLRPC.User user, final TLRPC.ChatParticipants info, int count_fwd) {\n if (user == null) {\n return;\n }\n\n if (chat_id > 0) {\n TLRPC.TL_messages_addChatUser req = new TLRPC.TL_messages_addChatUser();\n req.chat_id = chat_id;\n req.fwd_limit = count_fwd;\n req.user_id = getInputUser(user);\n\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error != null) {\n return;\n }\n\n final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response;\n MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);\n\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(res.users, false);\n putChats(res.chats, false);\n final ArrayList<MessageObject> messagesObj = new ArrayList<>();\n messagesObj.add(new MessageObject(res.message, users, true));\n TLRPC.Chat chat = res.chats.get(0);\n updateInterfaceWithMessages(-chat.id, messagesObj);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);\n\n if (info != null) {\n for (TLRPC.TL_chatParticipant p : info.participants) {\n if (p.user_id == user.id) {\n return;\n }\n }\n TLRPC.TL_chatParticipant newPart = new TLRPC.TL_chatParticipant();\n newPart.user_id = user.id;\n newPart.inviter_id = UserConfig.getClientUserId();\n newPart.date = ConnectionsManager.getInstance().getCurrentTime();\n info.participants.add(0, newPart);\n MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info);\n }\n }\n });\n\n final ArrayList<TLRPC.Message> messages = new ArrayList<>();\n messages.add(res.message);\n MessagesStorage.getInstance().putMessages(messages, true, true, false, 0);\n\n if (res instanceof TLRPC.TL_messages_statedMessage) {\n MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.message.date, res.pts_count);\n } else if (res instanceof TLRPC.TL_messages_statedMessageLink) {\n MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date, res.pts_count);\n }\n }\n });\n } else {\n if (info != null) {\n for (TLRPC.TL_chatParticipant p : info.participants) {\n if (p.user_id == user.id) {\n return;\n }\n }\n\n TLRPC.Chat chat = getChat(chat_id);\n chat.participants_count++;\n ArrayList<TLRPC.Chat> chatArrayList = new ArrayList<>();\n chatArrayList.add(chat);\n MessagesStorage.getInstance().putUsersAndChats(null, chatArrayList, true, true);\n\n TLRPC.TL_chatParticipant newPart = new TLRPC.TL_chatParticipant();\n newPart.user_id = user.id;\n newPart.inviter_id = UserConfig.getClientUserId();\n newPart.date = ConnectionsManager.getInstance().getCurrentTime();\n info.participants.add(0, newPart);\n MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);\n }\n }\n }\n\n public void deleteUserFromChat(final int chat_id, final TLRPC.User user, final TLRPC.ChatParticipants info) {\n if (user == null) {\n return;\n }\n if (chat_id > 0) {\n TLRPC.TL_messages_deleteChatUser req = new TLRPC.TL_messages_deleteChatUser();\n req.chat_id = chat_id;\n req.user_id = getInputUser(user);\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error != null) {\n return;\n }\n final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response;\n if (user.id == UserConfig.getClientUserId()) {\n res.chats = null;\n }\n MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);\n\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(res.users, false);\n putChats(res.chats, false);\n if (user.id != UserConfig.getClientUserId()) {\n final ArrayList<MessageObject> messagesObj = new ArrayList<>();\n messagesObj.add(new MessageObject(res.message, users, true));\n TLRPC.Chat chat = res.chats.get(0);\n updateInterfaceWithMessages(-chat.id, messagesObj);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);\n }\n boolean changed = false;\n if (info != null) {\n for (int a = 0; a < info.participants.size(); a++) {\n TLRPC.TL_chatParticipant p = info.participants.get(a);\n if (p.user_id == user.id) {\n info.participants.remove(a);\n changed = true;\n break;\n }\n }\n if (changed) {\n MessagesStorage.getInstance().updateChatInfo(chat_id, info, true);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info);\n } else {\n MessagesStorage.getInstance().updateChatInfo(chat_id, user.id, true, 0, 0);\n }\n } else {\n MessagesStorage.getInstance().updateChatInfo(chat_id, user.id, true, 0, 0);\n }\n }\n });\n\n if (user.id != UserConfig.getClientUserId()) {\n final ArrayList<TLRPC.Message> messages = new ArrayList<>();\n messages.add(res.message);\n MessagesStorage.getInstance().putMessages(messages, true, true, false, 0);\n }\n\n if (res instanceof TLRPC.TL_messages_statedMessage) {\n MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.message.date, res.pts_count);\n } else if (res instanceof TLRPC.TL_messages_statedMessageLink) {\n MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date, res.pts_count);\n }\n }\n });\n } else {\n if (info != null) {\n TLRPC.Chat chat = getChat(chat_id);\n chat.participants_count--;\n ArrayList<TLRPC.Chat> chatArrayList = new ArrayList<>();\n chatArrayList.add(chat);\n MessagesStorage.getInstance().putUsersAndChats(null, chatArrayList, true, true);\n\n boolean changed = false;\n if (info != null) {\n for (int a = 0; a < info.participants.size(); a++) {\n TLRPC.TL_chatParticipant p = info.participants.get(a);\n if (p.user_id == user.id) {\n info.participants.remove(a);\n changed = true;\n break;\n }\n }\n if (changed) {\n MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info);\n }\n }\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);\n }\n }\n }\n\n public void changeChatTitle(int chat_id, String title) {\n if (chat_id > 0) {\n TLRPC.TL_messages_editChatTitle req = new TLRPC.TL_messages_editChatTitle();\n req.chat_id = chat_id;\n req.title = title;\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error != null) {\n return;\n }\n final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response;\n MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);\n\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(res.users, false);\n putChats(res.chats, false);\n final ArrayList<MessageObject> messagesObj = new ArrayList<>();\n messagesObj.add(new MessageObject(res.message, users, true));\n TLRPC.Chat chat = res.chats.get(0);\n updateInterfaceWithMessages(-chat.id, messagesObj);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_NAME);\n }\n });\n\n final ArrayList<TLRPC.Message> messages = new ArrayList<>();\n messages.add(res.message);\n MessagesStorage.getInstance().putMessages(messages, true, true, false, 0);\n\n if (res instanceof TLRPC.TL_messages_statedMessage) {\n MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.message.date, res.pts_count);\n } else if (res instanceof TLRPC.TL_messages_statedMessageLink) {\n MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date, res.pts_count);\n }\n }\n });\n } else {\n TLRPC.Chat chat = getChat(chat_id);\n chat.title = title;\n ArrayList<TLRPC.Chat> chatArrayList = new ArrayList<>();\n chatArrayList.add(chat);\n MessagesStorage.getInstance().putUsersAndChats(null, chatArrayList, true, true);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_NAME);\n }\n }\n\n public void changeChatAvatar(int chat_id, TLRPC.InputFile uploadedAvatar) {\n TLRPC.TL_messages_editChatPhoto req2 = new TLRPC.TL_messages_editChatPhoto();\n req2.chat_id = chat_id;\n if (uploadedAvatar != null) {\n req2.photo = new TLRPC.TL_inputChatUploadedPhoto();\n req2.photo.file = uploadedAvatar;\n req2.photo.crop = new TLRPC.TL_inputPhotoCropAuto();\n } else {\n req2.photo = new TLRPC.TL_inputChatPhotoEmpty();\n }\n ConnectionsManager.getInstance().performRpc(req2, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error != null) {\n return;\n }\n final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response;\n MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);\n\n final ArrayList<TLRPC.Message> messages = new ArrayList<>();\n messages.add(res.message);\n ImageLoader.saveMessagesThumbs(messages);\n\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(res.users, false);\n putChats(res.chats, false);\n final ArrayList<MessageObject> messagesObj = new ArrayList<>();\n messagesObj.add(new MessageObject(res.message, users, true));\n TLRPC.Chat chat = res.chats.get(0);\n updateInterfaceWithMessages(-chat.id, messagesObj);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_AVATAR);\n }\n });\n\n MessagesStorage.getInstance().putMessages(messages, true, true, false, 0);\n\n if (res instanceof TLRPC.TL_messages_statedMessage) {\n MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.message.date, res.pts_count);\n } else if (res instanceof TLRPC.TL_messages_statedMessageLink) {\n MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date, res.pts_count);\n }\n }\n });\n }\n\n public void unregistedPush() {\n if (UserConfig.registeredForPush && UserConfig.pushString.length() == 0) {\n TLRPC.TL_account_unregisterDevice req = new TLRPC.TL_account_unregisterDevice();\n req.token = UserConfig.pushString;\n req.token_type = 2;\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n\n }\n });\n }\n }\n\n public void logOut() {\n TLRPC.TL_auth_logOut req = new TLRPC.TL_auth_logOut();\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n ConnectionsManager.getInstance().cleanUp();\n }\n });\n }\n\n public void registerForPush(final String regid) {\n if (regid == null || regid.length() == 0 || registeringForPush || UserConfig.getClientUserId() == 0) {\n return;\n }\n if (UserConfig.registeredForPush && regid.equals(UserConfig.pushString)) {\n return;\n }\n registeringForPush = true;\n TLRPC.TL_account_registerDevice req = new TLRPC.TL_account_registerDevice();\n req.token_type = 2;\n req.token = regid;\n req.app_sandbox = false;\n try {\n req.lang_code = LocaleController.getLocaleString(Locale.getDefault());\n req.device_model = Build.MANUFACTURER + Build.MODEL;\n if (req.device_model == null) {\n req.device_model = \"Android unknown\";\n }\n req.system_version = \"SDK \" + Build.VERSION.SDK_INT;\n PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0);\n req.app_version = pInfo.versionName + \" (\" + pInfo.versionCode + \")\";\n if (req.app_version == null) {\n req.app_version = \"App version unknown\";\n }\n\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n req.lang_code = \"en\";\n req.device_model = \"Android unknown\";\n req.system_version = \"SDK \" + Build.VERSION.SDK_INT;\n req.app_version = \"App version unknown\";\n }\n\n if (req.lang_code == null || req.lang_code.length() == 0) {\n req.lang_code = \"en\";\n }\n if (req.device_model == null || req.device_model.length() == 0) {\n req.device_model = \"Android unknown\";\n }\n if (req.app_version == null || req.app_version.length() == 0) {\n req.app_version = \"App version unknown\";\n }\n if (req.system_version == null || req.system_version.length() == 0) {\n req.system_version = \"SDK Unknown\";\n }\n\n if (req.app_version != null) {\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n FileLog.e(\"tmessages\", \"registered for push\");\n UserConfig.registeredForPush = true;\n UserConfig.pushString = regid;\n UserConfig.saveConfig(false);\n }\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n registeringForPush = false;\n }\n });\n }\n });\n }\n }\n\n public void loadCurrentState() {\n if (updatingState) {\n return;\n }\n updatingState = true;\n TLRPC.TL_updates_getState req = new TLRPC.TL_updates_getState();\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n updatingState = false;\n if (error == null) {\n TLRPC.TL_updates_state res = (TLRPC.TL_updates_state) response;\n MessagesStorage.lastDateValue = res.date;\n MessagesStorage.lastPtsValue = res.pts;\n MessagesStorage.lastSeqValue = res.seq;\n MessagesStorage.lastQtsValue = res.qts;\n for (int a = 0; a < 3; a++) {\n processUpdatesQueue(a, 2);\n }\n MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);\n } else {\n if (error.code != 401) {\n loadCurrentState();\n }\n }\n }\n });\n }\n\n private int getUpdateSeq(TLRPC.Updates updates) {\n if (updates instanceof TLRPC.TL_updatesCombined) {\n return updates.seq_start;\n } else {\n return updates.seq;\n }\n }\n\n private void setUpdatesStartTime(int type, long time) {\n if (type == 0) {\n updatesStartWaitTimeSeq = time;\n } else if (type == 1) {\n updatesStartWaitTimePts = time;\n } else if (type == 2) {\n updatesStartWaitTimeQts = time;\n }\n }\n\n public long getUpdatesStartTime(int type) {\n if (type == 0) {\n return updatesStartWaitTimeSeq;\n } else if (type == 1) {\n return updatesStartWaitTimePts;\n } else if (type == 2) {\n return updatesStartWaitTimeQts;\n }\n return 0;\n }\n\n private int isValidUpdate(TLRPC.Updates updates, int type) {\n if (type == 0) {\n int seq = getUpdateSeq(updates);\n if (MessagesStorage.lastSeqValue + 1 == seq || MessagesStorage.lastSeqValue == seq) {\n return 0;\n } else if (MessagesStorage.lastSeqValue < seq) {\n return 1;\n } else {\n return 2;\n }\n } else if (type == 1) {\n if (updates.pts <= MessagesStorage.lastPtsValue) {\n return 2;\n } else if (MessagesStorage.lastPtsValue + updates.pts_count == updates.pts) {\n return 0;\n } else {\n return 1;\n }\n } else if (type == 2) {\n if (updates.qts <= MessagesStorage.lastQtsValue) {\n return 2;\n } else if (MessagesStorage.lastQtsValue + 1 == updates.qts) {\n return 0;\n } else {\n return 1;\n }\n }\n return 0;\n }\n\n private boolean processUpdatesQueue(int type, int state) {\n ArrayList<TLRPC.Updates> updatesQueue = null;\n if (type == 0) {\n updatesQueue = updatesQueueSeq;\n Collections.sort(updatesQueue, new Comparator<TLRPC.Updates>() {\n @Override\n public int compare(TLRPC.Updates updates, TLRPC.Updates updates2) {\n int seq1 = getUpdateSeq(updates);\n int seq2 = getUpdateSeq(updates2);\n if (seq1 == seq2) {\n return 0;\n } else if (seq1 > seq2) {\n return 1;\n }\n return -1;\n }\n });\n } else if (type == 1) {\n updatesQueue = updatesQueuePts;\n Collections.sort(updatesQueue, new Comparator<TLRPC.Updates>() {\n @Override\n public int compare(TLRPC.Updates updates, TLRPC.Updates updates2) {\n if (updates.pts == updates2.pts) {\n return 0;\n } else if (updates.pts > updates2.pts) {\n return 1;\n }\n return -1;\n }\n });\n } else if (type == 2) {\n updatesQueue = updatesQueueQts;\n Collections.sort(updatesQueue, new Comparator<TLRPC.Updates>() {\n @Override\n public int compare(TLRPC.Updates updates, TLRPC.Updates updates2) {\n if (updates.qts == updates2.qts) {\n return 0;\n } else if (updates.qts > updates2.qts) {\n return 1;\n }\n return -1;\n }\n });\n }\n if (!updatesQueue.isEmpty()) {\n boolean anyProceed = false;\n if (state == 2) {\n TLRPC.Updates updates = updatesQueue.get(0);\n if (type == 0) {\n MessagesStorage.lastSeqValue = getUpdateSeq(updates);\n } else if (type == 1) {\n MessagesStorage.lastPtsValue = updates.pts;\n } else if (type == 2) {\n MessagesStorage.lastQtsValue = updates.qts;\n }\n }\n for (int a = 0; a < updatesQueue.size(); a++) {\n TLRPC.Updates updates = updatesQueue.get(a);\n int updateState = isValidUpdate(updates, type);\n if (updateState == 0) {\n processUpdates(updates, true);\n anyProceed = true;\n updatesQueue.remove(a);\n a--;\n } else if (updateState == 1) {\n if (getUpdatesStartTime(type) != 0 && (anyProceed || getUpdatesStartTime(type) + 1500 > System.currentTimeMillis())) {\n FileLog.e(\"tmessages\", \"HOLE IN UPDATES QUEUE - will wait more time\");\n if (anyProceed) {\n setUpdatesStartTime(type, System.currentTimeMillis());\n }\n return false;\n } else {\n FileLog.e(\"tmessages\", \"HOLE IN UPDATES QUEUE - getDifference\");\n setUpdatesStartTime(type, 0);\n updatesQueue.clear();\n getDifference();\n return false;\n }\n } else {\n updatesQueue.remove(a);\n a--;\n }\n }\n updatesQueue.clear();\n FileLog.e(\"tmessages\", \"UPDATES QUEUE PROCEED - OK\");\n }\n setUpdatesStartTime(type, 0);\n return true;\n }\n\n public void getDifference() {\n registerForPush(UserConfig.pushString);\n if (MessagesStorage.lastDateValue == 0) {\n loadCurrentState();\n return;\n }\n if (gettingDifference) {\n return;\n }\n if (!firstGettingTask) {\n getNewDeleteTask(null);\n firstGettingTask = true;\n }\n gettingDifference = true;\n TLRPC.TL_updates_getDifference req = new TLRPC.TL_updates_getDifference();\n req.pts = MessagesStorage.lastPtsValue;\n req.date = MessagesStorage.lastDateValue;\n req.qts = MessagesStorage.lastQtsValue;\n FileLog.e(\"tmessages\", \"start getDifference with date = \" + MessagesStorage.lastDateValue + \" pts = \" + MessagesStorage.lastPtsValue + \" seq = \" + MessagesStorage.lastSeqValue);\n if (ConnectionsManager.getInstance().getConnectionState() == 0) {\n ConnectionsManager.getInstance().setConnectionState(3);\n final int stateCopy = ConnectionsManager.getInstance().getConnectionState();\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy);\n }\n });\n }\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n gettingDifferenceAgain = false;\n if (error == null) {\n final TLRPC.updates_Difference res = (TLRPC.updates_Difference) response;\n gettingDifferenceAgain = res instanceof TLRPC.TL_updates_differenceSlice;\n\n final HashMap<Integer, TLRPC.User> usersDict = new HashMap<>();\n for (TLRPC.User user : res.users) {\n usersDict.put(user.id, user);\n }\n\n final ArrayList<TLRPC.TL_updateMessageID> msgUpdates = new ArrayList<>();\n if (!res.other_updates.isEmpty()) {\n for (int a = 0; a < res.other_updates.size(); a++) {\n TLRPC.Update upd = res.other_updates.get(a);\n if (upd instanceof TLRPC.TL_updateMessageID) {\n msgUpdates.add((TLRPC.TL_updateMessageID) upd);\n res.other_updates.remove(a);\n a--;\n }\n }\n }\n\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(res.users, false);\n putChats(res.chats, false);\n }\n });\n\n MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {\n @Override\n public void run() {\n if (!msgUpdates.isEmpty()) {\n final HashMap<Integer, Integer> corrected = new HashMap<>();\n for (TLRPC.TL_updateMessageID update : msgUpdates) {\n Integer oldId = MessagesStorage.getInstance().updateMessageStateAndId(update.random_id, null, update.id, 0, false);\n if (oldId != null) {\n corrected.put(oldId, update.id);\n }\n }\n\n if (!corrected.isEmpty()) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n for (HashMap.Entry<Integer, Integer> entry : corrected.entrySet()) {\n Integer oldId = entry.getKey();\n SendMessagesHelper.getInstance().processSentMessage(oldId);\n Integer newId = entry.getValue();\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newId, null);\n }\n }\n });\n }\n }\n\n Utilities.stageQueue.postRunnable(new Runnable() {\n @Override\n public void run() {\n if (!res.new_messages.isEmpty() || !res.new_encrypted_messages.isEmpty()) {\n final HashMap<Long, ArrayList<MessageObject>> messages = new HashMap<>();\n for (TLRPC.EncryptedMessage encryptedMessage : res.new_encrypted_messages) {\n ArrayList<TLRPC.Message> decryptedMessages = SecretChatHelper.getInstance().decryptMessage(encryptedMessage);\n if (decryptedMessages != null && !decryptedMessages.isEmpty()) {\n for (TLRPC.Message message : decryptedMessages) {\n res.new_messages.add(message);\n }\n }\n }\n\n ImageLoader.saveMessagesThumbs(res.new_messages);\n\n final ArrayList<MessageObject> pushMessages = new ArrayList<>();\n for (TLRPC.Message message : res.new_messages) {\n MessageObject obj = new MessageObject(message, usersDict, true);\n\n long dialog_id = obj.messageOwner.dialog_id;\n if (dialog_id == 0) {\n if (obj.messageOwner.to_id.chat_id != 0) {\n dialog_id = -obj.messageOwner.to_id.chat_id;\n } else {\n dialog_id = obj.messageOwner.to_id.user_id;\n }\n }\n\n if (!obj.isFromMe() && obj.isUnread()) {\n pushMessages.add(obj);\n }\n\n long uid;\n if (message.dialog_id != 0) {\n uid = message.dialog_id;\n } else {\n if (message.to_id.chat_id != 0) {\n uid = -message.to_id.chat_id;\n } else {\n if (message.to_id.user_id == UserConfig.getClientUserId()) {\n message.to_id.user_id = message.from_id;\n }\n uid = message.to_id.user_id;\n }\n }\n ArrayList<MessageObject> arr = messages.get(uid);\n if (arr == null) {\n arr = new ArrayList<>();\n messages.put(uid, arr);\n }\n arr.add(obj);\n }\n\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n for (HashMap.Entry<Long, ArrayList<MessageObject>> pair : messages.entrySet()) {\n Long key = pair.getKey();\n ArrayList<MessageObject> value = pair.getValue();\n updateInterfaceWithMessages(key, value);\n }\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n }\n });\n MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {\n @Override\n public void run() {\n if (!pushMessages.isEmpty()) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationsController.getInstance().processNewMessages(pushMessages, !(res instanceof TLRPC.TL_updates_differenceSlice));\n }\n });\n }\n MessagesStorage.getInstance().startTransaction(false);\n MessagesStorage.getInstance().putMessages(res.new_messages, false, false, false, MediaController.getInstance().getAutodownloadMask());\n MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, false, false);\n MessagesStorage.getInstance().commitTransaction(false);\n }\n });\n\n SecretChatHelper.getInstance().processPendingEncMessages();\n }\n\n if (res != null && !res.other_updates.isEmpty()) {\n processUpdateArray(res.other_updates, res.users, res.chats);\n }\n\n gettingDifference = false;\n if (res instanceof TLRPC.TL_updates_difference) {\n MessagesStorage.lastSeqValue = res.state.seq;\n MessagesStorage.lastDateValue = res.state.date;\n MessagesStorage.lastPtsValue = res.state.pts;\n MessagesStorage.lastQtsValue = res.state.qts;\n ConnectionsManager.getInstance().setConnectionState(0);\n boolean done = true;\n for (int a = 0; a < 3; a++) {\n if (!processUpdatesQueue(a, 1)) {\n done = false;\n }\n }\n if (done) {\n final int stateCopy = ConnectionsManager.getInstance().getConnectionState();\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy);\n }\n });\n }\n } else if (res instanceof TLRPC.TL_updates_differenceSlice) {\n MessagesStorage.lastDateValue = res.intermediate_state.date;\n MessagesStorage.lastPtsValue = res.intermediate_state.pts;\n MessagesStorage.lastQtsValue = res.intermediate_state.qts;\n gettingDifferenceAgain = true;\n getDifference();\n } else if (res instanceof TLRPC.TL_updates_differenceEmpty) {\n MessagesStorage.lastSeqValue = res.seq;\n MessagesStorage.lastDateValue = res.date;\n ConnectionsManager.getInstance().setConnectionState(0);\n boolean done = true;\n for (int a = 0; a < 3; a++) {\n if (!processUpdatesQueue(a, 1)) {\n done = false;\n }\n }\n if (done) {\n final int stateCopy = ConnectionsManager.getInstance().getConnectionState();\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy);\n }\n });\n }\n }\n MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);\n FileLog.e(\"tmessages\", \"received difference with date = \" + MessagesStorage.lastDateValue + \" pts = \" + MessagesStorage.lastPtsValue + \" seq = \" + MessagesStorage.lastSeqValue);\n FileLog.e(\"tmessages\", \"messages = \" + res.new_messages.size() + \" users = \" + res.users.size() + \" chats = \" + res.chats.size() + \" other updates = \" + res.other_updates.size());\n }\n });\n }\n });\n } else {\n gettingDifference = false;\n ConnectionsManager.getInstance().setConnectionState(0);\n final int stateCopy = ConnectionsManager.getInstance().getConnectionState();\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy);\n }\n });\n }\n }\n });\n }\n\n public void processUpdates(final TLRPC.Updates updates, boolean fromQueue) {\n boolean needGetDiff = false;\n boolean needReceivedQueue = false;\n boolean updateStatus = false;\n if (updates instanceof TLRPC.TL_updateShort) {\n ArrayList<TLRPC.Update> arr = new ArrayList<>();\n arr.add(updates.update);\n processUpdateArray(arr, null, null);\n } else if (updates instanceof TLRPC.TL_updateShortChatMessage || updates instanceof TLRPC.TL_updateShortMessage) {\n TLRPC.User user = getUser(updates.user_id);\n TLRPC.User user2 = null;\n\n boolean needFwdUser = false;\n if (updates.fwd_from_id != 0) {\n user2 = getUser(updates.fwd_from_id);\n needFwdUser = true;\n }\n\n boolean missingData = false;\n if (updates instanceof TLRPC.TL_updateShortMessage) {\n missingData = user == null || needFwdUser && user2 == null;\n } else {\n missingData = getChat(updates.chat_id) == null || user == null || needFwdUser && user2 == null;\n }\n if (user != null && user.status != null && user.status.expires <= 0) {\n onlinePrivacy.put(user.id, ConnectionsManager.getInstance().getCurrentTime());\n updateStatus = true;\n }\n\n if (missingData) {\n needGetDiff = true;\n } else {\n if (MessagesStorage.lastPtsValue + updates.pts_count == updates.pts) {\n TLRPC.TL_message message = new TLRPC.TL_message();\n message.id = updates.id;\n if (updates instanceof TLRPC.TL_updateShortMessage) {\n if ((updates.flags & TLRPC.MESSAGE_FLAG_OUT) != 0) {\n message.from_id = UserConfig.getClientUserId();\n } else {\n message.from_id = updates.user_id;\n }\n message.to_id = new TLRPC.TL_peerUser();\n message.to_id.user_id = updates.user_id;\n message.dialog_id = updates.user_id;\n } else {\n message.from_id = updates.user_id;\n message.to_id = new TLRPC.TL_peerChat();\n message.to_id.chat_id = updates.chat_id;\n message.dialog_id = -updates.chat_id;\n }\n message.message = updates.message;\n message.date = updates.date;\n message.flags = updates.flags;\n message.fwd_from_id = updates.fwd_from_id;\n message.fwd_date = updates.fwd_date;\n message.reply_to_msg_id = updates.reply_to_msg_id;\n message.media = new TLRPC.TL_messageMediaEmpty();\n MessagesStorage.lastPtsValue = updates.pts;\n final MessageObject obj = new MessageObject(message, null, true);\n final ArrayList<MessageObject> objArr = new ArrayList<>();\n objArr.add(obj);\n ArrayList<TLRPC.Message> arr = new ArrayList<>();\n arr.add(message);\n if (updates instanceof TLRPC.TL_updateShortMessage) {\n final boolean printUpdate = (updates.flags & TLRPC.MESSAGE_FLAG_OUT) == 0 && updatePrintingUsersWithNewMessages(updates.user_id, objArr);\n if (printUpdate) {\n updatePrintingStrings();\n }\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n if (printUpdate) {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT);\n }\n updateInterfaceWithMessages(updates.user_id, objArr);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n }\n });\n } else {\n final boolean printUpdate = updatePrintingUsersWithNewMessages(-updates.chat_id, objArr);\n if (printUpdate) {\n updatePrintingStrings();\n }\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n if (printUpdate) {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT);\n }\n\n updateInterfaceWithMessages(-updates.chat_id, objArr);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n }\n });\n }\n\n MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {\n @Override\n public void run() {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n if (!obj.isFromMe() && obj.isUnread()) {\n NotificationsController.getInstance().processNewMessages(objArr, true);\n }\n }\n });\n }\n });\n MessagesStorage.getInstance().putMessages(arr, false, true, false, 0);\n } else if (MessagesStorage.lastPtsValue != updates.pts) {\n FileLog.e(\"tmessages\", \"need get diff short message, pts: \" + MessagesStorage.lastPtsValue + \" \" + updates.pts + \" count = \" + updates.pts_count);\n if (gettingDifference || updatesStartWaitTimePts == 0 || updatesStartWaitTimePts != 0 && updatesStartWaitTimePts + 1500 > System.currentTimeMillis()) {\n if (updatesStartWaitTimePts == 0) {\n updatesStartWaitTimePts = System.currentTimeMillis();\n }\n FileLog.e(\"tmessages\", \"add short message to queue\");\n updatesQueuePts.add(updates);\n } else {\n needGetDiff = true;\n }\n }\n }\n } else if (updates instanceof TLRPC.TL_updatesCombined || updates instanceof TLRPC.TL_updates) {\n MessagesStorage.getInstance().putUsersAndChats(updates.users, updates.chats, true, true);\n int lastQtsValue = MessagesStorage.lastQtsValue;\n for (int a = 0; a < updates.updates.size(); a++) {\n TLRPC.Update update = updates.updates.get(a);\n if (update instanceof TLRPC.TL_updateNewMessage || update instanceof TLRPC.TL_updateReadMessages || update instanceof TLRPC.TL_updateReadHistoryInbox ||\n update instanceof TLRPC.TL_updateReadHistoryOutbox || update instanceof TLRPC.TL_updateDeleteMessages) {\n TLRPC.TL_updates updatesNew = new TLRPC.TL_updates();\n updatesNew.updates.add(update);\n updatesNew.pts = update.pts;\n updatesNew.pts_count = update.pts_count;\n if (MessagesStorage.lastPtsValue + update.pts_count == update.pts) {\n if (!processUpdateArray(updatesNew.updates, updates.users, updates.chats)) {\n FileLog.e(\"tmessages\", \"need get diff inner TL_updates, seq: \" + MessagesStorage.lastSeqValue + \" \" + updates.seq);\n needGetDiff = true;\n } else {\n MessagesStorage.lastPtsValue = update.pts;\n }\n } else if (MessagesStorage.lastPtsValue != update.pts) {\n FileLog.e(\"tmessages\", update + \" need get diff, pts: \" + MessagesStorage.lastPtsValue + \" \" + update.pts + \" count = \" + update.pts_count);\n if (gettingDifference || updatesStartWaitTimePts == 0 || updatesStartWaitTimePts != 0 && updatesStartWaitTimePts + 1500 > System.currentTimeMillis()) {\n if (updatesStartWaitTimePts == 0) {\n updatesStartWaitTimePts = System.currentTimeMillis();\n }\n FileLog.e(\"tmessages\", \"add short message to queue\");\n updatesQueuePts.add(updatesNew);\n } else {\n needGetDiff = true;\n }\n }\n } else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) {\n TLRPC.TL_updates updatesNew = new TLRPC.TL_updates();\n updatesNew.updates.add(update);\n updatesNew.qts = update.qts;\n if (MessagesStorage.lastQtsValue == 0 || MessagesStorage.lastQtsValue + 1 == update.qts) {\n processUpdateArray(updatesNew.updates, updates.users, updates.chats);\n MessagesStorage.lastQtsValue = update.qts;\n needReceivedQueue = true;\n } else if (MessagesStorage.lastPtsValue != update.qts) {\n FileLog.e(\"tmessages\", update + \" need get diff, qts: \" + MessagesStorage.lastQtsValue + \" \" + update.qts);\n if (gettingDifference || updatesStartWaitTimeQts == 0 || updatesStartWaitTimeQts != 0 && updatesStartWaitTimeQts + 1500 > System.currentTimeMillis()) {\n if (updatesStartWaitTimeQts == 0) {\n updatesStartWaitTimeQts = System.currentTimeMillis();\n }\n FileLog.e(\"tmessages\", \"add short message to queue\");\n updatesQueueQts.add(updatesNew);\n } else {\n needGetDiff = true;\n }\n }\n } else {\n continue;\n }\n updates.updates.remove(a);\n a--;\n }\n\n boolean processUpdate = false;\n if (updates instanceof TLRPC.TL_updatesCombined) {\n processUpdate = MessagesStorage.lastSeqValue + 1 == updates.seq_start || MessagesStorage.lastSeqValue == updates.seq_start;\n } else {\n processUpdate = MessagesStorage.lastSeqValue + 1 == updates.seq || updates.seq == 0 || updates.seq == MessagesStorage.lastSeqValue;\n }\n if (processUpdate) {\n processUpdateArray(updates.updates, updates.users, updates.chats);\n MessagesStorage.lastDateValue = updates.date;\n if (updates.seq != 0) {\n MessagesStorage.lastSeqValue = updates.seq;\n }\n } else {\n if (updates instanceof TLRPC.TL_updatesCombined) {\n FileLog.e(\"tmessages\", \"need get diff TL_updatesCombined, seq: \" + MessagesStorage.lastSeqValue + \" \" + updates.seq_start);\n } else {\n FileLog.e(\"tmessages\", \"need get diff TL_updates, seq: \" + MessagesStorage.lastSeqValue + \" \" + updates.seq);\n }\n\n if (gettingDifference || updatesStartWaitTimeSeq == 0 || updatesStartWaitTimeSeq != 0 && updatesStartWaitTimeSeq + 1500 > System.currentTimeMillis()) {\n if (updatesStartWaitTimeSeq == 0) {\n updatesStartWaitTimeSeq = System.currentTimeMillis();\n }\n FileLog.e(\"tmessages\", \"add TL_updates/Combined to queue\");\n updatesQueueSeq.add(updates);\n } else {\n needGetDiff = true;\n }\n }\n } else if (updates instanceof TLRPC.TL_updatesTooLong) {\n FileLog.e(\"tmessages\", \"need get diff TL_updatesTooLong\");\n needGetDiff = true;\n } else if (updates instanceof UserActionUpdatesSeq) {\n MessagesStorage.lastSeqValue = updates.seq;\n } else if (updates instanceof UserActionUpdatesPts) {\n MessagesStorage.lastPtsValue = updates.pts;\n }\n SecretChatHelper.getInstance().processPendingEncMessages();\n if (!fromQueue) {\n if (needGetDiff) {\n getDifference();\n } else {\n for (int a = 0; a < 3; a++) {\n ArrayList<TLRPC.Updates> updatesQueue = null;\n if (a == 0) {\n updatesQueue = updatesQueueSeq;\n } else if (a == 1) {\n updatesQueue = updatesQueuePts;\n } else if (a == 2) {\n updatesQueue = updatesQueueQts;\n }\n if (!updatesQueue.isEmpty()) {\n processUpdatesQueue(a, 0);\n }\n }\n }\n }\n if (needReceivedQueue) {\n TLRPC.TL_messages_receivedQueue req = new TLRPC.TL_messages_receivedQueue();\n req.max_qts = MessagesStorage.lastQtsValue;\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n\n }\n });\n }\n if (updateStatus) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_STATUS);\n }\n });\n }\n MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);\n }\n\n public boolean processUpdateArray(ArrayList<TLRPC.Update> updates, final ArrayList<TLRPC.User> usersArr, final ArrayList<TLRPC.Chat> chatsArr) {\n if (updates.isEmpty()) {\n return true;\n }\n long currentTime = System.currentTimeMillis();\n\n final HashMap<Long, ArrayList<MessageObject>> messages = new HashMap<>();\n final ArrayList<MessageObject> pushMessages = new ArrayList<>();\n final ArrayList<TLRPC.Message> messagesArr = new ArrayList<>();\n final HashMap<Integer, Integer> markAsReadMessagesInbox = new HashMap<>();\n final HashMap<Integer, Integer> markAsReadMessagesOutbox = new HashMap<>();\n final HashMap<Integer, Integer> markAsReadEncrypted = new HashMap<>();\n final ArrayList<Integer> deletedMessages = new ArrayList<>();\n boolean printChanged = false;\n final ArrayList<TLRPC.ChatParticipants> chatInfoToUpdate = new ArrayList<>();\n final ArrayList<TLRPC.Update> updatesOnMainThread = new ArrayList<>();\n final ArrayList<TLRPC.TL_updateEncryptedMessagesRead> tasks = new ArrayList<>();\n final ArrayList<Integer> contactsIds = new ArrayList<>();\n\n boolean checkForUsers = true;\n ConcurrentHashMap<Integer, TLRPC.User> usersDict;\n ConcurrentHashMap<Integer, TLRPC.Chat> chatsDict;\n if (usersArr != null) {\n usersDict = new ConcurrentHashMap<>();\n for (TLRPC.User user : usersArr) {\n usersDict.put(user.id, user);\n }\n } else {\n checkForUsers = false;\n usersDict = users;\n }\n if (chatsArr != null) {\n chatsDict = new ConcurrentHashMap<>();\n for (TLRPC.Chat chat : chatsArr) {\n chatsDict.put(chat.id, chat);\n }\n } else {\n checkForUsers = false;\n chatsDict = chats;\n }\n\n if (usersArr != null || chatsArr != null) {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n putUsers(usersArr, false);\n putChats(chatsArr, false);\n }\n });\n }\n\n int interfaceUpdateMask = 0;\n\n for (TLRPC.Update update : updates) {\n if (update instanceof TLRPC.TL_updateNewMessage) {\n TLRPC.TL_updateNewMessage upd = (TLRPC.TL_updateNewMessage)update;\n if (checkForUsers) {\n TLRPC.User user = getUser(upd.message.from_id);\n if (usersDict.get(upd.message.from_id) == null && user == null || upd.message.to_id.chat_id != 0 && chatsDict.get(upd.message.to_id.chat_id) == null && getChat(upd.message.to_id.chat_id) == null) {\n return false;\n }\n\n if (user != null && user.status != null && user.status.expires <= 0) {\n onlinePrivacy.put(upd.message.from_id, ConnectionsManager.getInstance().getCurrentTime());\n interfaceUpdateMask |= UPDATE_MASK_STATUS;\n }\n }\n messagesArr.add(upd.message);\n ImageLoader.saveMessageThumbs(upd.message);\n MessageObject obj = new MessageObject(upd.message, usersDict, true);\n if (obj.type == 11) {\n interfaceUpdateMask |= UPDATE_MASK_CHAT_AVATAR;\n } else if (obj.type == 10) {\n interfaceUpdateMask |= UPDATE_MASK_CHAT_NAME;\n }\n long uid;\n if (upd.message.to_id.chat_id != 0) {\n uid = -upd.message.to_id.chat_id;\n } else {\n if (upd.message.to_id.user_id == UserConfig.getClientUserId()) {\n upd.message.to_id.user_id = upd.message.from_id;\n }\n uid = upd.message.to_id.user_id;\n }\n ArrayList<MessageObject> arr = messages.get(uid);\n if (arr == null) {\n arr = new ArrayList<>();\n messages.put(uid, arr);\n }\n arr.add(obj);\n if (!obj.isFromMe() && obj.isUnread()) {\n pushMessages.add(obj);\n }\n } else if (update instanceof TLRPC.TL_updateReadMessages) {\n //markAsReadMessages.addAll(update.messages); disabled for now\n } else if (update instanceof TLRPC.TL_updateReadHistoryInbox) {\n TLRPC.Peer peer = ((TLRPC.TL_updateReadHistoryInbox) update).peer;\n if (peer.chat_id != 0) {\n markAsReadMessagesInbox.put(-peer.chat_id, update.max_id);\n } else {\n markAsReadMessagesInbox.put(peer.user_id, update.max_id);\n }\n } else if (update instanceof TLRPC.TL_updateReadHistoryOutbox) {\n TLRPC.Peer peer = ((TLRPC.TL_updateReadHistoryOutbox) update).peer;\n if (peer.chat_id != 0) {\n markAsReadMessagesOutbox.put(-peer.chat_id, update.max_id);\n } else {\n markAsReadMessagesOutbox.put(peer.user_id, update.max_id);\n }\n } else if (update instanceof TLRPC.TL_updateDeleteMessages) {\n deletedMessages.addAll(update.messages);\n } else if (update instanceof TLRPC.TL_updateUserTyping || update instanceof TLRPC.TL_updateChatUserTyping) {\n if (update.action instanceof TLRPC.TL_sendMessageTypingAction && update.user_id != UserConfig.getClientUserId()) {\n long uid = -update.chat_id;\n if (uid == 0) {\n uid = update.user_id;\n }\n ArrayList<PrintingUser> arr = printingUsers.get(uid);\n if (arr == null) {\n arr = new ArrayList<>();\n printingUsers.put(uid, arr);\n }\n boolean exist = false;\n for (PrintingUser u : arr) {\n if (u.userId == update.user_id) {\n exist = true;\n u.lastTime = currentTime;\n break;\n }\n }\n if (!exist) {\n PrintingUser newUser = new PrintingUser();\n newUser.userId = update.user_id;\n newUser.lastTime = currentTime;\n arr.add(newUser);\n printChanged = true;\n }\n onlinePrivacy.put(update.user_id, ConnectionsManager.getInstance().getCurrentTime());\n }\n } else if (update instanceof TLRPC.TL_updateChatParticipants) {\n interfaceUpdateMask |= UPDATE_MASK_CHAT_MEMBERS;\n chatInfoToUpdate.add(update.participants);\n } else if (update instanceof TLRPC.TL_updateUserStatus) {\n interfaceUpdateMask |= UPDATE_MASK_STATUS;\n updatesOnMainThread.add(update);\n } else if (update instanceof TLRPC.TL_updateUserName) {\n interfaceUpdateMask |= UPDATE_MASK_NAME;\n updatesOnMainThread.add(update);\n } else if (update instanceof TLRPC.TL_updateUserPhoto) {\n interfaceUpdateMask |= UPDATE_MASK_AVATAR;\n MessagesStorage.getInstance().clearUserPhotos(update.user_id);\n updatesOnMainThread.add(update);\n } else if (update instanceof TLRPC.TL_updateUserPhone) {\n interfaceUpdateMask |= UPDATE_MASK_PHONE;\n updatesOnMainThread.add(update);\n } else if (update instanceof TLRPC.TL_updateContactRegistered) {\n if (enableJoined && usersDict.containsKey(update.user_id)) {\n TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();\n newMessage.action = new TLRPC.TL_messageActionUserJoined();\n newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();\n UserConfig.saveConfig(false);\n newMessage.flags = TLRPC.MESSAGE_FLAG_UNREAD;\n newMessage.date = update.date;\n newMessage.from_id = update.user_id;\n newMessage.to_id = new TLRPC.TL_peerUser();\n newMessage.to_id.user_id = UserConfig.getClientUserId();\n newMessage.dialog_id = update.user_id;\n\n messagesArr.add(newMessage);\n MessageObject obj = new MessageObject(newMessage, usersDict, true);\n ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);\n if (arr == null) {\n arr = new ArrayList<>();\n messages.put(newMessage.dialog_id, arr);\n }\n arr.add(obj);\n pushMessages.add(obj);\n }\n } else if (update instanceof TLRPC.TL_updateContactLink) {\n if (update.my_link instanceof TLRPC.TL_contactLinkContact) {\n int idx = contactsIds.indexOf(-update.user_id);\n if (idx != -1) {\n contactsIds.remove(idx);\n }\n if (!contactsIds.contains(update.user_id)) {\n contactsIds.add(update.user_id);\n }\n } else {\n int idx = contactsIds.indexOf(update.user_id);\n if (idx != -1) {\n contactsIds.remove(idx);\n }\n if (!contactsIds.contains(update.user_id)) {\n contactsIds.add(-update.user_id);\n }\n }\n } else if (update instanceof TLRPC.TL_updateActivation) {\n //DEPRECATED\n } else if (update instanceof TLRPC.TL_updateNewAuthorization) {\n // Disabled\n } else if (update instanceof TLRPC.TL_updateNewGeoChatMessage) {\n //DEPRECATED\n } else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) {\n ArrayList<TLRPC.Message> decryptedMessages = SecretChatHelper.getInstance().decryptMessage(((TLRPC.TL_updateNewEncryptedMessage) update).message);\n if (decryptedMessages != null && !decryptedMessages.isEmpty()) {\n int cid = ((TLRPC.TL_updateNewEncryptedMessage)update).message.chat_id;\n long uid = ((long) cid) << 32;\n ArrayList<MessageObject> arr = messages.get(uid);\n if (arr == null) {\n arr = new ArrayList<>();\n messages.put(uid, arr);\n }\n for (TLRPC.Message message : decryptedMessages) {\n ImageLoader.saveMessageThumbs(message);\n messagesArr.add(message);\n MessageObject obj = new MessageObject(message, usersDict, true);\n arr.add(obj);\n pushMessages.add(obj);\n }\n }\n } else if (update instanceof TLRPC.TL_updateEncryptedChatTyping) {\n TLRPC.EncryptedChat encryptedChat = getEncryptedChatDB(update.chat_id);\n if (encryptedChat != null) {\n update.user_id = encryptedChat.user_id;\n long uid = ((long) update.chat_id) << 32;\n ArrayList<PrintingUser> arr = printingUsers.get(uid);\n if (arr == null) {\n arr = new ArrayList<>();\n printingUsers.put(uid, arr);\n }\n boolean exist = false;\n for (PrintingUser u : arr) {\n if (u.userId == update.user_id) {\n exist = true;\n u.lastTime = currentTime;\n break;\n }\n }\n if (!exist) {\n PrintingUser newUser = new PrintingUser();\n newUser.userId = update.user_id;\n newUser.lastTime = currentTime;\n arr.add(newUser);\n printChanged = true;\n }\n onlinePrivacy.put(update.user_id, ConnectionsManager.getInstance().getCurrentTime());\n }\n } else if (update instanceof TLRPC.TL_updateEncryptedMessagesRead) {\n markAsReadEncrypted.put(update.chat_id, Math.max(update.max_date, update.date));\n tasks.add((TLRPC.TL_updateEncryptedMessagesRead) update);\n } else if (update instanceof TLRPC.TL_updateChatParticipantAdd) {\n MessagesStorage.getInstance().updateChatInfo(update.chat_id, update.user_id, false, update.inviter_id, update.version);\n } else if (update instanceof TLRPC.TL_updateChatParticipantDelete) {\n MessagesStorage.getInstance().updateChatInfo(update.chat_id, update.user_id, true, 0, update.version);\n } else if (update instanceof TLRPC.TL_updateDcOptions) {\n ConnectionsManager.getInstance().updateDcSettings(0);\n } else if (update instanceof TLRPC.TL_updateEncryption) {\n SecretChatHelper.getInstance().processUpdateEncryption((TLRPC.TL_updateEncryption) update, usersDict);\n } else if (update instanceof TLRPC.TL_updateUserBlocked) {\n final TLRPC.TL_updateUserBlocked finalUpdate = (TLRPC.TL_updateUserBlocked)update;\n if (finalUpdate.blocked) {\n ArrayList<Integer> ids = new ArrayList<>();\n ids.add(finalUpdate.user_id);\n MessagesStorage.getInstance().putBlockedUsers(ids, false);\n } else {\n MessagesStorage.getInstance().deleteBlockedUser(finalUpdate.user_id);\n }\n MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {\n @Override\n public void run() {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n if (finalUpdate.blocked) {\n if (!blockedUsers.contains(finalUpdate.user_id)) {\n blockedUsers.add(finalUpdate.user_id);\n }\n } else {\n blockedUsers.remove((Integer) finalUpdate.user_id);\n }\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded);\n }\n });\n }\n });\n } else if (update instanceof TLRPC.TL_updateNotifySettings) {\n updatesOnMainThread.add(update);\n } else if (update instanceof TLRPC.TL_updateServiceNotification) {\n TLRPC.TL_message newMessage = new TLRPC.TL_message();\n newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();\n UserConfig.saveConfig(false);\n newMessage.flags = TLRPC.MESSAGE_FLAG_UNREAD;\n newMessage.date = update.date;\n newMessage.from_id = 777000;\n newMessage.to_id = new TLRPC.TL_peerUser();\n newMessage.to_id.user_id = UserConfig.getClientUserId();\n newMessage.dialog_id = 777000;\n newMessage.media = update.media;\n newMessage.message = ((TLRPC.TL_updateServiceNotification)update).message;\n\n messagesArr.add(newMessage);\n MessageObject obj = new MessageObject(newMessage, usersDict, true);\n ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);\n if (arr == null) {\n arr = new ArrayList<>();\n messages.put(newMessage.dialog_id, arr);\n }\n arr.add(obj);\n pushMessages.add(obj);\n } else if (update instanceof TLRPC.TL_updatePrivacy) {\n updatesOnMainThread.add(update);\n }\n }\n if (!messages.isEmpty()) {\n for (HashMap.Entry<Long, ArrayList<MessageObject>> pair : messages.entrySet()) {\n Long key = pair.getKey();\n ArrayList<MessageObject> value = pair.getValue();\n if (updatePrintingUsersWithNewMessages(key, value)) {\n printChanged = true;\n }\n }\n }\n\n if (printChanged) {\n updatePrintingStrings();\n }\n\n final int interfaceUpdateMaskFinal = interfaceUpdateMask;\n final boolean printChangedArg = printChanged;\n\n if (!contactsIds.isEmpty()) {\n ContactsController.getInstance().processContactsUpdates(contactsIds, usersDict);\n }\n\n MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {\n @Override\n public void run() {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n if (!pushMessages.isEmpty()) {\n NotificationsController.getInstance().processNewMessages(pushMessages, true);\n }\n }\n });\n }\n });\n\n if (!messagesArr.isEmpty()) {\n MessagesStorage.getInstance().putMessages(messagesArr, true, true, false, MediaController.getInstance().getAutodownloadMask());\n }\n\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n int updateMask = interfaceUpdateMaskFinal;\n\n boolean avatarsUpdate = false;\n if (!updatesOnMainThread.isEmpty()) {\n ArrayList<TLRPC.User> dbUsers = new ArrayList<>();\n ArrayList<TLRPC.User> dbUsersStatus = new ArrayList<>();\n SharedPreferences.Editor editor = null;\n for (TLRPC.Update update : updatesOnMainThread) {\n final TLRPC.User toDbUser = new TLRPC.User();\n toDbUser.id = update.user_id;\n final TLRPC.User currentUser = getUser(update.user_id);\n if (update instanceof TLRPC.TL_updatePrivacy) {\n if (update.key instanceof TLRPC.TL_privacyKeyStatusTimestamp) {\n ContactsController.getInstance().setPrivacyRules(update.rules);\n }\n } else if (update instanceof TLRPC.TL_updateUserStatus) {\n if (update.status instanceof TLRPC.TL_userStatusRecently) {\n update.status.expires = -100;\n } else if (update.status instanceof TLRPC.TL_userStatusLastWeek) {\n update.status.expires = -101;\n } else if (update.status instanceof TLRPC.TL_userStatusLastMonth) {\n update.status.expires = -102;\n }\n if (currentUser != null) {\n currentUser.id = update.user_id;\n currentUser.status = update.status;\n }\n toDbUser.status = update.status;\n dbUsersStatus.add(toDbUser);\n if (update.user_id == UserConfig.getClientUserId()) {\n NotificationsController.getInstance().setLastOnlineFromOtherDevice(update.status.expires);\n }\n } else if (update instanceof TLRPC.TL_updateUserName) {\n if (currentUser != null) {\n if (currentUser.username != null && currentUser.username.length() > 0) {\n usersByUsernames.remove(currentUser.username);\n }\n if (update.username != null && update.username.length() > 0) {\n usersByUsernames.put(update.username, currentUser);\n }\n currentUser.first_name = update.first_name;\n currentUser.last_name = update.last_name;\n currentUser.username = update.username;\n }\n toDbUser.first_name = update.first_name;\n toDbUser.last_name = update.last_name;\n toDbUser.username = update.username;\n dbUsers.add(toDbUser);\n } else if (update instanceof TLRPC.TL_updateUserPhoto) {\n if (currentUser != null) {\n currentUser.photo = update.photo;\n }\n avatarsUpdate = true;\n toDbUser.photo = update.photo;\n dbUsers.add(toDbUser);\n } else if (update instanceof TLRPC.TL_updateUserPhone) {\n if (currentUser != null) {\n currentUser.phone = update.phone;\n Utilities.photoBookQueue.postRunnable(new Runnable() {\n @Override\n public void run() {\n ContactsController.getInstance().addContactToPhoneBook(currentUser, true);\n }\n });\n }\n toDbUser.phone = update.phone;\n dbUsers.add(toDbUser);\n } else if (update instanceof TLRPC.TL_updateNotifySettings) {\n if (update.notify_settings instanceof TLRPC.TL_peerNotifySettings && update.peer instanceof TLRPC.TL_notifyPeer) {\n if (editor == null) {\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"Notifications\", Activity.MODE_PRIVATE);\n editor = preferences.edit();\n }\n long dialog_id = update.peer.peer.user_id;\n if (dialog_id == 0) {\n dialog_id = -update.peer.peer.chat_id;\n }\n TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);\n if (dialog != null) {\n dialog.notify_settings = update.notify_settings;\n }\n if (update.notify_settings.mute_until > ConnectionsManager.getInstance().getCurrentTime()) {\n int until = 0;\n if (update.notify_settings.mute_until > ConnectionsManager.getInstance().getCurrentTime() + 60 * 60 * 24 * 365) {\n editor.putInt(\"notify2_\" + dialog_id, 2);\n if (dialog != null) {\n dialog.notify_settings.mute_until = Integer.MAX_VALUE;\n }\n } else {\n until = update.notify_settings.mute_until;\n editor.putInt(\"notify2_\" + dialog_id, 3);\n editor.putInt(\"notifyuntil_\" + dialog_id, update.notify_settings.mute_until);\n if (dialog != null) {\n dialog.notify_settings.mute_until = until;\n }\n }\n MessagesStorage.getInstance().setDialogFlags(dialog_id, ((long)until << 32) | 1);\n } else {\n if (dialog != null) {\n dialog.notify_settings.mute_until = 0;\n }\n editor.remove(\"notify2_\" + dialog_id);\n MessagesStorage.getInstance().setDialogFlags(dialog_id, 0);\n }\n\n }/* else if (update.peer instanceof TLRPC.TL_notifyChats) { disable global settings sync\n if (editor == null) {\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"Notifications\", Activity.MODE_PRIVATE);\n editor = preferences.edit();\n }\n editor.putBoolean(\"EnableGroup\", update.notify_settings.mute_until == 0);\n editor.putBoolean(\"EnablePreviewGroup\", update.notify_settings.show_previews);\n } else if (update.peer instanceof TLRPC.TL_notifyUsers) {\n if (editor == null) {\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"Notifications\", Activity.MODE_PRIVATE);\n editor = preferences.edit();\n }\n editor.putBoolean(\"EnableAll\", update.notify_settings.mute_until == 0);\n editor.putBoolean(\"EnablePreviewAll\", update.notify_settings.show_previews);\n }*/\n }\n }\n if (editor != null) {\n editor.commit();\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.notificationsSettingsUpdated);\n }\n MessagesStorage.getInstance().updateUsers(dbUsersStatus, true, true, true);\n MessagesStorage.getInstance().updateUsers(dbUsers, false, true, true);\n }\n\n if (!messages.isEmpty()) {\n for (HashMap.Entry<Long, ArrayList<MessageObject>> entry : messages.entrySet()) {\n Long key = entry.getKey();\n ArrayList<MessageObject> value = entry.getValue();\n updateInterfaceWithMessages(key, value);\n }\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);\n }\n if (printChangedArg) {\n updateMask |= UPDATE_MASK_USER_PRINT;\n }\n if (!contactsIds.isEmpty()) {\n updateMask |= UPDATE_MASK_NAME;\n updateMask |= UPDATE_MASK_USER_PHONE;\n }\n if (!chatInfoToUpdate.isEmpty()) {\n for (TLRPC.ChatParticipants info : chatInfoToUpdate) {\n MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info);\n }\n }\n if (updateMask != 0) {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, updateMask);\n }\n }\n });\n\n MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {\n @Override\n public void run() {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n int updateMask = 0;\n if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()) {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesRead, markAsReadMessagesInbox, markAsReadMessagesOutbox);\n NotificationsController.getInstance().processReadMessages(markAsReadMessagesInbox, 0, 0, 0, false);\n for (HashMap.Entry<Integer, Integer> entry : markAsReadMessagesInbox.entrySet()) {\n TLRPC.TL_dialog dialog = dialogs_dict.get((long) entry.getKey());\n if (dialog != null && dialog.top_message <= entry.getValue()) {\n MessageObject obj = dialogMessage.get(dialog.top_message);\n if (obj != null) {\n obj.setIsRead();\n updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;\n }\n }\n }\n for (HashMap.Entry<Integer, Integer> entry : markAsReadMessagesOutbox.entrySet()) {\n TLRPC.TL_dialog dialog = dialogs_dict.get((long) entry.getKey());\n if (dialog != null && dialog.top_message <= entry.getValue()) {\n MessageObject obj = dialogMessage.get(dialog.top_message);\n if (obj != null) {\n obj.setIsRead();\n updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;\n }\n }\n }\n }\n if (!markAsReadEncrypted.isEmpty()) {\n for (HashMap.Entry<Integer, Integer> entry : markAsReadEncrypted.entrySet()) {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesReadedEncrypted, entry.getKey(), entry.getValue());\n long dialog_id = (long) (entry.getKey()) << 32;\n TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);\n if (dialog != null) {\n MessageObject message = dialogMessage.get(dialog.top_message);\n if (message != null && message.messageOwner.date <= entry.getValue()) {\n message.setIsRead();\n updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;\n }\n }\n }\n }\n if (!deletedMessages.isEmpty()) {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesDeleted, deletedMessages);\n for (Integer id : deletedMessages) {\n MessageObject obj = dialogMessage.get(id);\n if (obj != null) {\n obj.deleted = true;\n }\n }\n }\n if (updateMask != 0) {\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, updateMask);\n }\n }\n });\n }\n });\n\n if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty() || !markAsReadEncrypted.isEmpty()) {\n if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()) {\n MessagesStorage.getInstance().updateDialogsWithReadedMessages(markAsReadMessagesInbox, true);\n }\n MessagesStorage.getInstance().markMessagesAsRead(markAsReadMessagesInbox, markAsReadMessagesOutbox, markAsReadEncrypted, true);\n }\n if (!deletedMessages.isEmpty()) {\n MessagesStorage.getInstance().markMessagesAsDeleted(deletedMessages, true);\n }\n if (!deletedMessages.isEmpty()) {\n MessagesStorage.getInstance().updateDialogsWithDeletedMessages(deletedMessages, true);\n }\n if (!tasks.isEmpty()) {\n for (TLRPC.TL_updateEncryptedMessagesRead update : tasks) {\n MessagesStorage.getInstance().createTaskForSecretChat(update.chat_id, update.max_date, update.date, 1, null);\n }\n }\n\n return true;\n }\n\n private boolean isNotifySettingsMuted(TLRPC.PeerNotifySettings settings) {\n return settings instanceof TLRPC.TL_peerNotifySettings && settings.mute_until > ConnectionsManager.getInstance().getCurrentTime();\n }\n\n public boolean isDialogMuted(long dialog_id) {\n SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences(\"Notifications\", Activity.MODE_PRIVATE);\n int mute_type = preferences.getInt(\"notify2_\" + dialog_id, 0);\n if (mute_type == 2) {\n return true;\n } else if (mute_type == 3) {\n int mute_until = preferences.getInt(\"notifyuntil_\" + dialog_id, 0);\n if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) {\n return true;\n }\n }\n return false;\n }\n\n private boolean updatePrintingUsersWithNewMessages(long uid, ArrayList<MessageObject> messages) {\n if (uid > 0) {\n ArrayList<PrintingUser> arr = printingUsers.get(uid);\n if (arr != null) {\n printingUsers.remove(uid);\n return true;\n }\n } else if (uid < 0) {\n ArrayList<Integer> messagesUsers = new ArrayList<>();\n for (MessageObject message : messages) {\n if (!messagesUsers.contains(message.messageOwner.from_id)) {\n messagesUsers.add(message.messageOwner.from_id);\n }\n }\n\n ArrayList<PrintingUser> arr = printingUsers.get(uid);\n boolean changed = false;\n if (arr != null) {\n for (int a = 0; a < arr.size(); a++) {\n PrintingUser user = arr.get(a);\n if (messagesUsers.contains(user.userId)) {\n arr.remove(a);\n a--;\n if (arr.isEmpty()) {\n printingUsers.remove(uid);\n }\n changed = true;\n }\n }\n }\n if (changed) {\n return true;\n }\n }\n return false;\n }\n\n protected void updateInterfaceWithMessages(long uid, ArrayList<MessageObject> messages) {\n updateInterfaceWithMessages(uid, messages, false);\n }\n\n protected void updateInterfaceWithMessages(final long uid, final ArrayList<MessageObject> messages, boolean isBroadcast) {\n MessageObject lastMessage = null;\n TLRPC.TL_dialog dialog = dialogs_dict.get(uid);\n\n boolean isEncryptedChat = ((int)uid) == 0;\n\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.didReceivedNewMessages, uid, messages);\n\n for (MessageObject message : messages) {\n if (lastMessage == null || (!isEncryptedChat && message.getId() > lastMessage.getId() || isEncryptedChat && message.getId() < lastMessage.getId()) || message.messageOwner.date > lastMessage.messageOwner.date) {\n lastMessage = message;\n }\n }\n\n boolean changed = false;\n\n if (dialog == null) {\n if (!isBroadcast) {\n dialog = new TLRPC.TL_dialog();\n dialog.id = uid;\n dialog.unread_count = 0;\n dialog.top_message = lastMessage.getId();\n dialog.last_message_date = lastMessage.messageOwner.date;\n dialogs_dict.put(uid, dialog);\n dialogs.add(dialog);\n dialogMessage.put(lastMessage.getId(), lastMessage);\n changed = true;\n }\n } else {\n boolean change = false;\n if (dialog.top_message > 0 && lastMessage.getId() > 0 && lastMessage.getId() > dialog.top_message ||\n dialog.top_message < 0 && lastMessage.getId() < 0 && lastMessage.getId() < dialog.top_message) {\n change = true;\n } else {\n MessageObject currentDialogMessage = dialogMessage.get(dialog.top_message);\n if (currentDialogMessage != null) {\n if (currentDialogMessage.isSending() && lastMessage.isSending()) {\n change = true;\n } else if (dialog.last_message_date < lastMessage.messageOwner.date || dialog.last_message_date == lastMessage.messageOwner.date && lastMessage.isSending()) {\n change = true;\n }\n } else {\n change = true;\n }\n }\n if (change) {\n dialogMessage.remove(dialog.top_message);\n dialog.top_message = lastMessage.getId();\n if (!isBroadcast) {\n dialog.last_message_date = lastMessage.messageOwner.date;\n changed = true;\n }\n dialogMessage.put(lastMessage.getId(), lastMessage);\n }\n }\n\n if (changed) {\n dialogsServerOnly.clear();\n Collections.sort(dialogs, new Comparator<TLRPC.TL_dialog>() {\n @Override\n public int compare(TLRPC.TL_dialog tl_dialog, TLRPC.TL_dialog tl_dialog2) {\n if (tl_dialog.unread_count > 0 && tl_dialog2.unread_count <= 0) {\n return -1;\n } else if (tl_dialog.unread_count <= 0 && tl_dialog2.unread_count > 0) {\n return 1;\n } else {\n if (tl_dialog.last_message_date == tl_dialog2.last_message_date) {\n return 0;\n } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) {\n return 1;\n } else {\n return -1;\n }\n }\n }\n });\n for (TLRPC.TL_dialog d : dialogs) {\n int high_id = (int)(d.id >> 32);\n if ((int)d.id != 0 && high_id != 1) {\n dialogsServerOnly.add(d);\n }\n }\n }\n }\n\n public void reloadDialogs() {\n new Thread(new Runnable() {\n @Override\n public void run() {\n TLRPC.TL_messages_getDialogs req = new TLRPC.TL_messages_getDialogs();\n req.offset = 0;\n req.max_id = 0;\n req.limit = 100;\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n if (response instanceof TLRPC.TL_messages_dialogs) {\n TLRPC.TL_messages_dialogs resp = (TLRPC.TL_messages_dialogs) response;\n MessagesController.getInstance().processDialogsUpdate(resp,null);\n MessagesStorage.getInstance().putDialogs(resp);\n } else {\n if (response instanceof TLRPC.TL_messages_dialogsSlice) {\n TLRPC.TL_messages_dialogsSlice resp = (TLRPC.TL_messages_dialogsSlice) response;\n reloadDialogInternal(1);\n }\n }\n }\n }\n });\n }\n });\n\n }\n\n private void reloadDialogInternal(final int numLlamada) {\n new Thread(new Runnable() {\n @Override\n public void run() {\n TLRPC.TL_messages_getDialogs req = new TLRPC.TL_messages_getDialogs();\n req.offset = 100*numLlamada;\n req.max_id = 0;\n req.limit = 100;\n ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {\n @Override\n public void run(TLObject response, TLRPC.TL_error error) {\n if (error == null) {\n if (response instanceof TLRPC.TL_messages_dialogs) {\n TLRPC.TL_messages_dialogs resp = (TLRPC.TL_messages_dialogs) response;\n processDialogsUpdate(resp, new ArrayList<TLRPC.EncryptedChat>());\n } else {\n if (response instanceof TLRPC.TL_messages_dialogsSlice) {\n TLRPC.TL_messages_dialogsSlice resp = (TLRPC.TL_messages_dialogsSlice) response;\n TLRPC.TL_messages_dialogs dialogs = new TLRPC.TL_messages_dialogs();\n dialogs.chats = resp.chats;\n dialogs.messages = resp.messages;\n dialogs.users = resp.users;\n dialogs.dialogs = resp.dialogs;\n dialogs.count = resp.count;\n processDialogsUpdate(dialogs, new ArrayList<TLRPC.EncryptedChat>());\n MessagesStorage.getInstance().putDialogs(dialogs);\n reloadDialogInternal(numLlamada+1);\n }\n }\n }\n }\n });\n }\n });\n }\n\n public void checkDialogsRead() {\n new Thread(new Runnable() {\n\n @Override\n public void run() {\n AndroidUtilities.runOnUIThread(new Runnable() {\n @Override\n public void run() {\n for(TLRPC.TL_dialog dialog : MessagesController.getInstance().dialogs) {\n if (dialog.unread_count > 0) {\n MessageObject message = MessagesController.getInstance().dialogMessage.get(dialog.top_message);\n if (message == null) {\n continue;\n }\n if (message.isFromMe()) {\n if (!message.messageText.toString().contains(\"#tsfBot\")) {\n dialog.unread_count = 0;\n }\n }\n }\n }\n NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesRead);\n }\n });\n }\n });\n }\n}", "public class ActionBar extends FrameLayout {\n\n public static class ActionBarMenuOnItemClick {\n public void onItemClick(int id) {\n\n }\n\n public boolean canOpenMenu() {\n return true;\n }\n }\n\n private FrameLayout titleFrameLayout;\n private ImageView backButtonImageView;\n private TextView titleTextView;\n private TextView subTitleTextView;\n private View actionModeTop;\n private ActionBarMenu menu;\n private ActionBarMenu actionMode;\n private boolean occupyStatusBar = Build.VERSION.SDK_INT >= 21;\n\n private boolean allowOverlayTitle;\n private CharSequence lastTitle;\n private boolean castShadows = true;\n\n protected boolean isSearchFieldVisible;\n protected int itemsBackgroundResourceId;\n private boolean isBackOverlayVisible;\n protected BaseFragment parentFragment;\n public ActionBarMenuOnItemClick actionBarMenuOnItemClick;\n private int extraHeight;\n\n public ActionBar(Context context) {\n super(context);\n titleFrameLayout = new FrameLayout(context);\n addView(titleFrameLayout);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)titleFrameLayout.getLayoutParams();\n layoutParams.width = LayoutParams.WRAP_CONTENT;\n layoutParams.height = LayoutParams.FILL_PARENT;\n layoutParams.gravity = Gravity.TOP | Gravity.LEFT;\n titleFrameLayout.setLayoutParams(layoutParams);\n titleFrameLayout.setPadding(0, 0, AndroidUtilities.dp(4), 0);\n titleFrameLayout.setEnabled(false);\n }\n\n private void positionBackImage(int height) {\n if (backButtonImageView != null) {\n LayoutParams layoutParams = (LayoutParams)backButtonImageView.getLayoutParams();\n layoutParams.width = AndroidUtilities.dp(54);\n layoutParams.height = height;\n layoutParams.gravity = Gravity.TOP | Gravity.LEFT;\n backButtonImageView.setLayoutParams(layoutParams);\n }\n }\n\n private void positionTitle(int width, int height) {\n int offset = AndroidUtilities.dp(2);\n if (!AndroidUtilities.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {\n offset = AndroidUtilities.dp(1);\n }\n int maxTextWidth = 0;\n\n LayoutParams layoutParams = null;\n\n if (titleTextView != null && titleTextView.getVisibility() == VISIBLE) {\n if (!AndroidUtilities.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {\n titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);\n } else {\n titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);\n }\n\n layoutParams = (LayoutParams) titleTextView.getLayoutParams();\n layoutParams.width = LayoutParams.WRAP_CONTENT;\n layoutParams.height = LayoutParams.WRAP_CONTENT;\n layoutParams.gravity = Gravity.TOP | Gravity.LEFT;\n titleTextView.setLayoutParams(layoutParams);\n titleTextView.measure(width, height);\n maxTextWidth = titleTextView.getMeasuredWidth();\n }\n if (subTitleTextView != null && subTitleTextView.getVisibility() == VISIBLE) {\n if (!AndroidUtilities.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {\n subTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);\n } else {\n subTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);\n }\n\n layoutParams = (LayoutParams) subTitleTextView.getLayoutParams();\n layoutParams.width = LayoutParams.WRAP_CONTENT;\n layoutParams.height = LayoutParams.WRAP_CONTENT;\n layoutParams.gravity = Gravity.TOP | Gravity.LEFT;\n subTitleTextView.setLayoutParams(layoutParams);\n subTitleTextView.measure(width, height);\n maxTextWidth = Math.max(maxTextWidth, subTitleTextView.getMeasuredWidth());\n }\n\n int x = 0;\n if (backButtonImageView != null) {\n if (AndroidUtilities.isTablet()) {\n x = AndroidUtilities.dp(80);\n } else {\n x = AndroidUtilities.dp(72);\n }\n } else {\n if (AndroidUtilities.isTablet()) {\n x = AndroidUtilities.dp(26);\n } else {\n x = AndroidUtilities.dp(18);\n }\n }\n\n if (menu != null) {\n maxTextWidth = Math.min(maxTextWidth, width - menu.getMeasuredWidth() - AndroidUtilities.dp(16) - x);\n }\n\n if (titleTextView != null && titleTextView.getVisibility() == VISIBLE) {\n layoutParams = (LayoutParams) titleTextView.getLayoutParams();\n layoutParams.width = LayoutParams.MATCH_PARENT;\n layoutParams.height = titleTextView.getMeasuredHeight();\n int y;\n if (subTitleTextView != null && subTitleTextView.getVisibility() == VISIBLE) {\n y = (height / 2 - titleTextView.getMeasuredHeight()) / 2 + offset;\n } else {\n y = (height - titleTextView.getMeasuredHeight()) / 2 - AndroidUtilities.dp(1);\n }\n layoutParams.setMargins(x, y, 0, 0);\n titleTextView.setLayoutParams(layoutParams);\n }\n if (subTitleTextView != null && subTitleTextView.getVisibility() == VISIBLE) {\n layoutParams = (LayoutParams) subTitleTextView.getLayoutParams();\n layoutParams.width = LayoutParams.MATCH_PARENT;\n layoutParams.height = subTitleTextView.getMeasuredHeight();\n layoutParams.setMargins(x, height / 2 + (height / 2 - subTitleTextView.getMeasuredHeight()) / 2 - offset, 0, 0);\n subTitleTextView.setLayoutParams(layoutParams);\n }\n\n MarginLayoutParams layoutParams1 = (MarginLayoutParams) titleFrameLayout.getLayoutParams();\n layoutParams1.width = x + maxTextWidth + (isSearchFieldVisible ? 0 : AndroidUtilities.dp(6));\n layoutParams1.topMargin = occupyStatusBar ? AndroidUtilities.statusBarHeight : 0;\n titleFrameLayout.setLayoutParams(layoutParams1);\n }\n\n public void positionMenu(int width, int height) {\n if (menu == null) {\n return;\n }\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)menu.getLayoutParams();\n layoutParams.width = isSearchFieldVisible ? LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT;\n layoutParams.height = height;\n layoutParams.leftMargin = isSearchFieldVisible ? AndroidUtilities.dp(AndroidUtilities.isTablet() ? 74 : 66) : 0;\n layoutParams.topMargin = occupyStatusBar ? AndroidUtilities.statusBarHeight : 0;\n menu.setLayoutParams(layoutParams);\n menu.measure(width, height);\n }\n\n private void createBackButtonImage() {\n if (backButtonImageView != null) {\n return;\n }\n backButtonImageView = new ImageView(getContext());\n titleFrameLayout.addView(backButtonImageView);\n backButtonImageView.setScaleType(ImageView.ScaleType.CENTER);\n backButtonImageView.setBackgroundResource(itemsBackgroundResourceId);\n backButtonImageView.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View v) {\n if (isSearchFieldVisible) {\n closeSearchField();\n return;\n }\n if (actionBarMenuOnItemClick != null) {\n actionBarMenuOnItemClick.onItemClick(-1);\n }\n }\n });\n }\n\n public void setBackButtonDrawable(Drawable drawable) {\n if (backButtonImageView == null) {\n createBackButtonImage();\n }\n backButtonImageView.setImageDrawable(drawable);\n }\n\n public void setBackButtonImage(int resource) {\n if (backButtonImageView == null) {\n createBackButtonImage();\n }\n backButtonImageView.setImageResource(resource);\n }\n\n private void createSubtitleTextView() {\n if (subTitleTextView != null) {\n return;\n }\n subTitleTextView = new TextView(getContext());\n titleFrameLayout.addView(subTitleTextView);\n subTitleTextView.setGravity(Gravity.LEFT);\n subTitleTextView.setTextColor(0xffd7e8f7);\n subTitleTextView.setSingleLine(true);\n subTitleTextView.setLines(1);\n subTitleTextView.setMaxLines(1);\n subTitleTextView.setEllipsize(TextUtils.TruncateAt.END);\n }\n\n public void setSubtitle(CharSequence value) {\n if (value != null && subTitleTextView == null) {\n createSubtitleTextView();\n }\n if (subTitleTextView != null) {\n subTitleTextView.setVisibility(value != null && !isSearchFieldVisible ? VISIBLE : GONE);\n subTitleTextView.setText(value);\n positionTitle(getMeasuredWidth(), getMeasuredHeight());\n }\n }\n\n public void setSubTitleIcon(int resourceId, Drawable drawable, int padding) {\n if ((resourceId != 0 || drawable != null) && subTitleTextView == null) {\n createSubtitleTextView();\n positionTitle(getMeasuredWidth(), getMeasuredHeight());\n }\n if (subTitleTextView != null) {\n if (drawable != null) {\n subTitleTextView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);\n } else {\n subTitleTextView.setCompoundDrawablesWithIntrinsicBounds(resourceId, 0, 0, 0);\n }\n subTitleTextView.setCompoundDrawablePadding(padding);\n }\n }\n\n private void createTitleTextView() {\n if (titleTextView != null) {\n return;\n }\n titleTextView = new TextView(getContext());\n titleTextView.setGravity(Gravity.LEFT);\n titleTextView.setSingleLine(true);\n titleTextView.setLines(1);\n titleTextView.setMaxLines(1);\n titleTextView.setEllipsize(TextUtils.TruncateAt.END);\n titleFrameLayout.addView(titleTextView);\n titleTextView.setTextColor(0xffffffff);\n titleTextView.setTypeface(AndroidUtilities.getTypeface(\"fonts/rmedium.ttf\"));\n }\n\n public void setTitle(CharSequence value) {\n if (value != null && titleTextView == null) {\n createTitleTextView();\n }\n if (titleTextView != null) {\n lastTitle = value;\n titleTextView.setVisibility(value != null && !isSearchFieldVisible ? VISIBLE : GONE);\n titleTextView.setText(value);\n positionTitle(getMeasuredWidth(), getMeasuredHeight());\n }\n }\n\n public void setTitleIcon(int resourceId, int padding) {\n if (resourceId != 0 && titleTextView == null) {\n createTitleTextView();\n positionTitle(getMeasuredWidth(), getMeasuredHeight());\n }\n titleTextView.setCompoundDrawablesWithIntrinsicBounds(resourceId, 0, 0, 0);\n titleTextView.setCompoundDrawablePadding(padding);\n }\n\n public Drawable getSubTitleIcon() {\n return subTitleTextView.getCompoundDrawables()[0];\n }\n\n public CharSequence getTitle() {\n if (titleTextView == null) {\n return null;\n }\n return titleTextView.getText();\n }\n\n public ActionBarMenu createMenu() {\n if (menu != null) {\n return menu;\n }\n menu = new ActionBarMenu(getContext(), this);\n addView(menu);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)menu.getLayoutParams();\n layoutParams.height = LayoutParams.FILL_PARENT;\n layoutParams.width = LayoutParams.WRAP_CONTENT;\n layoutParams.gravity = Gravity.RIGHT;\n menu.setLayoutParams(layoutParams);\n return menu;\n }\n\n public void setActionBarMenuOnItemClick(ActionBarMenuOnItemClick listener) {\n actionBarMenuOnItemClick = listener;\n }\n\n public void setCustomView(int resourceId) {\n LayoutInflater li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n View view = li.inflate(resourceId, null);\n addView(view);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)view.getLayoutParams();\n layoutParams.width = LayoutParams.FILL_PARENT;\n layoutParams.height = LayoutParams.FILL_PARENT;\n layoutParams.topMargin = occupyStatusBar ? AndroidUtilities.statusBarHeight : 0;\n view.setLayoutParams(layoutParams);\n }\n\n public ActionBarMenu createActionMode() {\n if (actionMode != null) {\n return actionMode;\n }\n actionMode = new ActionBarMenu(getContext(), this);\n actionMode.setBackgroundResource(R.drawable.editheader);\n addView(actionMode);\n actionMode.setPadding(0, occupyStatusBar ? AndroidUtilities.statusBarHeight : 0, 0, 0);\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)actionMode.getLayoutParams();\n layoutParams.height = LayoutParams.FILL_PARENT;\n layoutParams.width = LayoutParams.FILL_PARENT;\n layoutParams.gravity = Gravity.RIGHT;\n actionMode.setLayoutParams(layoutParams);\n actionMode.setVisibility(GONE);\n\n if (occupyStatusBar) {\n actionModeTop = new View(getContext());\n actionModeTop.setBackgroundColor(0x99000000);\n addView(actionModeTop);\n layoutParams = (FrameLayout.LayoutParams)actionModeTop.getLayoutParams();\n layoutParams.height = AndroidUtilities.statusBarHeight;\n layoutParams.width = LayoutParams.FILL_PARENT;\n layoutParams.gravity = Gravity.TOP | Gravity.LEFT;\n actionModeTop.setLayoutParams(layoutParams);\n actionModeTop.setVisibility(GONE);\n }\n\n return actionMode;\n }\n\n public void showActionMode() {\n if (actionMode == null) {\n return;\n }\n actionMode.setVisibility(VISIBLE);\n if (occupyStatusBar && actionModeTop != null) {\n actionModeTop.setVisibility(VISIBLE);\n }\n if (titleFrameLayout != null) {\n titleFrameLayout.setVisibility(INVISIBLE);\n }\n if (menu != null) {\n menu.setVisibility(INVISIBLE);\n }\n }\n\n public void hideActionMode() {\n if (actionMode == null) {\n return;\n }\n actionMode.setVisibility(GONE);\n if (occupyStatusBar && actionModeTop != null) {\n actionModeTop.setVisibility(GONE);\n }\n if (titleFrameLayout != null) {\n titleFrameLayout.setVisibility(VISIBLE);\n }\n if (menu != null) {\n menu.setVisibility(VISIBLE);\n }\n }\n\n public boolean isActionModeShowed() {\n return actionMode != null && actionMode.getVisibility() == VISIBLE;\n }\n\n protected void onSearchFieldVisibilityChanged(boolean visible) {\n isSearchFieldVisible = visible;\n if (titleTextView != null) {\n titleTextView.setVisibility(visible ? GONE : VISIBLE);\n }\n if (subTitleTextView != null) {\n subTitleTextView.setVisibility(visible ? GONE : VISIBLE);\n }\n Drawable drawable = backButtonImageView.getDrawable();\n if (drawable != null && drawable instanceof MenuDrawable) {\n ((MenuDrawable)drawable).setRotation(visible ? 1 : 0, true);\n }\n }\n\n public void closeSearchField() {\n if (!isSearchFieldVisible || menu == null) {\n return;\n }\n menu.closeSearchField();\n }\n\n public void openSearchField(String text) {\n if (isSearchFieldVisible || menu == null) {\n return;\n }\n menu.openSearchField(text);\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n int actionBarHeight = AndroidUtilities.getCurrentActionBarHeight();\n positionBackImage(actionBarHeight);\n positionMenu(MeasureSpec.getSize(widthMeasureSpec), actionBarHeight);\n positionTitle(MeasureSpec.getSize(widthMeasureSpec), actionBarHeight);\n actionBarHeight += occupyStatusBar ? AndroidUtilities.statusBarHeight : 0;\n super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(actionBarHeight + extraHeight, MeasureSpec.EXACTLY));\n }\n\n public void onMenuButtonPressed() {\n if (menu != null) {\n menu.onMenuButtonPressed();\n }\n }\n\n protected void onPause() {\n if (menu != null) {\n menu.hideAllPopupMenus();\n }\n }\n\n public void setAllowOverlayTitle(boolean value) {\n allowOverlayTitle = value;\n }\n\n public void setTitleOverlayText(String text) {\n if (!allowOverlayTitle || parentFragment.parentLayout == null) {\n return;\n }\n CharSequence textToSet = text != null ? text : lastTitle;\n if (textToSet != null && titleTextView == null) {\n createTitleTextView();\n }\n if (titleTextView != null) {\n titleTextView.setVisibility(textToSet != null && !isSearchFieldVisible ? VISIBLE : GONE);\n titleTextView.setText(textToSet);\n positionTitle(getMeasuredWidth(), getMeasuredHeight());\n }\n }\n\n public void setExtraHeight(int value, boolean layout) {\n extraHeight = value;\n if (layout) {\n requestLayout();\n }\n }\n\n public int getExtraHeight() {\n return extraHeight;\n }\n\n public void setOccupyStatusBar(boolean value) {\n occupyStatusBar = value;\n if (actionMode != null) {\n actionMode.setPadding(0, occupyStatusBar ? AndroidUtilities.statusBarHeight : 0, 0, 0);\n }\n }\n\n public boolean getOccupyStatusBar() {\n return occupyStatusBar;\n }\n\n public void setItemsBackground(int resourceId) {\n itemsBackgroundResourceId = resourceId;\n if (backButtonImageView != null) {\n backButtonImageView.setBackgroundResource(itemsBackgroundResourceId);\n }\n }\n\n public void setCastShadows(boolean value) {\n castShadows = value;\n }\n\n public boolean getCastShadows() {\n return castShadows;\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n super.onTouchEvent(event);\n return true;\n }\n}", "public class ActionBarMenu extends LinearLayout {\n\n protected ActionBar parentActionBar;\n\n public ActionBarMenu(Context context, ActionBar layer) {\n super(context);\n setOrientation(LinearLayout.HORIZONTAL);\n parentActionBar = layer;\n }\n\n public ActionBarMenu(Context context) {\n super(context);\n }\n\n public ActionBarMenu(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public ActionBarMenu(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n }\n\n public View addItemResource(int id, int resourceId) {\n LayoutInflater li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n View view = li.inflate(resourceId, null);\n view.setTag(id);\n addView(view);\n LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)view.getLayoutParams();\n layoutParams.height = FrameLayout.LayoutParams.FILL_PARENT;\n view.setBackgroundResource(parentActionBar.itemsBackgroundResourceId);\n view.setLayoutParams(layoutParams);\n view.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View view) {\n onItemClick((Integer) view.getTag());\n }\n });\n return view;\n }\n\n public ActionBarMenuItem addItem(int id, Drawable drawable) {\n return addItem(id, 0, parentActionBar.itemsBackgroundResourceId, drawable, AndroidUtilities.dp(48));\n }\n\n public ActionBarMenuItem addItem(int id, int icon) {\n return addItem(id, icon, parentActionBar.itemsBackgroundResourceId);\n }\n\n public ActionBarMenuItem addItem(int id, int icon, int backgroundResource) {\n return addItem(id, icon, backgroundResource, null, AndroidUtilities.dp(48));\n }\n\n public ActionBarMenuItem addItemWithWidth(int id, int icon, int width) {\n return addItem(id, icon, parentActionBar.itemsBackgroundResourceId, null, width);\n }\n\n public ActionBarMenuItem addItem(int id, int icon, int backgroundResource, Drawable drawable, int width) {\n ActionBarMenuItem menuItem = new ActionBarMenuItem(getContext(), this, backgroundResource);\n menuItem.setTag(id);\n if (drawable != null) {\n menuItem.iconView.setImageDrawable(drawable);\n } else {\n menuItem.iconView.setImageResource(icon);\n }\n addView(menuItem);\n LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)menuItem.getLayoutParams();\n layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;\n layoutParams.width = width;\n menuItem.setLayoutParams(layoutParams);\n menuItem.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View view) {\n ActionBarMenuItem item = (ActionBarMenuItem)view;\n if (item.hasSubMenu()) {\n if (parentActionBar.actionBarMenuOnItemClick.canOpenMenu()) {\n item.toggleSubMenu();\n }\n } else if (item.isSearchField()) {\n parentActionBar.onSearchFieldVisibilityChanged(item.toggleSearch());\n } else {\n onItemClick((Integer)view.getTag());\n }\n }\n });\n return menuItem;\n }\n\n public void hideAllPopupMenus() {\n for (int a = 0; a < getChildCount(); a++) {\n View view = getChildAt(a);\n if (view instanceof ActionBarMenuItem) {\n ((ActionBarMenuItem)view).closeSubMenu();\n }\n }\n }\n\n public void onItemClick(int id) {\n if (parentActionBar.actionBarMenuOnItemClick != null) {\n parentActionBar.actionBarMenuOnItemClick.onItemClick(id);\n }\n }\n\n public void clearItems() {\n for (int a = 0; a < getChildCount(); a++) {\n View view = getChildAt(a);\n removeView(view);\n }\n }\n\n public void onMenuButtonPressed() {\n for (int a = 0; a < getChildCount(); a++) {\n View view = getChildAt(a);\n if (view instanceof ActionBarMenuItem) {\n ActionBarMenuItem item = (ActionBarMenuItem)view;\n if (item.hasSubMenu() && item.getVisibility() == VISIBLE) {\n item.toggleSubMenu();\n break;\n }\n }\n }\n }\n\n public void closeSearchField() {\n for (int a = 0; a < getChildCount(); a++) {\n View view = getChildAt(a);\n if (view instanceof ActionBarMenuItem) {\n ActionBarMenuItem item = (ActionBarMenuItem)view;\n if (item.isSearchField()) {\n parentActionBar.onSearchFieldVisibilityChanged(item.toggleSearch());\n break;\n }\n }\n }\n }\n\n public void openSearchField(String text) {\n for (int a = 0; a < getChildCount(); a++) {\n View view = getChildAt(a);\n if (view instanceof ActionBarMenuItem) {\n ActionBarMenuItem item = (ActionBarMenuItem)view;\n if (item.isSearchField()) {\n parentActionBar.onSearchFieldVisibilityChanged(item.toggleSearch());\n item.getSearchField().setText(text);\n item.getSearchField().setSelection(text.length());\n break;\n }\n }\n }\n }\n\n public ActionBarMenuItem getItem(int id) {\n View v = findViewWithTag(id);\n if (v instanceof ActionBarMenuItem) {\n return (ActionBarMenuItem)v;\n }\n return null;\n }\n}", "public class BaseFragment {\n private boolean isFinished = false;\n protected AlertDialog visibleDialog = null;\n\n protected View fragmentView;\n protected ActionBarLayout parentLayout;\n protected ActionBar actionBar;\n protected int classGuid = 0;\n protected Bundle arguments;\n protected boolean swipeBackEnabled = true;\n\n public BaseFragment() {\n classGuid = ConnectionsManager.getInstance().generateClassGuid();\n }\n\n public BaseFragment(Bundle args) {\n arguments = args;\n classGuid = ConnectionsManager.getInstance().generateClassGuid();\n }\n\n public View createView(LayoutInflater inflater) {\n return null;\n }\n\n public Bundle getArguments() {\n return arguments;\n }\n\n protected void setParentLayout(ActionBarLayout layout) {\n if (parentLayout != layout) {\n parentLayout = layout;\n if (fragmentView != null) {\n ViewGroup parent = (ViewGroup) fragmentView.getParent();\n if (parent != null) {\n try {\n parent.removeView(fragmentView);\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n fragmentView = null;\n }\n if (actionBar != null) {\n ViewGroup parent = (ViewGroup) actionBar.getParent();\n if (parent != null) {\n try {\n parent.removeView(actionBar);\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n }\n if (parentLayout != null) {\n actionBar = new ActionBar(parentLayout.getContext());\n actionBar.parentFragment = this;\n actionBar.setBackgroundColor(0xff54759e);\n actionBar.setItemsBackground(R.drawable.bar_selector);\n }\n }\n }\n\n public void finishFragment() {\n finishFragment(true);\n }\n\n public void finishFragment(boolean animated) {\n if (isFinished || parentLayout == null) {\n return;\n }\n parentLayout.closeLastFragment(animated);\n }\n\n public void removeSelfFromStack() {\n if (isFinished || parentLayout == null) {\n return;\n }\n parentLayout.removeFragmentFromStack(this);\n }\n\n public boolean onFragmentCreate() {\n return true;\n }\n\n public void onFragmentDestroy() {\n ConnectionsManager.getInstance().cancelRpcsForClassGuid(classGuid);\n isFinished = true;\n if (actionBar != null) {\n actionBar.setEnabled(false);\n }\n }\n\n public void onResume() {\n\n }\n\n public void onPause() {\n if (actionBar != null) {\n actionBar.onPause();\n }\n try {\n if (visibleDialog != null && visibleDialog.isShowing()) {\n visibleDialog.dismiss();\n visibleDialog = null;\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n\n public void onConfigurationChanged(android.content.res.Configuration newConfig) {\n\n }\n\n public boolean onBackPressed() {\n return true;\n }\n\n public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {\n\n }\n\n public void saveSelfArgs(Bundle args) {\n\n }\n\n public void restoreSelfArgs(Bundle args) {\n\n }\n\n public boolean presentFragment(BaseFragment fragment) {\n return parentLayout != null && parentLayout.presentFragment(fragment);\n }\n\n public boolean presentFragment(BaseFragment fragment, boolean removeLast) {\n return parentLayout != null && parentLayout.presentFragment(fragment, removeLast);\n }\n\n public boolean presentFragment(BaseFragment fragment, boolean removeLast, boolean forceWithoutAnimation) {\n return parentLayout != null && parentLayout.presentFragment(fragment, removeLast, forceWithoutAnimation, true);\n }\n\n public Activity getParentActivity() {\n if (parentLayout != null) {\n return parentLayout.parentActivity;\n }\n return null;\n }\n\n public void startActivityForResult(final Intent intent, final int requestCode) {\n if (parentLayout != null) {\n parentLayout.startActivityForResult(intent, requestCode);\n }\n }\n\n public void onBeginSlide() {\n try {\n if (visibleDialog != null && visibleDialog.isShowing()) {\n visibleDialog.dismiss();\n visibleDialog = null;\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n if (actionBar != null) {\n actionBar.onPause();\n }\n }\n\n public void onOpenAnimationEnd() {\n\n }\n\n public void onLowMemory() {\n\n }\n\n public boolean needAddActionBar() {\n return true;\n }\n\n public void showAlertDialog(AlertDialog.Builder builder) {\n if (parentLayout == null || parentLayout.checkTransitionAnimation() || parentLayout.animationInProgress || parentLayout.startedTracking) {\n return;\n }\n try {\n if (visibleDialog != null) {\n visibleDialog.dismiss();\n visibleDialog = null;\n }\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n try {\n visibleDialog = builder.show();\n visibleDialog.setCanceledOnTouchOutside(true);\n visibleDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {\n @Override\n public void onDismiss(DialogInterface dialog) {\n visibleDialog = null;\n onDialogDismiss();\n }\n });\n } catch (Exception e) {\n FileLog.e(\"tmessages\", e);\n }\n }\n\n protected void onDialogDismiss() {\n\n }\n}" ]
import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.text.InputType; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import org.telegram.android.AndroidUtilities; import org.telegram.android.LocaleController; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.TLRPC; import org.telegram.android.MessagesController; import org.telegram.messenger.R; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.BaseFragment;
/* * This is the source code of Telegram for Android v. 1.3.2. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013. */ package org.telegram.ui; public class ChangeChatNameActivity extends BaseFragment { private EditText firstNameField; private View headerLabelView; private int chat_id; private View doneButton; private final static int done_button = 1; public ChangeChatNameActivity(Bundle args) { super(args); } @Override public boolean onFragmentCreate() { super.onFragmentCreate(); chat_id = getArguments().getInt("chat_id", 0); return true; } @Override public View createView(LayoutInflater inflater) { if (fragmentView == null) { actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(true); actionBar.setTitle(LocaleController.getString("EditName", R.string.EditName)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == done_button) { if (firstNameField.getText().length() != 0) { saveName(); finishFragment(); } } } }); ActionBarMenu menu = actionBar.createMenu(); doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));
TLRPC.Chat currentChat = MessagesController.getInstance().getChat(chat_id);
3
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/models/Episode.java
[ "public class ProfileManager {\n\n public static final String JS_SUBSCRIBED_PODCASTS = \"subscribedPodcasts\";\n public static final String JS_SUBSCRIBED_STATIONS = \"subscribedStations\";\n public static final String JS_RECENT_STATIONS = \"recentStations\";\n\n public static ProfileManager profileManager;\n private IOperationFinishWithDataCallback profileSavedCallback;\n\n\n public static class ProfileUpdateEvent {\n public String updateListType;\n public MediaItem mediaItem;\n public boolean isRemoved;\n\n public ProfileUpdateEvent(String updateListType, MediaItem mediaItem, boolean isRemoved) {\n this.updateListType = updateListType;\n this.mediaItem = mediaItem;\n this.isRemoved = isRemoved;\n }\n }\n\n private ProfileManager() {\n\n }\n\n public synchronized static ProfileManager getInstance() {\n if (profileManager == null) {\n profileManager = new ProfileManager();\n }\n return profileManager;\n }\n\n public void setProfileSavedCallback(IOperationFinishWithDataCallback profileSavedCallback) {\n this.profileSavedCallback = profileSavedCallback;\n }\n\n private ArrayList<Long> getMediaListIds(String mediaType, String listType) {\n SQLiteDatabase database = UpodsApplication.getDatabaseManager().getReadableDatabase();\n String[] args1 = {mediaType, listType};\n ArrayList<Long> ids = new ArrayList<>();\n String table = mediaType.equals(MediaListItem.TYPE_RADIO) ? \"radio_stations\" : \"podcasts\";\n Cursor cursor = database.rawQuery(\"SELECT p.id FROM \" + table + \" as p\\n\" +\n \"LEFT JOIN media_list as ml\\n\" +\n \"ON p.id = ml.media_id\\n\" +\n \"WHERE ml.media_type = ? and ml.list_type = ?\", args1);\n while (cursor.moveToNext()) {\n ids.add(cursor.getLong(cursor.getColumnIndex(\"id\")));\n }\n cursor.close();\n return ids;\n }\n\n private ArrayList<Podcast> getPodcastsForMediaType(String mediaType) {\n SQLiteDatabase database = UpodsApplication.getDatabaseManager().getReadableDatabase();\n ArrayList<Long> ids = getMediaListIds(MediaListItem.TYPE_PODCAST,\n mediaType.equals(MediaListItem.DOWNLOADED) ? MediaListItem.SUBSCRIBED : MediaListItem.DOWNLOADED);\n ArrayList<Podcast> podcasts = new ArrayList<>();\n String[] args2 = {MediaListItem.TYPE_PODCAST, mediaType};\n Cursor cursor = database.rawQuery(\"SELECT p.* FROM podcasts as p\\n\" +\n \"LEFT JOIN media_list as ml\\n\" +\n \"ON p.id = ml.media_id\\n\" +\n \"WHERE ml.media_type = ? and ml.list_type = ? \" +\n \"ORDER BY id DESC\", args2);\n while (cursor.moveToNext()) {\n Podcast podcast = Podcast.withCursor(cursor);\n if (mediaType.equals(MediaListItem.DOWNLOADED)) {\n podcast.isDownloaded = true;\n if (ids.contains(podcast.id)) {\n podcast.isSubscribed = true;\n }\n } else if (mediaType.equals(MediaListItem.SUBSCRIBED)) {\n podcast.isSubscribed = true;\n if (ids.contains(podcast.id)) {\n podcast.isDownloaded = true;\n }\n }\n podcasts.add(podcast);\n }\n cursor.close();\n\n Podcast.syncWithDb(podcasts);\n\n return podcasts;\n }\n\n private ArrayList<RadioItem> getRadioStationsForMediaType(String mediaType) {\n SQLiteDatabase database = UpodsApplication.getDatabaseManager().getReadableDatabase();\n ArrayList<Long> ids = getMediaListIds(MediaListItem.TYPE_RADIO,\n mediaType.equals(MediaListItem.RECENT) ? MediaListItem.SUBSCRIBED : MediaListItem.RECENT);\n ArrayList<RadioItem> radioItems = new ArrayList<>();\n String[] args2 = {MediaListItem.TYPE_RADIO, mediaType};\n\n Cursor cursor = database.rawQuery(\"SELECT r.* FROM radio_stations as r\\n\" +\n \"LEFT JOIN media_list as ml\\n\" +\n \"ON r.id = ml.media_id\\n\" +\n \"WHERE ml.media_type = ? and ml.list_type = ? \" +\n \"ORDER BY id DESC\", args2);\n\n while (cursor.moveToNext()) {\n RadioItem radioItem = RadioItem.withCursor(cursor);\n if (mediaType.equals(MediaListItem.RECENT)) {\n radioItem.isRecent = true;\n if (ids.contains(radioItem.id)) {\n radioItem.isSubscribed = true;\n }\n } else if (mediaType.equals(MediaListItem.SUBSCRIBED)) {\n radioItem.isSubscribed = true;\n if (ids.contains(radioItem.id)) {\n radioItem.isRecent = true;\n }\n }\n radioItems.add(radioItem);\n }\n cursor.close();\n return radioItems;\n }\n\n private void addTrack(MediaItem mediaItem, Track track, String listType) {\n if (mediaItem instanceof Podcast && track instanceof Episode) {\n SQLiteDatabase database = UpodsApplication.getDatabaseManager().getWritableDatabase();\n boolean isNotifyChanges = false;\n Podcast podcast = (Podcast) mediaItem;\n Episode episode = (Episode) track;\n\n //1. Save episode/podcast if needed\n if (!podcast.isExistsInDb) {\n podcast.save();\n }\n if (!episode.isExistsInDb) {\n episode.save(podcast.id);\n }\n\n //2. Add podcast to media_list if needed\n if ((!podcast.isDownloaded && listType.equals(MediaListItem.DOWNLOADED)) ||\n (!podcast.hasNewEpisodes && listType.equals(MediaListItem.NEW))) {\n ContentValues values = new ContentValues();\n values.put(\"media_id\", mediaItem.id);\n values.put(\"media_type\", MediaListItem.TYPE_PODCAST);\n values.put(\"list_type\", listType);\n database.insert(\"media_list\", null, values);\n isNotifyChanges = true;\n }\n\n //3. Create podcasts_episodes_rel\n if ((!episode.isDownloaded && listType.equals(MediaListItem.DOWNLOADED)) ||\n (!episode.isNew && listType.equals(MediaListItem.NEW))) {\n ContentValues values = new ContentValues();\n values.put(\"podcast_id\", podcast.id);\n values.put(\"episode_id\", episode.id);\n values.put(\"type\", listType);\n database.insert(\"podcasts_episodes_rel\", null, values);\n }\n\n //4. Update objects\n if (listType.equals(MediaListItem.DOWNLOADED)) {\n podcast.isDownloaded = true;\n episode.isDownloaded = true;\n if (isNotifyChanges) {\n notifyChanges(new ProfileUpdateEvent(MediaListItem.DOWNLOADED, mediaItem, false));\n }\n } else if (listType.equals(MediaListItem.NEW)) {\n podcast.hasNewEpisodes = true;\n episode.isNew = true;\n if (!Podcast.hasEpisodeWithTitle(podcast, episode)) {\n podcast.getEpisodes().add(episode);\n }\n if (Looper.myLooper() == Looper.getMainLooper()) {\n notifyChanges(new ProfileUpdateEvent(MediaListItem.NEW, mediaItem, false));\n }\n }\n }\n }\n\n private void removeTrack(MediaItem mediaItem, Track track, String listType) {\n if (mediaItem instanceof Podcast && track instanceof Episode) {\n SQLiteDatabase database = UpodsApplication.getDatabaseManager().getWritableDatabase();\n Podcast podcast = (Podcast) mediaItem;\n Episode episode = (Episode) track;\n\n //Remove reletionships -> then remove episode\n String args[] = {String.valueOf(podcast.id), String.valueOf(episode.id), listType};\n database.delete(\"podcasts_episodes_rel\", \"podcast_id = ? AND episode_id = ? AND type = ?\", args);\n\n if (listType.equals(MediaListItem.DOWNLOADED)) {\n File episodeFile = new File(episode.getAudeoUrl());\n episodeFile.delete();\n episode.isDownloaded = false;\n if (!episode.isNew) {\n episode.remove();\n }\n } else if (listType.equals(MediaListItem.NEW)) {\n episode.isNew = false;\n if (!episode.isDownloaded) {\n episode.remove();\n }\n }\n\n if (listType.equals(MediaListItem.DOWNLOADED) && podcast.getDownloadedEpisodsCount() == 0) {\n String args2[] = {String.valueOf(podcast.id), MediaListItem.TYPE_PODCAST, MediaListItem.DOWNLOADED};\n database.delete(\"media_list\", \"media_id = ? AND media_type = ? AND list_type = ?\", args2);\n podcast.isDownloaded = false;\n notifyChanges(new ProfileUpdateEvent(MediaListItem.DOWNLOADED, mediaItem, true));\n } else if (listType.equals(MediaListItem.NEW) && podcast.getNewEpisodsCount() == 0) {\n podcast.hasNewEpisodes = false;\n String args2[] = {String.valueOf(podcast.id), MediaListItem.TYPE_PODCAST, MediaListItem.NEW};\n database.delete(\"media_list\", \"media_id = ? AND media_type = ? AND list_type = ?\", args2);\n }\n\n if (listType.equals(MediaListItem.NEW) && Looper.myLooper() == Looper.getMainLooper()) {\n //If we are in main thread and were changes in count of new episodes -> notify provider\n notifyChanges(new ProfileUpdateEvent(MediaListItem.NEW, mediaItem, false));\n }\n\n }\n }\n\n public ArrayList<Podcast> getDownloadedPodcasts() {\n return getPodcastsForMediaType(MediaListItem.DOWNLOADED);\n }\n\n public ArrayList<Podcast> getSubscribedPodcasts() {\n return getPodcastsForMediaType(MediaListItem.SUBSCRIBED);\n }\n\n public ArrayList<RadioItem> getSubscribedRadioItems() {\n return getRadioStationsForMediaType(MediaListItem.SUBSCRIBED);\n }\n\n public ArrayList<RadioItem> getRecentRadioItems() {\n return getRadioStationsForMediaType(MediaListItem.RECENT);\n }\n\n public int getTrackPosition(Track track) {\n int trackPostion = -1;\n SQLiteDatabase database = UpodsApplication.getDatabaseManager().getReadableDatabase();\n String args[] = {track.getTitle()};\n Cursor cursor = database.rawQuery(\"SELECT position FROM tracks_positions WHERE track_name = ?\", args);\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n trackPostion = cursor.getInt(cursor.getColumnIndex(\"position\"));\n }\n return trackPostion;\n }\n\n public void addSubscribedMediaItem(MediaItem mediaItem) {\n if (!mediaItem.isSubscribed) {\n String mediaType = MediaListItem.TYPE_RADIO;\n if (mediaItem instanceof Podcast) {\n mediaType = MediaListItem.TYPE_PODCAST;\n Podcast podcast = ((Podcast) mediaItem);\n if (!mediaItem.isExistsInDb) {\n podcast.save();\n }\n Feed.removeFeed(podcast.getFeedUrl());\n Feed.saveAsFeed(podcast.getFeedUrl(), podcast.getEpisodes(), true);\n } else if (mediaItem instanceof RadioItem) {\n if (!mediaItem.isExistsInDb) {\n ((RadioItem) mediaItem).save();\n }\n }\n ContentValues values = new ContentValues();\n values.put(\"media_id\", mediaItem.id);\n values.put(\"media_type\", mediaType);\n values.put(\"list_type\", MediaListItem.SUBSCRIBED);\n UpodsApplication.getDatabaseManager().getWritableDatabase().insert(\"media_list\", null, values);\n mediaItem.isSubscribed = true;\n\n if (mediaItem instanceof Podcast && getSubscribedPodcasts().size() == 1) {\n UpodsApplication.setAlarmManagerTasks();\n }\n }\n notifyChanges(new ProfileUpdateEvent(MediaListItem.SUBSCRIBED, mediaItem, false));\n }\n\n public void addRecentMediaItem(MediaItem mediaItem) {\n if (mediaItem instanceof RadioItem) {\n if (!((RadioItem) mediaItem).isRecent) {\n if (!mediaItem.isExistsInDb) {\n ((RadioItem) mediaItem).save();\n }\n ContentValues values = new ContentValues();\n values.put(\"media_id\", mediaItem.id);\n values.put(\"media_type\", MediaListItem.TYPE_RADIO);\n values.put(\"list_type\", MediaListItem.RECENT);\n UpodsApplication.getDatabaseManager().getWritableDatabase().insert(\"media_list\", null, values);\n ((RadioItem) mediaItem).isRecent = true;\n notifyChanges(new ProfileUpdateEvent(MediaListItem.RECENT, mediaItem, false));\n }\n }\n }\n\n public void addNewTrack(MediaItem mediaItem, Track track) {\n addTrack(mediaItem, track, MediaListItem.NEW);\n }\n\n public void addDownloadedTrack(MediaItem mediaItem, Track track) {\n addTrack(mediaItem, track, MediaListItem.DOWNLOADED);\n }\n\n public void saveTrackPosition(Track track, int position) {\n SQLiteDatabase database = UpodsApplication.getDatabaseManager().getWritableDatabase();\n ContentValues values = new ContentValues();\n values.put(\"track_name\", track.getTitle());\n values.put(\"position\", position);\n database.replace(\"tracks_positions\", null, values);\n }\n\n public void removeNewTrack(MediaItem mediaItem, Track track) {\n removeTrack(mediaItem, track, MediaListItem.NEW);\n }\n\n public void removeDownloadedTrack(MediaItem mediaItem, Track track) {\n removeTrack(mediaItem, track, MediaListItem.DOWNLOADED);\n }\n\n public void removeRecentMediaItem(MediaItem mediaItem) {\n if (mediaItem instanceof RadioItem) {\n SQLiteDatabase database = UpodsApplication.getDatabaseManager().getWritableDatabase();\n String args[] = {String.valueOf(mediaItem.id), MediaListItem.TYPE_RADIO, MediaListItem.RECENT};\n database.delete(\"media_list\", \"media_id = ? AND media_type = ? AND list_type = ?\", args);\n ((RadioItem) mediaItem).isRecent = false;\n\n //Remove media item from DB if it doesn't use\n if (!((RadioItem) mediaItem).isSubscribed) {\n String args2[] = {String.valueOf(mediaItem.id)};\n database.delete(\"radio_stations\", \"id = ?\", args2);\n }\n }\n notifyChanges(new ProfileUpdateEvent(MediaListItem.SUBSCRIBED, mediaItem, true));\n }\n\n public void removeSubscribedMediaItem(MediaItem mediaItem) {\n SQLiteDatabase database = UpodsApplication.getDatabaseManager().getWritableDatabase();\n String type = MediaListItem.TYPE_RADIO;\n if (mediaItem instanceof Podcast) {\n type = MediaListItem.TYPE_PODCAST;\n }\n mediaItem.isSubscribed = false;\n String args[] = {String.valueOf(mediaItem.id), type, MediaListItem.SUBSCRIBED};\n database.delete(\"media_list\", \"media_id = ? AND media_type = ? AND list_type = ?\", args);\n\n //Remove media item from DB if it doesn't use\n if (mediaItem instanceof RadioItem && !((RadioItem) mediaItem).isRecent) {\n String args2[] = {String.valueOf(mediaItem.id)};\n database.delete(\"radio_stations\", \"id = ?\", args2);\n } else if (mediaItem instanceof Podcast && !((Podcast) mediaItem).isDownloaded && !((Podcast) mediaItem).hasNewEpisodes) {\n String args2[] = {String.valueOf(mediaItem.id)};\n database.delete(\"podcasts\", \"id = ?\", args2);\n }\n\n notifyChanges(new ProfileUpdateEvent(MediaListItem.SUBSCRIBED, mediaItem, true));\n }\n\n public void notifyChanges(ProfileUpdateEvent updateEvent) {\n if (profileSavedCallback != null) {\n profileSavedCallback.operationFinished(updateEvent);\n }\n }\n\n private void initSubscribedPodcasts(JSONArray jSubscribedPodcasts) {\n try {\n SQLiteDatabase database = UpodsApplication.getDatabaseManager().getWritableDatabase();\n ArrayList<Podcast> subscribedPodcasts = new ArrayList<>();\n for (int i = 0; i < jSubscribedPodcasts.length(); i++) {\n Podcast podcast = new Podcast(jSubscribedPodcasts.getJSONObject(i));\n subscribedPodcasts.add(podcast);\n }\n\n if (subscribedPodcasts.isEmpty()) {\n return;\n }\n\n Podcast.syncWithDb(subscribedPodcasts);\n for (Podcast podcast : subscribedPodcasts) {\n if (!podcast.isSubscribed) {\n addSubscribedMediaItem(podcast);\n }\n }\n ArrayList<String> ids = MediaItem.getIds(subscribedPodcasts);\n if (ids.size() == 0) {\n return;\n }\n ArrayList<String> args = new ArrayList<>();\n args.add(MediaListItem.TYPE_PODCAST);\n args.add(MediaListItem.SUBSCRIBED);\n args.addAll(ids);\n database.delete(\"media_list\", \"media_type = ? AND list_type = ? AND media_id not in (\" + SQLdatabaseManager.makePlaceholders(ids.size()) + \")\",\n args.toArray(new String[args.size()]));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private void initRadioStations(JSONArray jStations, String listType) {\n try {\n SQLiteDatabase database = UpodsApplication.getDatabaseManager().getWritableDatabase();\n ArrayList<RadioItem> radioStations = new ArrayList<>();\n for (int i = 0; i < jStations.length(); i++) {\n RadioItem radioItem = new RadioItem(jStations.getJSONObject(i));\n radioStations.add(radioItem);\n }\n\n if (radioStations.isEmpty()) {\n return;\n }\n\n RadioItem.syncWithDb(radioStations);\n for (RadioItem radioItem : radioStations) {\n if (!radioItem.isSubscribed && listType.equals(MediaListItem.SUBSCRIBED)) {\n addSubscribedMediaItem(radioItem);\n } else if (!radioItem.isRecent && listType.equals(MediaListItem.RECENT)) {\n addRecentMediaItem(radioItem);\n }\n }\n ArrayList<String> ids = MediaItem.getIds(radioStations);\n\n if (ids.size() == 0) {\n return;\n }\n\n ArrayList<String> args = new ArrayList<>();\n args.add(MediaListItem.TYPE_RADIO);\n args.add(listType);\n args.addAll(ids);\n database.delete(\"media_list\", \"media_type = ? AND list_type = ? AND media_id not in (\" + SQLdatabaseManager.makePlaceholders(ids.size()) + \")\",\n args.toArray(new String[args.size()]));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public void readFromJson(JSONObject rootProfile) {\n try {\n //Read from JSON -> syncWithDB -> save all which not exists -> remove all which not in JSON\n // -> UI will be notified inside init... functions\n\n initSubscribedPodcasts(rootProfile.getJSONArray(JS_SUBSCRIBED_PODCASTS));\n initRadioStations(rootProfile.getJSONArray(JS_SUBSCRIBED_STATIONS), MediaListItem.SUBSCRIBED);\n initRadioStations(rootProfile.getJSONArray(JS_RECENT_STATIONS), MediaListItem.RECENT);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n\n public JSONObject getAsJson() {\n JSONObject rootProfile = new JSONObject();\n try {\n rootProfile.put(JS_RECENT_STATIONS, RadioItem.toJsonArray(getRecentRadioItems()));\n rootProfile.put(JS_SUBSCRIBED_STATIONS, RadioItem.toJsonArray(getSubscribedRadioItems()));\n rootProfile.put(JS_SUBSCRIBED_PODCASTS, Podcast.toJsonArray(getSubscribedPodcasts()));\n } catch (JSONException e) {\n e.printStackTrace();\n }\n return rootProfile;\n }\n\n}", "public class UpodsApplication extends Application {\n\n private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302;\n\n private static final String TAG = \"UpodsApplication\";\n private static Context applicationContext;\n private static SQLdatabaseManager databaseManager;\n private static boolean isLoaded;\n\n @Override\n public void onCreate() {\n isLoaded = false;\n applicationContext = getApplicationContext();\n YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY);\n YandexMetrica.enableActivityAutoTracking(this);\n FacebookSdk.sdkInitialize(applicationContext);\n LoginMaster.getInstance().init();\n new Prefs.Builder()\n .setContext(this)\n .setMode(ContextWrapper.MODE_PRIVATE)\n .setPrefsName(getPackageName())\n .setUseDefaultSharedPreference(true).build();\n\n super.onCreate();\n }\n\n /**\n * All resources which can be loaded not in onCreate(), should be load here,\n * this function called while splash screen is active\n */\n public static void initAllResources() {\n if (!isLoaded) {\n databaseManager = new SQLdatabaseManager(applicationContext);\n SettingsManager.getInstace().init();\n Category.initPodcastsCatrgories();\n SimpleCacheManager.getInstance().removeExpiredCache();\n runMainService();\n setAlarmManagerTasks();\n isLoaded = true;\n }\n }\n\n private static void runMainService() {\n applicationContext.startService(new Intent(applicationContext, MainService.class));\n }\n\n public static void setAlarmManagerTasks() {\n setAlarmManagerTasks(applicationContext);\n }\n\n public static void setAlarmManagerTasks(Context context) {\n try {\n if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) {\n return;\n }\n AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n Intent intent = new Intent(context, NetworkTasksService.class);\n intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS);\n PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent,\n PendingIntent.FLAG_UPDATE_CURRENT);\n\n if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) {\n long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME);\n //interval = TimeUnit.MINUTES.toMillis(60);\n alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,\n SystemClock.elapsedRealtime(),\n interval, alarmIntent);\n Logger.printInfo(TAG, \"Alarm managers - Episods check for updates task added\");\n } else {\n alarmIntent.cancel();\n alarmMgr.cancel(alarmIntent);\n Logger.printInfo(TAG, \"Alarm managers - Episods check for updates task canceled\");\n }\n } catch (Exception e) {\n Logger.printInfo(TAG, \"Alarm managers - can't set alarm manager\");\n e.printStackTrace();\n }\n }\n\n @Override\n public void onTerminate() {\n super.onTerminate();\n }\n\n public static Context getContext() {\n return applicationContext;\n }\n\n public static SQLdatabaseManager getDatabaseManager() {\n return databaseManager;\n }\n}", "public class GlobalUtils {\n\n public static boolean safeTitleEquals(String title1, String title2) {\n if (title1 == null || title2 == null) {\n return false;\n }\n //replaceAll(\"[^a-z,A-Z,0-9,.,+,-, ,!,?,_,:,;,=]\", \"\");\n title1 = title1.trim().replace(\"'\",\"\");\n title2 = title2.trim().replace(\"'\",\"\");;\n return title1.equals(title2);\n }\n\n public static String getCurrentDateTimeUS() {\n DateFormat df = new SimpleDateFormat(\"d MMM, HH:mm\", Locale.US);\n String date = df.format(Calendar.getInstance().getTime());\n Logger.printInfo(\"Sync date\", date);\n return date;\n }\n\n public static String parserDateToMonth(String date) {\n try {\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"EEE, dd MMM yyyy hh:mm:ss Z\", Locale.US);\n Date inputDate = dateFormat.parse(date);\n dateFormat = new SimpleDateFormat(\"MMM\\ndd\", Locale.US);\n date = dateFormat.format(inputDate);\n } catch (ParseException e) {\n e.printStackTrace();\n }\n return date;\n }\n\n public static String getCleanFileName(String str) {\n str = str.toLowerCase();\n return str.replaceAll(\"[^a-zA-Z0-9]+\", \"_\");\n }\n\n public static boolean deleteDirectory(File path) {\n if (path.exists()) {\n File[] files = path.listFiles();\n if (files == null) {\n return true;\n }\n for (int i = 0; i < files.length; i++) {\n if (files[i].isDirectory()) {\n deleteDirectory(files[i]);\n } else {\n files[i].delete();\n }\n }\n }\n return (path.delete());\n }\n\n public static boolean isInternetConnected() {\n ConnectivityManager cm = (ConnectivityManager) UpodsApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);\n return cm.getActiveNetworkInfo() != null;\n }\n\n /**\n * Returns a list with all links contained in the input\n */\n public static List<String> extractUrls(String text) {\n String lines[] = text.split(\"\\\\s+\");\n List<String> containedUrls = new ArrayList<String>();\n String urlRegex = \"((https?|ftp|gopher|telnet|file):((//)|(\\\\\\\\))+[\\\\w\\\\d:#@%/;$()~_?\\\\+-=\\\\\\\\\\\\.&]*)\";\n Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);\n\n for (String line : lines) {\n Matcher urlMatcher = pattern.matcher(line);\n while (urlMatcher.find()) {\n containedUrls.add(line.substring(urlMatcher.start(0), urlMatcher.end(0)));\n }\n }\n return containedUrls;\n }\n\n public static boolean isUrlReachable(String urlToCheck) {\n try {\n URL url = new URL(urlToCheck);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setConnectTimeout(1000);\n int code = connection.getResponseCode();\n if (code == 200) {\n return true;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n\n public static void rateApp(Context context) {\n Uri uri = Uri.parse(\"market://details?id=\" + context.getPackageName());\n Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);\n\n goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);\n try {\n context.startActivity(goToMarket);\n } catch (ActivityNotFoundException e) {\n context.startActivity(new Intent(Intent.ACTION_VIEW,\n Uri.parse(\"http://play.google.com/store/apps/details?id=\" + context.getPackageName())));\n }\n }\n\n public static boolean isPackageInstalled(String packagename) {\n PackageManager pm = UpodsApplication.getContext().getPackageManager();\n try {\n pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);\n return true;\n } catch (PackageManager.NameNotFoundException e) {\n return false;\n }\n }\n\n public static String upperCase(String str) {\n StringBuilder rackingSystemSb = new StringBuilder(str.toLowerCase());\n rackingSystemSb.setCharAt(0, Character.toUpperCase(rackingSystemSb.charAt(0)));\n str = rackingSystemSb.toString();\n return str;\n }\n\n}", "public class Logger {\n\n private static boolean isTurnedOn = false;\n\n public static void printInfo(String tag, String text) {\n if (isTurnedOn) {\n Log.i(tag, text);\n }\n }\n\n public static void printInfo(String tag, int text) {\n if (isTurnedOn) {\n Log.i(tag, String.valueOf(text));\n }\n }\n\n public static void printInfo(String tag, boolean text) {\n if (isTurnedOn) {\n Log.i(tag, String.valueOf(text));\n }\n }\n\n\n public static void printError(String tag, String text) {\n if (isTurnedOn) {\n Log.i(tag, text);\n }\n }\n}", "public class MediaUtils {\n\n private static final String LOG_TAG = \"MediaUtils\";\n\n public static String extractMp3FromFile(String m3uUrl) throws IOException, JSONException {\n Request request = new Request.Builder().url(m3uUrl).build();\n String response = BackendManager.getInstance().sendSimpleSynchronicRequest(request);\n List<String> allURls = GlobalUtils.extractUrls(response);\n String mp3Url = allURls.size() > 0 ? allURls.get(0) : \"\";\n Logger.printInfo(LOG_TAG, \"Extracted from file urls: \" + allURls.toString());\n return mp3Url;\n }\n\n public static String formatMsToTimeString(int millis) {\n return String.format(\"%02d:%02d\",\n MILLISECONDS.toMinutes(millis),\n MILLISECONDS.toSeconds(millis) -\n TimeUnit.MINUTES.toSeconds(MILLISECONDS.toMinutes(millis))\n );\n }\n\n public static long timeStringToLong(String timeString) {\n if (timeString.matches(\"^[0-9]{3,5}$\")) {//Time was given in seconds\n return Long.valueOf(timeString) * 1000;\n }\n if (timeString.matches(\"[0-9]{2}:[0-9]{2}\")) {\n timeString = \"00:\" + timeString;\n }\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n Date date = null;\n long ms;\n try {\n date = sdf.parse(\"1970-01-01 \" + timeString);\n ms = date.getTime();\n } catch (ParseException e) {\n ms = FragmentPlayer.DEFAULT_RADIO_DURATIO;\n e.printStackTrace();\n }\n return ms;\n }\n\n public static int calculateNextTrackNumber(Direction direction, int currentTrackNumber, int tracksSize) {\n int changeTo = 0;\n if (direction == Direction.LEFT) {\n changeTo = currentTrackNumber - 1;\n if (changeTo < 0) {\n changeTo = tracksSize - 1;\n }\n } else {\n changeTo = currentTrackNumber + 1;\n if (changeTo >= tracksSize) {\n changeTo = 0;\n }\n }\n return changeTo;\n }\n\n public static boolean isVideoUrl(String link) {\n return link.matches(\".*\\\\.(mpeg|avi|mp4|3gp|webm|mkv|ogg|wma)$\");\n }\n\n public static IOperationFinishCallback getPlayerFailCallback(final Activity activity, final MediaItem playableMediaItem) {\n return new IOperationFinishCallback() {\n @Override\n public void operationFinished() {\n UniversalPlayer.getInstance().releasePlayer();\n StringBuilder mesStringBuilder = new StringBuilder();\n mesStringBuilder.append(activity.getString(R.string.cant_play));\n mesStringBuilder.append(\" \");\n mesStringBuilder.append(playableMediaItem instanceof Podcast\n ? activity.getString(R.string.podcast_small) : activity.getString(R.string.radio_station));\n mesStringBuilder.append(\":( \");\n mesStringBuilder.append(activity.getString(R.string.please_try_later));\n DialogFragmentMessage dialogFragmentMessage = new DialogFragmentMessage();\n dialogFragmentMessage.setMessage(mesStringBuilder.toString());\n dialogFragmentMessage.setTitle(activity.getString(R.string.oops));\n dialogFragmentMessage.setOnOkClicked(new IOperationFinishCallback() {\n @Override\n public void operationFinished() {\n activity.onBackPressed();\n UniversalPlayer.getInstance().releasePlayer();\n }\n });\n ((IFragmentsManager) activity).showDialogFragment(dialogFragmentMessage);\n }\n };\n }\n\n}" ]
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.format.Formatter; import com.chickenkiller.upods2.controllers.app.ProfileManager; import com.chickenkiller.upods2.controllers.app.UpodsApplication; import com.chickenkiller.upods2.utils.GlobalUtils; import com.chickenkiller.upods2.utils.Logger; import com.chickenkiller.upods2.utils.MediaUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList;
package com.chickenkiller.upods2.models; /** * Created by Alon Zilberman on 8/31/15. */ public class Episode extends Track { private static final String TABLE = "episodes"; private static String EPISODE_LOG = "EPISODE"; private String summary; private String length; private String duration; private String date; private String pathOnDisk; //Not in DB public boolean isNew; public boolean isDownloaded; public Episode() { super(); this.summary = ""; this.length = ""; this.duration = ""; this.date = ""; this.pathOnDisk = ""; this.isNew = false; this.isDownloaded = false; } public Episode(JSONObject jsonItem) { this(); try { this.title = jsonItem.has("title") ? jsonItem.getString("title") : ""; this.title = this.title.replace("\n", "").trim(); this.summary = jsonItem.has("summary") ? jsonItem.getString("summary") : ""; this.length = jsonItem.has("length") ? jsonItem.getString("length") : ""; this.duration = jsonItem.has("duration") ? jsonItem.getString("duration") : ""; this.date = jsonItem.has("date") ? jsonItem.getString("date") : ""; this.pathOnDisk = jsonItem.has("pathOnDisk") ? jsonItem.getString("pathOnDisk") : ""; this.audeoUrl = jsonItem.has("audeoUrl") ? jsonItem.getString("audeoUrl") : ""; } catch (JSONException e) {
Logger.printError(EPISODE_LOG, "Can't parse episod from json");
3
iloveeclipse/anyedittools
AnyEditTools/src/de/loskutov/anyedit/actions/compare/CompareWithAction.java
[ "public class AnyEditToolsPlugin extends AbstractUIPlugin {\n\n private static AnyEditToolsPlugin plugin;\n\n private static boolean isSaveHookInitialized;\n\n /**\n * The constructor.\n */\n public AnyEditToolsPlugin() {\n super();\n if(plugin != null) {\n throw new IllegalStateException(\"AnyEditToolsPlugin is a singleton!\");\n }\n plugin = this;\n }\n\n public static String getId(){\n return getDefault().getBundle().getSymbolicName();\n }\n\n /**\n * Returns the shared instance.\n */\n public static AnyEditToolsPlugin getDefault() {\n return plugin;\n }\n\n /**\n * Returns the workspace instance.\n */\n public static Shell getShell() {\n return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell();\n }\n\n public static void errorDialog(String message, Throwable error) {\n Shell shell = getShell();\n if (message == null) {\n message = Messages.error;\n }\n message = message + \" \" + error.getMessage();\n\n getDefault().getLog().log(\n new Status(IStatus.ERROR, getId(), IStatus.OK, message, error));\n\n MessageDialog.openError(shell, Messages.title, message);\n }\n\n /**\n * @param error\n */\n public static void logError(String message, Throwable error) {\n if (message == null) {\n message = error.getMessage();\n if (message == null) {\n message = error.toString();\n }\n }\n getDefault().getLog().log(\n new Status(IStatus.ERROR, getId(), IStatus.OK, message, error));\n }\n\n public static void logInfo(String message) {\n getDefault().getLog().log(\n new Status(IStatus.INFO, getId(), IStatus.OK, message, null));\n }\n\n public static void errorDialog(String message) {\n Shell shell = getShell();\n MessageDialog.openError(shell, Messages.title, message);\n }\n\n /**\n * @param isSaveHookInitialized\n * The isSaveHookInitialized to set.\n */\n public static void setSaveHookInitialized(boolean isSaveHookInitialized) {\n AnyEditToolsPlugin.isSaveHookInitialized = isSaveHookInitialized;\n }\n\n /**\n * @return Returns the isSaveHookInitialized.\n */\n public static boolean isSaveHookInitialized() {\n return isSaveHookInitialized;\n }\n\n}", "public class AnyeditCompareInput extends CompareEditorInput {\n\n\n static class ExclusiveJobRule implements ISchedulingRule {\n\n private final Object id;\n\n public ExclusiveJobRule(Object id) {\n this.id = id;\n }\n\n @Override\n public boolean contains(ISchedulingRule rule) {\n return rule instanceof ExclusiveJobRule && ((ExclusiveJobRule) rule).id == id;\n }\n\n @Override\n public boolean isConflicting(ISchedulingRule rule) {\n return contains(rule);\n }\n\n }\n\n\n // org.eclipse.compare.internal.CompareEditor.CONFIRM_SAVE_PROPERTY;\n private static final String CONFIRM_SAVE_PROPERTY = \"org.eclipse.compare.internal.CONFIRM_SAVE_PROPERTY\";\n private StreamContent left;\n private StreamContent right;\n private Object differences;\n /**\n * allow \"no diff\" result to keep the editor open\n */\n private boolean createNoDiffNode;\n\n public AnyeditCompareInput(StreamContent left, StreamContent right) {\n super(new CompareConfiguration());\n this.left = left;\n this.right = right;\n getCompareConfiguration().setProperty(CONFIRM_SAVE_PROPERTY, Boolean.FALSE);\n }\n\n\n @Override\n public Object getAdapter(Class adapter) {\n if(IFile.class == adapter) {\n Object object = EclipseUtils.getIFile(left, false);\n if(object != null) {\n return object;\n }\n return EclipseUtils.getIFile(right, false);\n }\n return super.getAdapter(adapter);\n }\n\n @Override\n protected Object prepareInput(IProgressMonitor monitor)\n throws InvocationTargetException, InterruptedException {\n if (right == null || left == null) {\n return null;\n }\n try {\n initTitle();\n left.init(this);\n right.init(this);\n Differencer differencer = new Differencer();\n String message = \"Comparing \" + left.getName() + \" with \" + right.getName();\n monitor.beginTask(message, 30);\n IProgressMonitor sub = new SubProgressMonitor(monitor, 10);\n try {\n sub.beginTask(message, 100);\n\n differences = differencer.findDifferences(false, sub, null, null, left, right);\n if(differences == null && createNoDiffNode) {\n differences = new DiffNode(left, right);\n }\n return differences;\n } finally {\n sub.done();\n }\n } catch (OperationCanceledException e) {\n left.dispose();\n right.dispose();\n throw new InterruptedException(e.getMessage());\n } finally {\n monitor.done();\n }\n }\n\n @Override\n public void saveChanges(IProgressMonitor monitor) throws CoreException {\n super.saveChanges(monitor);\n if (differences instanceof DiffNode) {\n try {\n boolean result = commit(monitor, (DiffNode) differences);\n // let the UI re-compare here on changed inputs\n if(result){\n reuseEditor();\n }\n } finally {\n setDirty(false);\n }\n }\n }\n\n @Override\n public Object getCompareResult() {\n Object compareResult = super.getCompareResult();\n if(compareResult == null){\n // dispose???\n }\n return compareResult;\n }\n\n void reuseEditor() {\n UIJob job = new UIJob(\"Updating differences\"){\n @Override\n public IStatus runInUIThread(IProgressMonitor monitor) {\n if(monitor.isCanceled() || left.isDisposed() || right.isDisposed()){\n return Status.CANCEL_STATUS;\n }\n\n // This causes too much flicker:\n // AnyeditCompareInput input = new AnyeditCompareInput(left.recreate(), right\n // .recreate());\n // if(monitor.isCanceled()){\n // input.internalDispose();\n // return Status.CANCEL_STATUS;\n // }\n // CompareUI.reuseCompareEditor(input, (IReusableEditor) getWorkbenchPart());\n\n AnyeditCompareInput input = AnyeditCompareInput.this;\n // allow \"no diff\" result to keep the editor open\n createNoDiffNode = true;\n try {\n StreamContent old_left = left;\n left = old_left.recreate();\n old_left.dispose();\n StreamContent old_right = right;\n right = old_right.recreate();\n old_right.dispose();\n\n\n // calls prepareInput(monitor);\n input.run(monitor);\n if(differences != null){\n CompareViewerSwitchingPane pane = getInputPane();\n if(pane != null){\n Viewer viewer = pane.getViewer();\n if (viewer instanceof TextMergeViewer) {\n viewer.setInput(differences);\n }\n }\n }\n } catch (InterruptedException e) {\n // ignore, we are interrupted\n return Status.CANCEL_STATUS;\n } catch (InvocationTargetException e) {\n AnyEditToolsPlugin.errorDialog(\"Error during diff of \" + getName(), e);\n return Status.CANCEL_STATUS;\n } finally {\n createNoDiffNode = false;\n }\n return Status.OK_STATUS;\n }\n @Override\n public boolean belongsTo(Object family) {\n return AnyeditCompareInput.this == family;\n }\n\n };\n job.setPriority(Job.SHORT);\n job.setUser(true);\n job.setRule(new ExclusiveJobRule(this));\n Job[] jobs = Job.getJobManager().find(this);\n if(jobs.length > 0){\n for (int i = 0; i < jobs.length; i++) {\n jobs[i].cancel();\n }\n }\n jobs = Job.getJobManager().find(this);\n if(jobs.length > 0) {\n job.schedule(1000);\n } else {\n job.schedule(500);\n }\n }\n\n public CompareViewerSwitchingPane getInputPane() {\n try {\n Field field = CompareEditorInput.class.getDeclaredField(\"fContentInputPane\");\n field.setAccessible(true);\n Object object = field.get(this);\n if(object instanceof CompareViewerSwitchingPane) {\n return (CompareViewerSwitchingPane) object;\n }\n } catch (Throwable e) {\n // ignore\n }\n return null;\n }\n\n private boolean commit(IProgressMonitor monitor, ICompareInput diffNode) {\n boolean okLeft = commitNode(monitor, diffNode.getLeft());\n boolean okRight = commitNode(monitor, diffNode.getRight());\n return okLeft || okRight;\n }\n\n private boolean commitNode(IProgressMonitor monitor, ITypedElement element) {\n if(element instanceof StreamContent) {\n StreamContent content = (StreamContent) element;\n if(content.isDirty()) {\n try {\n return content.commitChanges(monitor);\n } catch (CoreException e) {\n AnyEditToolsPlugin.errorDialog(\"Error during save of \" + content.getName(), e);\n }\n }\n }\n return false;\n }\n\n private void initTitle() {\n CompareConfiguration cc = getCompareConfiguration();\n String nameLeft = left.getName();\n String nameRight = right.getName();\n if(nameLeft.equals(nameRight)){\n nameLeft = left.getFullName();\n nameRight = right.getFullName();\n }\n\n cc.setLeftLabel(nameLeft);\n cc.setLeftImage(left.getImage());\n\n cc.setRightLabel(nameRight);\n cc.setRightImage(right.getImage());\n\n cc.setLeftEditable(true);\n cc.setRightEditable(true);\n setTitle(\"Compare (\" + nameLeft + \" - \" + nameRight + \")\");\n }\n\n @Override\n protected void handleDispose() {\n internalDispose();\n super.handleDispose();\n }\n\n\n public void internalDispose() {\n left.dispose();\n right.dispose();\n differences = null;\n }\n\n}", "public class ContentWrapper implements IActionFilter {\n\n /** content type for compare */\n public static final String UNKNOWN_CONTENT_TYPE = ITypedElement.UNKNOWN_TYPE; // XXX ? ITypedElement.TEXT_TYPE;\n\n private final String name;\n private final String extension;\n private IFile ifile;\n private File file;\n private boolean modifiable;\n private ITextSelection selection;\n\n public ContentWrapper(String name, String fileExtension, AbstractEditor editor) {\n super();\n this.name = name;\n if (editor != null) {\n this.selection = editor.getSelection();\n this.ifile = editor.getIFile();\n this.file = editor.getFile();\n } else {\n this.selection = null;\n }\n if(selection != null && selection.getLength() == 0){\n selection = null;\n }\n this.extension = fileExtension == null? UNKNOWN_CONTENT_TYPE : fileExtension;\n this.modifiable = true;\n }\n\n public ContentWrapper recreate(){\n ContentWrapper cw = new ContentWrapper(name, extension, null);\n cw.ifile = ifile;\n cw.file = file;\n cw.modifiable = modifiable;\n cw.setSelection(selection);\n return cw;\n }\n\n private ContentWrapper(IPath path) {\n this(path.lastSegment(), path.getFileExtension(), null);\n }\n\n private ContentWrapper(IFile file) {\n this(file.getFullPath());\n this.ifile = file;\n }\n\n private ContentWrapper(File file) {\n this(new Path(file.getAbsolutePath()));\n this.file = file;\n }\n\n public File getFile() {\n if(file == null && ifile != null){\n IPath location = ifile.getLocation();\n if(location != null){\n return location.toFile();\n }\n }\n return file;\n }\n\n public IFile getIFile() {\n return ifile;\n }\n\n public String getName() {\n return name;\n }\n\n public String getFullName(){\n if(ifile != null){\n IPath path = ifile.getLocation();\n if(path != null){\n return path.toOSString();\n }\n } else if(file != null){\n return file.getAbsolutePath();\n }\n return getName();\n }\n\n public String getFileExtension() {\n return extension;\n }\n\n public static ContentWrapper create(AbstractEditor editor1) {\n IDocument document = editor1.getDocument();\n if (document != null) {\n String title = editor1.getTitle();\n String type = editor1.getContentType();\n return new ContentWrapper(title, type, editor1);\n }\n\n IFile ifile = editor1.getIFile();\n if (ifile != null) {\n if (ifile.getLocation() != null) {\n return new ContentWrapper(ifile);\n }\n return new ContentWrapper(ifile.getFullPath().toFile());\n }\n\n File file = editor1.getFile();\n if(file != null){\n return new ContentWrapper(file);\n }\n return null;\n }\n\n public static ContentWrapper create(Object element) {\n if (element instanceof IFile) {\n return new ContentWrapper((IFile) element);\n }\n if (element instanceof File) {\n return new ContentWrapper((File) element);\n }\n if (element instanceof ContentWrapper) {\n return (ContentWrapper) element;\n }\n if (element instanceof AbstractEditor) {\n return create((AbstractEditor) element);\n }\n IFile ifile = EclipseUtils.getIFile(element, true);\n if (ifile != null) {\n return new ContentWrapper(ifile);\n }\n File file = EclipseUtils.getFile(element, true);\n if (file != null) {\n return new ContentWrapper(file);\n }\n ContentWrapper content = EclipseUtils.getAdapter(element, ContentWrapper.class);\n return content;\n }\n\n public void setModifiable(boolean modifiable) {\n this.modifiable = modifiable;\n }\n\n public boolean isModifiable() {\n return modifiable;\n }\n\n @Override\n public boolean testAttribute(Object target, String attrName, String value) {\n if(!(target instanceof ContentWrapper)){\n return false;\n }\n if(\"isModifiable\".equals(attrName)){\n ContentWrapper content = (ContentWrapper) target;\n return Boolean.valueOf(value).booleanValue() == content.isModifiable();\n }\n return false;\n }\n\n public ITextSelection getSelection() {\n return selection;\n }\n public void setSelection(ITextSelection sel) {\n selection = sel;\n }\n\n}", "public class ExternalFileStreamContent extends BufferedContent implements StreamContent,\nIEditableContent, IModificationDate, IEditableContentExtension {\n\n protected boolean dirty;\n private final ContentWrapper content;\n\n\n public ExternalFileStreamContent(ContentWrapper content) {\n super();\n this.content = content;\n }\n\n @Override\n public void setContent(byte[] contents) {\n dirty = true;\n super.setContent(contents);\n }\n\n @Override\n public Image getImage() {\n return CompareUI.getImage(content.getFileExtension());\n }\n\n @Override\n public boolean commitChanges(IProgressMonitor pm) throws CoreException {\n if (!dirty) {\n return true;\n }\n\n byte[] bytes = getContent();\n FileOutputStream fos = null;\n try {\n fos = new FileOutputStream(content.getFile());\n fos.write(bytes);\n return true;\n } catch (IOException e) {\n AnyEditToolsPlugin.errorDialog(\n \"Can't store compare buffer to external file: \" + content.getFile(), e);\n } finally {\n try {\n if (fos != null) {\n fos.close();\n }\n } catch (IOException e) {\n // ignore\n }\n }\n return false;\n }\n\n @Override\n protected InputStream createStream() throws CoreException {\n FileInputStream fis;\n try {\n fis = new FileInputStream(content.getFile());\n return fis;\n } catch (FileNotFoundException e) {\n return null;\n }\n }\n\n @Override\n public boolean isDirty() {\n return dirty;\n }\n\n @Override\n public String getName() {\n return content.getName();\n }\n\n @Override\n public String getFullName() {\n return content.getFullName();\n }\n\n @Override\n public String getType() {\n return content.getFileExtension();\n }\n\n @Override\n public Object[] getChildren() {\n return new StreamContent[0];\n }\n\n @Override\n public boolean isEditable() {\n return true;\n }\n\n @Override\n public ITypedElement replace(ITypedElement dest, ITypedElement src) {\n return null;\n }\n\n @Override\n public long getModificationDate() {\n return content.getFile().lastModified();\n }\n\n @Override\n public boolean isReadOnly() {\n return !content.getFile().canWrite();\n }\n\n @Override\n public IStatus validateEdit(Shell shell) {\n File file = content.getFile();\n if(file.canWrite()) {\n return Status.OK_STATUS;\n }\n FileInfo fi = new FileInfo(file.getAbsolutePath());\n fi.setAttribute(EFS.ATTRIBUTE_READ_ONLY, false);\n try {\n IFileStore store = EFS.getStore(URIUtil.toURI(file.getAbsolutePath()));\n store.putInfo(fi, EFS.SET_ATTRIBUTES, null);\n } catch (CoreException e) {\n AnyEditToolsPlugin.logError(\"Can't make file writable: \" + file, e);\n }\n if(file.canWrite()) {\n return Status.OK_STATUS;\n }\n return Status.CANCEL_STATUS;\n }\n\n @Override\n public void dispose() {\n discardBuffer();\n }\n\n @Override\n public boolean isDisposed() {\n return false;\n }\n\n @Override\n public void init(AnyeditCompareInput input) {\n getContent();\n }\n\n @Override\n public StreamContent recreate() {\n return new ExternalFileStreamContent(content);\n }\n\n @Override\n public Object getAdapter(Class adapter) {\n return null;\n }\n\n @Override\n public void setDirty(boolean dirty) {\n this.dirty = dirty;\n }\n}", "public class FileStreamContent extends ResourceNode implements StreamContent {\n\n private boolean dirty;\n private final ContentWrapper content;\n private EditableSharedDocumentAdapter sharedDocumentAdapter;\n\n public FileStreamContent(ContentWrapper content) {\n super(content.getIFile());\n this.content = content;\n }\n\n @Override\n public void setContent(byte[] contents) {\n dirty = true;\n super.setContent(contents);\n }\n\n @Override\n public String getFullName() {\n return content.getFullName();\n }\n\n @Override\n public boolean isDirty() {\n return dirty;\n }\n\n @Override\n public boolean commitChanges(IProgressMonitor pm) throws CoreException {\n if (!dirty) {\n return true;\n }\n if (sharedDocumentAdapter != null) {\n boolean documentSaved = sharedDocumentAdapter.saveDocument(\n sharedDocumentAdapter.getDocumentKey(this), true, pm);\n if(documentSaved) {\n dirty = false;\n }\n return documentSaved;\n }\n byte[] bytes = getContent();\n ByteArrayInputStream is = new ByteArrayInputStream(bytes);\n IFile file = content.getIFile();\n try {\n if (file.exists()) {\n file.setContents(is, true, true, pm);\n } else {\n file.create(is, true, pm);\n }\n dirty = false;\n } finally {\n try {\n is.close();\n } catch (IOException e) {\n AnyEditToolsPlugin.logError(\n \"Can't save changed compare buffer for file: \" + file, e);\n }\n }\n return true;\n }\n\n @Override\n public void dispose() {\n discardBuffer();\n if (sharedDocumentAdapter != null) {\n sharedDocumentAdapter.releaseBuffer();\n }\n }\n\n @Override\n public boolean isDisposed() {\n return false;\n }\n\n @Override\n public void init(AnyeditCompareInput input) {\n getContent();\n }\n\n @Override\n public StreamContent recreate() {\n return new FileStreamContent(content);\n }\n\n @Override\n public Object getAdapter(Class adapter) {\n\n if (adapter == ISharedDocumentAdapter.class) {\n return getSharedDocumentAdapter();\n }\n if(adapter == IFile.class) {\n return content.getIFile();\n }\n return Platform.getAdapterManager().getAdapter(this, adapter);\n }\n\n /**\n * The code below is copy from org.eclipse.team.internal.ui.synchronize.LocalResourceTypedElement\n * and is required to add full Java editor capabilities (content assist, navigation etc) to the compare editor\n * @return\n */\n private ISharedDocumentAdapter getSharedDocumentAdapter() {\n if (sharedDocumentAdapter == null) {\n sharedDocumentAdapter = new EditableSharedDocumentAdapter(this);\n }\n return sharedDocumentAdapter;\n }\n\n @Override\n public void setDirty(boolean dirty) {\n this.dirty = dirty;\n }\n}", "public interface StreamContent extends ITypedElement, IAdaptable,\nIStructureComparator {\n\n public boolean isDirty();\n\n public void setDirty(boolean dirty);\n\n public boolean commitChanges(IProgressMonitor pm) throws CoreException;\n\n public void dispose();\n\n public void init(AnyeditCompareInput input);\n\n public StreamContent recreate();\n\n boolean isDisposed();\n\n String getFullName();\n}", "public class TextStreamContent implements StreamContent, IStreamContentAccessor, IEditableContent,\nIEditableContentExtension {\n\n private static final String ANY_EDIT_COMPARE = \"AnyEditTools.compare\";\n private final String selectedText;\n private final Position position;\n private final ContentWrapper content;\n private final AbstractEditor editor;\n private byte[] bytes;\n private boolean dirty;\n private final IPartListener2 partListener;\n private DefaultPositionUpdater positionUpdater;\n private IDocumentListener docListener;\n private Annotation lineAnnotation;\n private AnyeditCompareInput compareInput;\n private boolean disposed;\n private EditableSharedDocumentAdapter sharedDocumentAdapter;\n\n /**\n * @param content NOT null\n * @param editor might be null\n */\n public TextStreamContent(ContentWrapper content, AbstractEditor editor) {\n this(content, editor, editor != null ? editor.getSelectedText() : null,\n createPosition(content.getSelection()));\n }\n\n private TextStreamContent(ContentWrapper content, AbstractEditor editor, String selectedText,\n Position position) {\n this.content = content;\n this.editor = editor == null? new AbstractEditor(null) : editor;\n this.selectedText = selectedText;\n this.position = position;\n this.partListener = new PartListener2Impl();\n if(this.editor.getPart() != null) {\n PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().addPartListener(\n partListener);\n IDocument document = this.editor.getDocument();\n // trigger recompare\n if(document != null) {\n docListener = new IDocumentListener(){\n @Override\n public void documentAboutToBeChanged(DocumentEvent event) {\n // noop\n }\n @Override\n public void documentChanged(DocumentEvent event) {\n updateCompareEditor(event);\n }\n };\n document.addDocumentListener(docListener);\n }\n }\n if (selectedText != null && isEditable()) {\n hookOnSelection();\n }\n }\n\n void updateCompareEditor(DocumentEvent event){\n if (event.getText() != null) {\n if ((event.fOffset >= position.offset && event.fOffset < position.offset\n + position.length)\n || (event.fOffset <= position.offset && event.fOffset + event.fLength > position.offset)) {\n compareInput.reuseEditor();\n }\n }\n }\n\n private static Position createPosition(ITextSelection selection) {\n if (selection != null) {\n return new Position(selection.getOffset(), selection.getLength());\n }\n Position pos = new Position(0, 0);\n pos.isDeleted = true;\n return pos;\n }\n\n private void hookOnSelection() {\n try {\n IDocument document = editor.getDocument();\n positionUpdater = new DefaultPositionUpdater(ANY_EDIT_COMPARE);\n document.addPositionCategory(ANY_EDIT_COMPARE);\n document.addPositionUpdater(positionUpdater);\n document.addPosition(ANY_EDIT_COMPARE, position);\n addSelectionAnnotation();\n } catch (BadLocationException e) {\n AnyEditToolsPlugin.logError(\"Can't create position in document\", e);\n } catch (BadPositionCategoryException e) {\n AnyEditToolsPlugin.logError(\"Can't create position in document\", e);\n }\n }\n\n private String getChangedCompareText() {\n if(bytes == null){\n if(sharedDocumentAdapter != null) {\n\n IEditorInput editorInput = sharedDocumentAdapter.getDocumentKey(this);\n if(editorInput == null) {\n return null;\n }\n IDocumentProvider documentProvider = SharedDocumentAdapter.getDocumentProvider(editorInput);\n if(documentProvider != null) {\n IDocument document = documentProvider.getDocument(editorInput);\n if(document != null) {\n return document.get();\n }\n }\n }\n return null;\n }\n // use charset from editor\n String charset = editor.computeEncoding();\n try {\n return new String(bytes, charset);\n } catch (UnsupportedEncodingException e) {\n return new String(bytes);\n }\n }\n\n @Override\n public Image getImage() {\n return CompareUI.getImage(getType());\n }\n\n @Override\n public String getName() {\n return selectedText == null ? content.getName() : \"Selection in \" + content.getName();\n }\n\n @Override\n public String getFullName() {\n return selectedText == null ? content.getFullName() : \"Selection in \" + content.getFullName();\n }\n\n @Override\n public String getType() {\n return content.getFileExtension();\n }\n\n @Override\n public Object[] getChildren() {\n return new StreamContent[0];\n }\n\n @Override\n public boolean commitChanges(IProgressMonitor pm) throws CoreException {\n if (!dirty || !isEditable()) {\n return true;\n }\n IDocument document = editor.getDocument();\n ITextSelection selection = content.getSelection();\n String text = getChangedCompareText();\n if(text == null){\n dirty = false;\n return true;\n }\n dirty = false;\n if (selection == null) {\n boolean sharedSaveOk = false;\n if(sharedDocumentAdapter != null) {\n IEditorInput editorInput = sharedDocumentAdapter.getDocumentKey(this);\n if(editorInput != null) {\n sharedSaveOk = sharedDocumentAdapter.saveDocument(editorInput, true, pm);\n }\n }\n if(!sharedSaveOk){\n document.set(text);\n }\n } else {\n try {\n document.replace(position.getOffset(), position.getLength(), text);\n } catch (BadLocationException e) {\n AnyEditToolsPlugin.logError(\"Can't update text in editor\", e);\n position.isDeleted = true;\n document.removePositionUpdater(positionUpdater);\n removeSelectionAnnotation();\n return false;\n }\n }\n return true;\n }\n\n\n\n @Override\n public boolean isDirty() {\n return dirty;\n }\n\n @Override\n public InputStream getContents() throws CoreException {\n String charset = editor.computeEncoding();\n if (selectedText != null) {\n byte[] bytes2;\n try {\n bytes2 = selectedText.getBytes(charset);\n } catch (UnsupportedEncodingException e) {\n bytes2 = selectedText.getBytes();\n }\n return new ByteArrayInputStream(bytes2);\n }\n String documentContent = editor.getText();\n if (documentContent != null) {\n byte[] bytes2;\n try {\n bytes2 = documentContent.getBytes(charset);\n } catch (UnsupportedEncodingException e) {\n bytes2 = documentContent.getBytes();\n }\n return new ByteArrayInputStream(bytes2);\n }\n return null;\n }\n\n @Override\n public final boolean isEditable() {\n if (selectedText != null) {\n return !position.isDeleted && content.isModifiable() && !editor.isDisposed();\n }\n return content.isModifiable() && editor.getDocument() != null;\n }\n\n @Override\n public ITypedElement replace(ITypedElement dest, ITypedElement src) {\n return null;\n }\n\n @Override\n public void setContent(byte[] newContent) {\n bytes = newContent;\n if(isEditable()) {\n dirty = true;\n }\n }\n\n @Override\n public void dispose() {\n IWorkbench workbench = PlatformUI.getWorkbench();\n if(workbench.isClosing()){\n return;\n }\n IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage();\n page.removePartListener(partListener);\n if (selectedText != null) {\n removeSelectionAnnotation();\n }\n IDocument document = editor.getDocument();\n if(document != null) {\n document.removeDocumentListener(docListener);\n document.removePosition(position);\n document.removePositionUpdater(positionUpdater);\n }\n position.isDeleted = true;\n lineAnnotation = null;\n editor.dispose();\n dirty = false;\n if (sharedDocumentAdapter != null) {\n sharedDocumentAdapter.releaseBuffer();\n }\n disposed = true;\n }\n\n @Override\n public boolean isDisposed() {\n return disposed;\n }\n\n private synchronized void addSelectionAnnotation() {\n if(editor.isDisposed()){\n return;\n }\n IDocumentProvider documentProvider = editor.getDocumentProvider();\n if(documentProvider == null){\n return;\n }\n IEditorInput input = editor.getInput();\n if(input == null){\n return;\n }\n\n IAnnotationModel extension = documentProvider.getAnnotationModel(input);\n if (!(extension instanceof IAnnotationModelExtension)) {\n return;\n }\n lineAnnotation = new Annotation(ANY_EDIT_COMPARE, false,\n \"This text is being compared with anoter one\");\n IAnnotationModelExtension modelExtension = (IAnnotationModelExtension) extension;\n IAnnotationModel model = modelExtension.getAnnotationModel(TextStreamContent.class);\n if (model == null) {\n model = new AnnotationModel();\n }\n model.addAnnotation(lineAnnotation, new Position(position.offset, position.length));\n modelExtension.addAnnotationModel(TextStreamContent.class, model);\n }\n\n private synchronized void removeSelectionAnnotation() {\n if(editor.isDisposed()){\n return;\n }\n IDocumentProvider documentProvider = editor.getDocumentProvider();\n if(documentProvider == null){\n return;\n }\n IEditorInput input = editor.getInput();\n if(input == null){\n return;\n }\n IAnnotationModel extension = documentProvider.getAnnotationModel(input);\n if (!(extension instanceof IAnnotationModelExtension)) {\n return;\n }\n IAnnotationModelExtension modelExtension = (IAnnotationModelExtension) extension;\n IAnnotationModel model = modelExtension.getAnnotationModel(TextStreamContent.class);\n if(model == null){\n return;\n }\n for (Iterator<?> iterator = model.getAnnotationIterator(); iterator.hasNext();) {\n Annotation ann = (Annotation) iterator.next();\n if (lineAnnotation == ann) {\n model.removeAnnotation(ann);\n }\n }\n if (!model.getAnnotationIterator().hasNext()) {\n modelExtension.removeAnnotationModel(TextStreamContent.class);\n }\n }\n\n private final class PartListener2Impl implements IPartListener2 {\n\n @Override\n public void partClosed(IWorkbenchPartReference partRef) {\n if (editor.getPart() == partRef.getPart(false)) {\n\n positionUpdater = null;\n dispose();\n }\n }\n\n @Override\n public void partInputChanged(IWorkbenchPartReference partRef) {\n partClosed(partRef);\n }\n\n @Override\n public void partActivated(IWorkbenchPartReference partRef) {\n // noop\n }\n\n @Override\n public void partBroughtToTop(IWorkbenchPartReference partRef) {\n // noop\n }\n\n @Override\n public void partDeactivated(IWorkbenchPartReference partRef) {\n // noop\n }\n\n @Override\n public void partHidden(IWorkbenchPartReference partRef) {\n // noop\n }\n\n @Override\n public void partOpened(IWorkbenchPartReference partRef) {\n // noop\n }\n\n @Override\n public void partVisible(IWorkbenchPartReference partRef) {\n // noop\n }\n }\n\n @Override\n public void init(AnyeditCompareInput input) {\n this.compareInput = input;\n }\n\n /** create new one with the selection re-created from annotation, if any */\n @Override\n public StreamContent recreate() {\n TextStreamContent tc;\n\n // we should not dispose editor OR should re-create editor here\n if (selectedText == null || position.isDeleted) {\n tc = new TextStreamContent(content, editor.recreate(), null, createPosition(null));\n } else {\n Position pos = new Position(position.getOffset(), position.getLength());\n TextSelection sel = new TextSelection(editor.getDocument(), pos.getOffset(), pos.getLength());\n content.setSelection(sel);\n String text = getText(pos);\n tc = new TextStreamContent(content, editor.recreate(), text, pos);\n }\n return tc;\n }\n\n private String getText(Position pos) {\n String text = null;\n try {\n text = editor.getDocument().get(pos.getOffset(), pos.getLength());\n } catch (BadLocationException e) {\n // ignore, shit happens\n }\n return text;\n }\n\n @Override\n public boolean isReadOnly() {\n return editor.isEditorInputModifiable();\n }\n\n @Override\n public IStatus validateEdit(Shell shell) {\n boolean state = editor.validateEditorInputState();\n if(state){\n return Status.OK_STATUS;\n }\n return Status.CANCEL_STATUS;\n }\n\n @Override\n public Object getAdapter(Class adapter) {\n if(selectedText == null) {\n if (adapter == ISharedDocumentAdapter.class) {\n return getSharedDocumentAdapter();\n }\n }\n if(adapter == IFile.class) {\n return content.getIFile();\n }\n return Platform.getAdapterManager().getAdapter(this, adapter);\n }\n\n /**\n * The code below is copy from org.eclipse.team.internal.ui.synchronize.LocalResourceTypedElement\n * and is required to add full Java editor capabilities (content assist, navigation etc) to the compare editor\n * @return\n */\n private synchronized ISharedDocumentAdapter getSharedDocumentAdapter() {\n if (sharedDocumentAdapter == null) {\n sharedDocumentAdapter = new EditableSharedDocumentAdapter(this);\n }\n return sharedDocumentAdapter;\n }\n\n @Override\n public void setDirty(boolean dirty) {\n this.dirty = dirty;\n }\n}", "public class AbstractEditor implements ITextEditorExtension2 {\n private IWorkbenchPart wPart;\n private boolean multipage;\n\n /**\n * Proxy for different editor types\n */\n public AbstractEditor(final @Nullable IWorkbenchPart editorPart) {\n this();\n wPart = editorPart;\n if(editorPart instanceof FormEditor){\n FormEditor fe = (FormEditor)editorPart;\n wPart = fe.getActiveEditor();\n multipage = true;\n } else if(editorPart instanceof MultiPageEditorPart){\n MultiPageEditorPart me = (MultiPageEditorPart)editorPart;\n // followed is because \"getActiveEditor\" method is protected in\n // MultiPageEditorPart class.\n try {\n Method method = MultiPageEditorPart.class.getDeclaredMethod(\n \"getActiveEditor\", null);\n method.setAccessible(true);\n wPart = (IEditorPart) method.invoke(me, null);\n multipage = true;\n } catch (Exception e) {\n AnyEditToolsPlugin.logError(\"Can't get current page\", e);\n }\n } else if(editorPart!= null\n && !(editorPart instanceof ITextEditor)\n && !(editorPart instanceof IViewPart)) {\n /*\n * added to support different multipage editors which are not extending\n * MultiPageEditorPart, like adobe Flex family editors\n */\n try {\n Method[] declaredMethods = editorPart.getClass().getDeclaredMethods();\n for (int i = 0; i < declaredMethods.length; i++) {\n Method method = declaredMethods[i];\n String methodName = method.getName();\n if((\"getActiveEditor\".equals(methodName)\n // lines below are for Flex 3, above for Flex 2\n || \"getCodeEditor\".equals(methodName)\n || \"getTextEditor\".equals(methodName))\n && method.getParameterTypes().length == 0){\n method.setAccessible(true);\n IEditorPart ePart = (IEditorPart) method.invoke(editorPart, null);\n if(ePart == null) {\n continue;\n }\n wPart = ePart;\n multipage = true;\n break;\n }\n }\n } catch (Exception e) {\n AnyEditToolsPlugin.logError(\"Can't get current page\", e);\n }\n }\n }\n\n private AbstractEditor() {\n super();\n }\n\n public AbstractEditor recreate(){\n AbstractEditor ae = new AbstractEditor();\n ae.wPart = wPart;\n ae.multipage = multipage;\n return ae;\n }\n\n public boolean isMultiPage(){\n return multipage;\n }\n\n /**\n * @return may return null\n */\n @Nullable\n public IDocumentProvider getDocumentProvider() {\n if (wPart == null) {\n return null;\n }\n if (wPart instanceof ITextEditor) {\n return ((ITextEditor) wPart).getDocumentProvider();\n }\n\n IDocumentProvider docProvider = getAdapter(wPart, IDocumentProvider.class);\n return docProvider;\n }\n\n /**\n * @return may return null\n */\n @Nullable\n public IEditorInput getInput() {\n if (!(wPart instanceof IEditorPart)) {\n return null;\n }\n return ((IEditorPart) wPart).getEditorInput();\n }\n\n /**\n * @return may return null\n */\n @Nullable\n public IFile getIFile(){\n if(wPart == null){\n return null;\n }\n IEditorInput input = getInput();\n if(input != null){\n IFile adapter = EclipseUtils.getIFile(input, true);\n if(adapter != null){\n return adapter;\n }\n }\n IFile adapter = EclipseUtils.getIFile(wPart, true);\n return adapter;\n }\n\n @Nullable\n public File getFile(){\n if(wPart == null){\n return null;\n }\n IEditorInput input = getInput();\n if(input != null){\n File adapter = EclipseUtils.getFile(input, true);\n if(adapter != null){\n return adapter;\n }\n }\n File adapter = EclipseUtils.getFile(wPart, true);\n if(adapter != null){\n return adapter;\n }\n ISelectionProvider sp = getSelectionProvider();\n if(sp != null){\n ISelection selection = sp.getSelection();\n if(selection != null){\n adapter = EclipseUtils.getFile(selection, true);\n }\n }\n return adapter;\n }\n\n /**\n * @see ITypedElement#getType()\n */\n @Nullable\n public String getContentType(){\n URI uri = getURI();\n String path;\n if(uri != null) {\n path = uri.toString();\n } else {\n File file = getFile();\n if(file == null) {\n return null;\n }\n path = file.getAbsolutePath();\n }\n int dot = path.lastIndexOf('.') + 1;\n if(dot >= 0){\n return path.substring(dot);\n }\n return path;\n }\n\n @NonNull\n public String getTitle(){\n if(wPart == null){\n return \"\";\n }\n String title = wPart.getTitle();\n return title != null? title : \"\";\n }\n\n /**\n * @return may return null\n */\n @Nullable\n private URI getURI(){\n return EclipseUtils.getURI(getInput());\n }\n\n @NonNull\n public String computeEncoding() {\n IFile file = getIFile();\n if(file != null) {\n try {\n String charset = file.getCharset();\n if(charset != null) {\n return charset;\n }\n } catch (CoreException e) {\n // ignore;\n }\n }\n IDocumentProvider provider = getDocumentProvider();\n if(provider instanceof IStorageDocumentProvider) {\n IStorageDocumentProvider docProvider = (IStorageDocumentProvider) provider;\n String encoding = docProvider.getEncoding(getInput());\n if(encoding != null) {\n return encoding;\n }\n }\n return TextUtil.SYSTEM_CHARSET;\n }\n\n @Nullable\n public ISelectionProvider getSelectionProvider() {\n if (wPart == null) {\n return null;\n }\n if (wPart instanceof ITextEditor) {\n return ((ITextEditor) wPart).getSelectionProvider();\n }\n // PDEMultiPageEditor doesn't implement ITextEditor interface\n ISelectionProvider adapter = getAdapter(wPart, ISelectionProvider.class);\n if(adapter != null){\n return adapter;\n }\n ISelectionProvider sp = wPart.getSite().getSelectionProvider();\n if(sp != null){\n return sp;\n }\n TextViewer viewer = getAdapter(wPart, TextViewer.class);\n if(viewer != null){\n return viewer.getSelectionProvider();\n }\n return null;\n }\n\n @Nullable\n public IDocument getDocument() {\n IEditorInput input = getInput();\n if(input != null) {\n IDocumentProvider provider = getDocumentProvider();\n if (provider != null) {\n return provider.getDocument(input);\n }\n }\n if (wPart instanceof PageBookView) {\n IPage page = ((PageBookView) wPart).getCurrentPage();\n ITextViewer viewer = EditorPropertyTester.getViewer(page);\n if( viewer != null ) {\n return viewer.getDocument();\n }\n }\n if (wPart instanceof IViewPart) {\n ISelectionProvider sp = ((IViewPart) wPart).getViewSite().getSelectionProvider();\n if(sp instanceof ITextViewer){\n return ((ITextViewer) sp).getDocument();\n }\n }\n if(wPart != null){\n TextViewer viewer = getAdapter(wPart, TextViewer.class);\n if(viewer != null){\n return viewer.getDocument();\n }\n }\n return null;\n }\n\n @Nullable\n public ITextSelection getSelection(){\n ISelectionProvider selectionProvider = getSelectionProvider();\n if (selectionProvider == null) {\n return null;\n }\n ISelection selection = selectionProvider.getSelection();\n if (selection instanceof ITextSelection) {\n return (ITextSelection) selection;\n }\n return null;\n }\n\n @Nullable\n public String getSelectedText(){\n ITextSelection selection = getSelection();\n if(selection == null){\n return null;\n }\n String selectedText = selection.getText();\n if(selectedText != null && selectedText.length() > 0) {\n return selectedText;\n }\n return null;\n }\n\n public void selectAndReveal(int lineNumber){\n if (!(wPart instanceof ITextEditor)) {\n return;\n }\n IDocument document = getDocument();\n if(document != null){\n try {\n // line count internally starts with 0, and not with 1 like in GUI\n IRegion lineInfo = document.getLineInformation(lineNumber - 1);\n if(lineInfo != null){\n ((ITextEditor)wPart).selectAndReveal(lineInfo.getOffset(), lineInfo.getLength());\n }\n } catch (BadLocationException e) {\n //ignored because line number may not really exist in document, we guess this...\n }\n }\n }\n\n public boolean isDirty(){\n if (!(wPart instanceof ISaveablePart)) {\n return false;\n }\n return ((ISaveablePart) wPart).isDirty();\n }\n\n @Nullable\n private <T> T getAdapterFromPart(Class<T> clazz){\n if (wPart == null) {\n return null;\n }\n return getAdapter(wPart, clazz);\n }\n\n public void doSave(IProgressMonitor moni){\n if (!(wPart instanceof ISaveablePart)) {\n return;\n }\n ((ISaveablePart) wPart).doSave(moni);\n }\n\n @Override\n public boolean isEditorInputModifiable() {\n if (wPart == null) {\n return false;\n }\n if (wPart instanceof ITextEditorExtension2) {\n return ((ITextEditorExtension2)wPart).isEditorInputModifiable();\n }\n if (wPart instanceof ITextEditorExtension) {\n return !((ITextEditorExtension) wPart).isEditorInputReadOnly();\n }\n if (wPart instanceof ITextEditor) {\n return ((ITextEditor)wPart).isEditable();\n }\n return true;\n }\n\n @Override\n public boolean validateEditorInputState() {\n if (wPart == null) {\n return false;\n }\n if (wPart instanceof ITextEditorExtension2) {\n return ((ITextEditorExtension2)wPart).validateEditorInputState();\n }\n return true;\n }\n\n /**\n * Sets the sequential rewrite mode of the viewer's document.\n */\n public void stopSequentialRewriteMode(DocumentRewriteSession session) {\n IDocument document = getDocument();\n if (document instanceof IDocumentExtension4) {\n IDocumentExtension4 extension= (IDocumentExtension4) document;\n extension.stopRewriteSession(session);\n } else if (document instanceof IDocumentExtension) {\n IDocumentExtension extension= (IDocumentExtension)document;\n extension.stopSequentialRewrite();\n }\n\n IRewriteTarget target = getAdapterFromPart(IRewriteTarget.class);\n if (target != null) {\n target.endCompoundChange();\n target.setRedraw(true);\n }\n }\n\n /**\n * Starts the sequential rewrite mode of the viewer's document.\n * @param normalized <code>true</code> if the rewrite is performed\n * from the start to the end of the document\n */\n @Nullable\n public DocumentRewriteSession startSequentialRewriteMode(boolean normalized) {\n // de/activate listeners etc, prepare multiple replace\n IRewriteTarget target = getAdapterFromPart(IRewriteTarget.class);\n if (target != null) {\n target.setRedraw(false);\n target.beginCompoundChange();\n }\n\n DocumentRewriteSession rewriteSession = null;\n IDocument document = getDocument();\n if (document instanceof IDocumentExtension4) {\n IDocumentExtension4 extension= (IDocumentExtension4) document;\n if (normalized) {\n rewriteSession = extension\n .startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);\n } else {\n rewriteSession = extension\n .startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL);\n }\n } else if (document instanceof IDocumentExtension) {\n IDocumentExtension extension = (IDocumentExtension) document;\n extension.startSequentialRewrite(normalized);\n }\n return rewriteSession;\n }\n\n /**\n * clean reference to wrapped \"real\" editor object\n */\n public void dispose(){\n wPart = null;\n }\n\n public boolean isDisposed(){\n return wPart == null;\n }\n\n @Override\n public int hashCode() {\n IDocumentProvider provider = getDocumentProvider();\n IEditorInput input = getInput();\n int code = 0;\n if(provider != null){\n code += provider.hashCode();\n }\n if(input != null){\n code += input.hashCode();\n }\n if(wPart != null){\n code += wPart.hashCode();\n }\n return code;\n }\n\n @Override\n public boolean equals(Object obj) {\n if(obj == this){\n return true;\n }\n if(!(obj instanceof AbstractEditor)){\n return false;\n }\n AbstractEditor other = (AbstractEditor) obj;\n if(this.wPart != other.wPart){\n return false;\n }\n // now check for multi page stuff\n if(!isMultiPage()){\n return true;\n }\n return this.hashCode() == other.hashCode();\n }\n\n @Nullable\n public IWorkbenchPart getPart() {\n return wPart;\n }\n\n @Nullable\n public String getText() {\n IDocument doc = getDocument();\n return doc != null? doc.get() : null;\n }\n\n}" ]
import org.eclipse.compare.CompareUI; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.handlers.HandlerUtil; import de.loskutov.anyedit.AnyEditToolsPlugin; import de.loskutov.anyedit.compare.AnyeditCompareInput; import de.loskutov.anyedit.compare.ContentWrapper; import de.loskutov.anyedit.compare.ExternalFileStreamContent; import de.loskutov.anyedit.compare.FileStreamContent; import de.loskutov.anyedit.compare.StreamContent; import de.loskutov.anyedit.compare.TextStreamContent; import de.loskutov.anyedit.ui.editor.AbstractEditor;
/******************************************************************************* * Copyright (c) 2009 Andrey Loskutov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributor: Andrey Loskutov - initial API and implementation *******************************************************************************/ package de.loskutov.anyedit.actions.compare; /** * @author Andrey * */ public abstract class CompareWithAction extends AbstractHandler implements IObjectActionDelegate { protected ContentWrapper selectedContent; protected AbstractEditor editor; public CompareWithAction() { super(); editor = new AbstractEditor(null); } @Override public Object execute(final ExecutionEvent event) throws ExecutionException { IWorkbenchPart activePart = HandlerUtil.getActivePart(event); Action dummyAction = new Action(){ @Override public String getId() { return event.getCommand().getId(); } }; setActivePart(dummyAction, activePart); ISelection currentSelection = HandlerUtil.getCurrentSelection(event); selectionChanged(dummyAction, currentSelection); if(dummyAction.isEnabled()) { run(dummyAction); } return null; } @Override public void setActivePart(IAction action, IWorkbenchPart targetPart) { editor = new AbstractEditor(targetPart); } @Override public void run(IAction action) { StreamContent left = createLeftContent(); if (left == null) { return; } try { StreamContent right = createRightContent(left); if (right == null) { left.dispose(); return; } compare(left, right); } catch (CoreException e) { left.dispose(); AnyEditToolsPlugin.logError("Can't perform compare", e); } finally { selectedContent = null; editor = null; } } protected StreamContent createLeftContent() { if (!editor.isDisposed()) { String selectedText = editor.getSelectedText(); if (selectedText != null && selectedText.length() != 0) { return new TextStreamContent(selectedContent, editor); } } return createContent(selectedContent); } protected abstract StreamContent createRightContent(StreamContent left) throws CoreException; protected final StreamContent createContent(ContentWrapper content) { if (content == null) { return null; } /// XXX should we really first check for the document??? if (editor.getDocument() != null) { return new TextStreamContent(content, editor); } return createContentFromFile(content); } protected static final StreamContent createContentFromFile(ContentWrapper content) { if (content == null) { return null; } if (content.getIFile() != null) {
return new FileStreamContent(content);
4
recoilme/freemp
app/src/main/java/org/freemp/droid/player/ActPlayer.java
[ "public class ClsTrack implements Serializable {\n\n private static final long serialVersionUID = 1L;\n private String artist;\n private String title;\n private String album;\n private String composer;\n private int year;\n private int track;\n private int duration;\n private String path;\n private String folder;\n private long lastModified;\n private String group;\n private boolean selected;\n private int albumId;\n\n public ClsTrack(String artist, String title, String album, String composer, int year, int track, int duration,\n String path, String folder, long lastModified, int albumId) {\n this.artist = artist;\n this.title = title;\n this.album = album;\n this.composer = composer;\n this.year = year;\n this.track = track;\n this.duration = duration;\n this.path = path;\n this.folder = folder;\n this.lastModified = lastModified;\n this.group = \"\";\n this.albumId = albumId;\n }\n\n public static ClsTrack newInstance(ClsTrack o) {\n return new ClsTrack(o.getArtist(), o.getTitle(), o.getAlbum(), o.getComposer(), o.getYear(), o.getTrack(), o.getDuration(),\n o.getPath(), o.getFolder(), o.getLastModified(), o.getAlbumId());\n }\n\n @Override\n public String toString() {\n return \"[\" + getGroup() + \",\" + getFolder() + \",\" + getTrack() + \",\" + getArtist() + \",\" + getTitle() + \"]\";\n }\n\n public String getArtist() {\n return artist;\n }\n\n public void setArtist(String artist) {\n this.artist = artist;\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 getAlbum() {\n return album;\n }\n\n public void setAlbum(String album) {\n this.album = album;\n }\n\n public int getDuration() {\n return duration;\n }\n\n public void setDuration(int duration) {\n this.duration = duration;\n }\n\n public String getFolder() {\n return folder;\n }\n\n public void setFolder(String folder) {\n this.folder = folder;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public int getYear() {\n return year;\n }\n\n public void setYear(int year) {\n this.year = year;\n }\n\n public String getComposer() {\n return composer;\n }\n\n public void setComposer(String composer) {\n this.composer = composer;\n }\n\n public int getTrack() {\n return track;\n }\n\n public void setTrack(int track) {\n this.track = track;\n }\n\n public long getLastModified() {\n return lastModified;\n }\n\n public void setLastModified(long lastModified) {\n this.lastModified = lastModified;\n }\n\n public String getGroup() {\n return group;\n }\n\n public void setGroup(String group) {\n this.group = group;\n }\n\n public boolean isSelected() {\n return selected;\n }\n\n public void setSelected(boolean selected) {\n this.selected = selected;\n }\n\n public int getAlbumId() {\n return albumId;\n }\n\n public void setAlbumId(int albumId) {\n this.albumId = albumId;\n }\n}", "public final class Constants {\n public static final int TYPE_MS = 0;\n public static final int TYPE_FS = 1;\n public static final int TYPE_GM = 2;\n public static final int NUM_ITEMS = 3;\n public static final String KEY_TITLE = \"title\";\n public static final boolean DEBUG = true;\n}", "public class FileUtils {\n\n\n public static final String SD_CARD = \"sdCard\";\n public static final String EXTERNAL_SD_CARD = \"externalSdCard\";\n\n\n //public class ExternalStorage {\n\n public static boolean writeObject(String filename, Context context, Object o) {\n boolean success = false;\n try {\n FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);\n ObjectOutputStream os = new ObjectOutputStream(fos);\n os.writeObject(o);\n fos.flush();\n os.close();\n success = true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return success;\n }\n\n public static Object readObject(String filename, Context context) {\n Object t = null;\n try {\n FileInputStream fis = context.openFileInput(filename);\n ObjectInputStream os = new ObjectInputStream(fis);\n t = (Object) os.readObject();\n os.close();\n } catch (Exception e) {\n //e.printStackTrace();\n }\n return t;\n }\n\n /**\n * @return True if the external storage is available. False otherwise.\n */\n public static boolean isAvailable() {\n String state = Environment.getExternalStorageState();\n if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {\n return true;\n }\n return false;\n }\n\n public static String getSdCardPath() {\n return Environment.getExternalStorageDirectory().getPath() + \"/\";\n }\n\n /**\n * @return True if the external storage is writable. False otherwise.\n */\n public static boolean isWritable() {\n String state = Environment.getExternalStorageState();\n if (Environment.MEDIA_MOUNTED.equals(state)) {\n return true;\n }\n return false;\n\n }\n\n /**\n * @return A map of all storage locations available\n */\n public static Map<String, File> getAllStorageLocations() {\n Map<String, File> map = new HashMap<String, File>(10);\n\n List<String> mMounts = new ArrayList<String>(10);\n List<String> mVold = new ArrayList<String>(10);\n mMounts.add(\"/mnt/sdcard\");\n mVold.add(\"/mnt/sdcard\");\n\n try {\n File mountFile = new File(\"/proc/mounts\");\n if (mountFile.exists()) {\n Scanner scanner = new Scanner(mountFile);\n while (scanner.hasNext()) {\n String line = scanner.nextLine();\n if (line.startsWith(\"/dev/block/vold/\")) {\n String[] lineElements = line.split(\" \");\n String element = lineElements[1];\n\n // don't add the default mount path\n // it's already in the list.\n if (!element.equals(\"/mnt/sdcard\"))\n mMounts.add(element);\n }\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n try {\n File voldFile = new File(\"/system/etc/vold.fstab\");\n if (voldFile.exists()) {\n Scanner scanner = new Scanner(voldFile);\n while (scanner.hasNext()) {\n String line = scanner.nextLine();\n if (line.startsWith(\"dev_mount\")) {\n String[] lineElements = line.split(\" \");\n String element = lineElements[2];\n\n if (element.contains(\":\"))\n element = element.substring(0, element.indexOf(\":\"));\n if (!element.equals(\"/mnt/sdcard\"))\n mVold.add(element);\n }\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n\n for (int i = 0; i < mMounts.size(); i++) {\n String mount = mMounts.get(i);\n if (!mVold.contains(mount))\n mMounts.remove(i--);\n }\n mVold.clear();\n\n List<String> mountHash = new ArrayList<String>(10);\n\n for (String mount : mMounts) {\n File root = new File(mount);\n if (root.exists() && root.isDirectory() && root.canWrite()) {\n File[] list = root.listFiles();\n String hash = \"[\";\n if (list != null) {\n for (File f : list) {\n hash += f.getName().hashCode() + \":\" + f.length() + \", \";\n }\n }\n hash += \"]\";\n if (!mountHash.contains(hash)) {\n String key = SD_CARD + \"_\" + map.size();\n if (map.size() == 0) {\n key = SD_CARD;\n } else if (map.size() == 1) {\n key = EXTERNAL_SD_CARD;\n }\n mountHash.add(hash);\n map.put(key, root);\n }\n }\n }\n\n mMounts.clear();\n\n if (map.isEmpty()) {\n map.put(SD_CARD, Environment.getExternalStorageDirectory());\n }\n return map;\n }\n\n // copied from MediaProvider\n public static boolean ensureFileExists(String path) {\n File file = new File(path);\n if (file.exists()) {\n return true;\n } else {\n // we will not attempt to create the first directory in the path\n // (for example, do not create /sdcard if the SD card is not mounted)\n int secondSlash = path.indexOf('/', 1);\n if (secondSlash < 1) return false;\n String directoryPath = path.substring(0, secondSlash);\n File directory = new File(directoryPath);\n if (!directory.exists())\n return false;\n file.getParentFile().mkdirs();\n try {\n return file.createNewFile();\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n return false;\n }\n }\n\n public static File getExternalSdCardPath(Context ctx) {\n File sdCardFile = null;\n sdCardFile = ctx.getExternalFilesDir(null);\n if (sdCardFile != null) {\n int andr = sdCardFile.getAbsolutePath().indexOf(\"Android\");\n if (andr == -1) {\n andr = sdCardFile.getAbsolutePath().indexOf(\"android\");\n }\n if (andr > 0) {\n String path = sdCardFile.getAbsolutePath().substring(0, andr);\n sdCardFile = new File(path);\n }\n }\n return sdCardFile;\n /*\n String path = null;\n File sdCardFile = null;\n List<String> sdCardPossiblePath = Arrays.asList(\"external_sd\", \"ext_sd\", \"external\", \"extSdCard\", \"sdcard2\", \"sdcard1\", \"external1\");\n for (String sdPath : sdCardPossiblePath) {\n File file = new File(\"/mnt/\", sdPath);\n if (file.isDirectory()) {\n path = file.getAbsolutePath();\n }\n }\n if (path != null) {\n sdCardFile = new File(path);\n }\n return sdCardFile;\n */\n }\n\n public static <T> T[] concatenate(T[] A, T[] B) {\n int aLen = A.length;\n int bLen = B.length;\n\n @SuppressWarnings(\"unchecked\")\n T[] C = (T[]) Array.newInstance(A.getClass().getComponentType(), aLen + bLen);\n System.arraycopy(A, 0, C, 0, aLen);\n System.arraycopy(B, 0, C, aLen, bLen);\n\n return C;\n }\n}", "public class MediaUtils {\n\n public static final Uri sArtworkUri = Uri.parse(\"content://media/external/audio/albumart\");\n public static final String ALBUM_FOLDER = \"albumthumbs\";\n private static final BitmapFactory.Options sBitmapOptionsCache = new BitmapFactory.Options();\n\n\n // Get album art for specified album. This method will not try to\n // fall back to getting empty_artwork directly from the file, nor will\n // it attempt to repair the database.\n public static Bitmap getArtworkQuick(Context context, ClsTrack track, int w, int h) {\n // NOTE: There is in fact a 1 pixel frame in the ImageView used to\n // display this drawable. Take it into account now, so we don't have to\n // scale later.\n Bitmap b = null;\n if (track == null) return null;\n String path = MediaUtils.getAlbumPath(context.getApplicationContext().getFilesDir().getAbsolutePath(), track);\n if (path != null && new File(path).exists()) {\n File file = new File(path);\n if (file.exists()) {\n b = getBitmap(context, file, null, w, h);\n }\n } else {\n final int album_id = track.getAlbumId();\n if (album_id != 0) {\n Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);\n if (uri != null) {\n b = getBitmap(context, null, uri, w, h);\n } else {\n b = getArtistQuick(context, track, w, h);\n }\n } else {\n b = getArtistQuick(context, track, w, h);\n }\n }\n return b;\n }\n\n public static Bitmap getArtistQuick(Context context, ClsTrack track, int w, int h) {\n // NOTE: There is in fact a 1 pixel frame in the ImageView used to\n // display this drawable. Take it into account now, so we don't have to\n // scale later.\n Bitmap b = null;\n if (track == null) return null;\n String path = MediaUtils.getArtistPath(context.getApplicationContext().getFilesDir().getAbsolutePath(), track);\n if (path != null) {\n File file = new File(path);\n if (file.exists()) {\n b = getBitmap(context, file, null, w, h);\n }\n }\n return b;\n }\n\n public static Bitmap getBitmap(Context context, File file, Uri uri, int w, int h) {\n ParcelFileDescriptor fd = null;\n Bitmap b = null;\n try {\n if (file != null) {\n fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);\n } else {\n ContentResolver res = context.getContentResolver();\n fd = res.openFileDescriptor(uri, \"r\");\n }\n\n int sampleSize = 1;\n\n // Compute the closest power-of-two scale factor\n // and pass that to sBitmapOptionsCache.inSampleSize, which will\n // result in faster decoding and better quality\n sBitmapOptionsCache.inJustDecodeBounds = true;\n BitmapFactory.decodeFileDescriptor(\n fd.getFileDescriptor(), null, sBitmapOptionsCache);\n int nextWidth = sBitmapOptionsCache.outWidth >> 1;\n int nextHeight = sBitmapOptionsCache.outHeight >> 1;\n while (nextWidth > w && nextHeight > h) {\n sampleSize <<= 1;\n nextWidth >>= 1;\n nextHeight >>= 1;\n }\n\n sBitmapOptionsCache.inSampleSize = sampleSize;\n sBitmapOptionsCache.inJustDecodeBounds = false;\n b = BitmapFactory.decodeFileDescriptor(\n fd.getFileDescriptor(), null, sBitmapOptionsCache);//теперь падает тут)\n\n if (b != null) {\n // finally rescale to exactly the size we need\n if (sBitmapOptionsCache.outWidth != w || sBitmapOptionsCache.outHeight != h) {\n Bitmap tmp = Bitmap.createScaledBitmap(b, w, h, true); //тут падало с аут оф мемори\n if (tmp != b) {\n b.recycle();\n }\n b = tmp;\n }\n }\n } catch (Exception e) {\n return null;\n } finally {\n try {\n if (fd != null)\n fd.close();\n } catch (IOException e) {\n }\n }\n return b;\n }\n\n public static void setRingtoneWithCoping(Context context, ClsTrack track) {\n /*\n http://www.stealthcopter.com/blog/2010/01/android-saving-a-sound-file-to-sd-from-resource-and-setting-as-ringtone/\n\n File path = Environment.getExternalStoragePublicDirectory(\n Environment.DIRECTORY_RINGTONES);\n path.mkdirs(); // Ensure the directory exists\n File file = new File(path, track.getPath());\n try {\n OutputStream os = new FileOutputStream(file);\n\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n */\n }\n\n public static void setRingtone(Context context, ClsTrack track) {\n\n ContentValues values = new ContentValues();\n values.put(MediaStore.MediaColumns.DATA, track.getPath());\n values.put(MediaStore.MediaColumns.TITLE, track.getTitle());\n //values.put(MediaStore.MediaColumns.SIZE, 1024*1024);\n values.put(MediaStore.MediaColumns.MIME_TYPE, \"audio/*\");\n values.put(MediaStore.Audio.Media.ARTIST, track.getArtist());\n //values.put(MediaStore.Audio.Media.DURATION, 5000);\n values.put(MediaStore.Audio.Media.IS_RINGTONE, true);\n values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);\n values.put(MediaStore.Audio.Media.IS_ALARM, false);\n values.put(MediaStore.Audio.Media.IS_MUSIC, true);\n\n Uri uri = MediaStore.Audio.Media.getContentUriForPath(track.getPath());\n\n if (uri == null || context.getContentResolver() == null) {\n Toast.makeText(context, context.getString(R.string.error), Toast.LENGTH_SHORT).show();\n return;\n }\n\n\n /*String ringTonePath = uri.toString();\n try {\n RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, uri);\n } catch (Exception e) {\n Toast.makeText(context, context.getString(R.string.error)+e.toString(), Toast.LENGTH_SHORT).show();\n }*/\n\n //TODO check this may be better copy file in ringtone dir before?\n context.getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + \"=\\\"\" + track.getPath() + \"\\\"\", null);\n Uri newUri = context.getContentResolver().insert(uri, values);\n\n if (newUri == null) {\n Toast.makeText(context, context.getString(R.string.error), Toast.LENGTH_SHORT).show();\n } else {\n RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);\n Toast.makeText(context, context.getString(R.string.set_as_ringtone), Toast.LENGTH_SHORT).show();\n }\n\n }\n\n //i steal it from http://www.netmite.com/android/mydroid/packages/apps/Music/src/com/android/music/MusicUtils.java\n //http://www.lastfm.ru/api/show/album.getInfo\n static void setRingtone(Context context, long id) {\n ContentResolver resolver = context.getContentResolver();\n // Set the flag in the database to mark this as a ringtone\n Uri ringUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);\n try {\n ContentValues values = new ContentValues(2);\n values.put(MediaStore.Audio.Media.IS_RINGTONE, \"1\");\n values.put(MediaStore.Audio.Media.IS_ALARM, \"1\");\n resolver.update(ringUri, values, null, null);\n } catch (UnsupportedOperationException ex) {\n // most likely the card just got unmounted\n Log.e(\"e\", \"couldn't set ringtone flag for id \" + id);\n return;\n }\n\n String[] cols = new String[]{\n MediaStore.Audio.Media._ID,\n MediaStore.Audio.Media.DATA,\n MediaStore.Audio.Media.TITLE\n };\n\n String where = MediaStore.Audio.Media._ID + \"=\" + id;\n Cursor cursor = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,\n cols, where, null, null);\n try {\n if (cursor != null && cursor.getCount() == 1) {\n // Set the system setting to make this the current ringtone\n cursor.moveToFirst();\n Settings.System.putString(resolver, Settings.System.RINGTONE, ringUri.toString());\n String message = context.getString(R.string.set_as_ringtone) + cursor.getString(2);\n Toast.makeText(context, message, Toast.LENGTH_SHORT).show();\n }\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n public static Cursor query(Context context, Uri uri, String[] projection,\n String selection, String[] selectionArgs, String sortOrder) {\n try {\n ContentResolver resolver = context.getContentResolver();\n if (resolver == null) {\n return null;\n }\n return resolver.query(uri, projection, selection, selectionArgs, sortOrder);\n } catch (UnsupportedOperationException ex) {\n return null;\n }\n\n }\n\n public static String getAlbumPath(String path, ClsTrack track, boolean withAlbum) {\n final String directoryPath = path + ALBUM_FOLDER;\n File directory = new File(directoryPath);\n boolean success = true;\n if (!directory.exists()) {\n success = directory.mkdirs();\n }\n if (!success) {\n return null;\n } else {\n return directoryPath + \"/\" + StringUtils.getFileName(track, withAlbum) + \".jpg\";\n }\n }\n\n public static String getAlbumPath(String path, ClsTrack track) {\n return getAlbumPath(path, track, true);\n }\n\n public static String getArtistPath(String path, ClsTrack track) {\n return getAlbumPath(path, track, false);\n }\n}", "public class UpdateUtils {\n\n public static final String MESSAGEURL = \"https://github.com/recoilme/freemp/blob/master/message.json?raw=true\";\n private final WeakReference<Activity> activityContainer;\n private Context context;\n private int versionCode;\n private String locale;\n private AQuery aq;\n\n public UpdateUtils(Activity activity) {\n activityContainer = new WeakReference<Activity>(activity);\n aq = new AQuery(activity);\n new Update().execute();\n }\n\n private void buildNotification(String title, String text, PendingIntent pIntent, int id) {\n if (TextUtils.equals(\"\", title) && TextUtils.equals(\"\", text)) {\n return;\n }\n // if you don't use support library, change NotificationCompat on Notification\n Notification noti = new NotificationCompat.Builder(context)\n .setContentTitle(title)\n .setContentText(text)\n .setSmallIcon(R.drawable.freemp)//change this on your freemp\n .setContentIntent(pIntent).build();\n NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);\n // hide the notification after its selected\n noti.flags |= Notification.FLAG_AUTO_CANCEL;\n\n notificationManager.notify(id, noti);\n }\n\n private class Update extends AsyncTask<Void, Void, String> {\n\n @Override\n protected String doInBackground(Void... params) {\n Activity activity = activityContainer.get();\n if (null == activity) {\n return \"\";\n }\n try {\n versionCode = activity.getPackageManager()\n .getPackageInfo(activity.getPackageName(), 0).versionCode;\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n }\n locale = activity.getResources().getConfiguration().locale.toString();//Locale.getDefault().toString();\n AQUtility.debug(\"locale\", locale);\n String response = \"\";\n\n AjaxCallback<String> cb = new AjaxCallback<String>();\n cb.url(MESSAGEURL).type(String.class).timeout(1);\n\n aq.sync(cb);\n\n response = cb.getResult();\n return response;\n }\n\n @Override\n protected void onPostExecute(String result) {\n if (result != null && !TextUtils.equals(\"\", result)) {\n JSONObject jsonResult = null;\n try {\n jsonResult = new JSONObject(result);\n } catch (Exception e) {\n e.printStackTrace();\n return;\n }\n //process notifications if exists\n JSONArray notifications = jsonResult.optJSONArray(\"notifications\");\n if (notifications == null) {\n return;\n }\n Activity activity = activityContainer.get();\n if (null == activity) {\n return;\n }\n context = activity.getApplicationContext();\n if (context == null) {\n return;\n }\n //string with showed messages\n String showedMessages = PreferenceManager.getDefaultSharedPreferences(context).getString(MESSAGEURL, \"\");\n for (int i = 0; i < notifications.length(); i++) {\n JSONObject jsonNotification = notifications.optJSONObject(i);\n\n if (jsonNotification == null) break;\n\n final int version = jsonNotification.optInt(\"version\", -1);\n if (version > 0 && version != versionCode) {\n continue;\n }\n\n final String localeTarget = jsonNotification.optString(\"locale\", \"all\");\n if (!TextUtils.equals(\"all\", localeTarget) && !TextUtils.equals(localeTarget, locale)) {\n continue;\n }\n\n final int id = jsonNotification.optInt(\"id\");\n if (showedMessages.contains(id + \";\")) {\n continue;\n } else {\n showedMessages += id + \";\";\n PreferenceManager.getDefaultSharedPreferences(context).edit().putString(MESSAGEURL, showedMessages).commit();\n\n Intent intent = null;\n if (!TextUtils.equals(\"\", jsonNotification.optString(\"action\", \"\"))) {\n // if has action add it\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\n jsonNotification.optString(\"action\", \"\")));\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\n } else {\n // if no - just inform\n intent = new Intent(activity, activity.getClass());\n }\n PendingIntent pIntent = PendingIntent.getActivity(context, id, intent, 0);\n\n buildNotification(jsonNotification.optString(\"title\", \"\"), jsonNotification.optString(\"text\", \"\"),\n pIntent, id);\n break;\n }\n }\n\n //process update if exists\n JSONObject update = jsonResult.optJSONObject(\"update\");\n if (update == null) {\n return;\n }\n\n final int version = update.optInt(\"version\", -1);\n if (version < 0 || version <= versionCode) {\n return;\n } else {\n //need update\n String url = update.optString(\"file\");\n if (!TextUtils.equals(\"\", url)) {\n //new Download(update.optString(\"title\"),update.optString(\"text\"),version).execute(new String[]{url});\n final String title = update.optString(\"title\");\n final String text = update.optString(\"text\");\n final int id = version;\n\n final String path = Environment.getExternalStorageDirectory() + \"/\" + id + \".apk\";\n File file = new File(path);\n\n aq.download(url, file, new AjaxCallback<File>() {\n\n public void callback(String url, File file, AjaxStatus status) {\n\n if (file != null) {\n Activity activity = activityContainer.get();\n if (null == activity) {\n return;\n }\n context = activity.getApplicationContext();\n Intent promptInstall = new Intent(Intent.ACTION_VIEW)\n .setDataAndType(Uri.parse(\"file:///\" + result),\n \"application/vnd.android.package-archive\");\n promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n PendingIntent pIntent = PendingIntent.getActivity(context, id, promptInstall, 0);\n buildNotification(title, text, pIntent, id);\n } else {\n //do nothing\n }\n }\n\n });\n }\n }\n }\n }\n\n }\n}", "public class ActPlaylist extends AppCompatActivity {\n\n public int type;\n private Activity activity;\n private AQuery aq;\n private Menu optionsMenu;\n private boolean refreshing = true;\n private AdpPagerAdapter adpPagerAdapter;\n private ViewPager mViewPager;\n private SlidingTabLayout mSlidingTabLayout;\n private String scanDir;\n private DlgChooseDirectory.Result dialogResult;\n\n private FragmentFolders playlistFragment = new FragmentFolders();\n private FragmentAlbums albumsFragment = new FragmentAlbums();\n private FragmentArtists artistsFragment = new FragmentArtists();\n\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getWindow().setFlags(WindowManager.LayoutParams.FLAG_DITHER, WindowManager.LayoutParams.FLAG_DITHER);\n\n setContentView(R.layout.playlist_tabs);\n\n activity = this;\n aq = new AQuery(activity);\n FlurryAgent.onStartSession(activity, getString(R.string.flurry));\n\n ActionBar actionBar = getSupportActionBar();\n actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_bgr));\n actionBar.setDisplayHomeAsUpEnabled(true);\n\n try {\n ViewConfiguration config = ViewConfiguration.get(activity);\n Field menuKeyField = ViewConfiguration.class.getDeclaredField(\"sHasPermanentMenuKey\");\n if (menuKeyField != null) {\n menuKeyField.setAccessible(true);\n menuKeyField.setBoolean(config, false);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n Bundle extras = getIntent().getExtras();\n if (extras == null) {\n return;\n } else {\n type = extras.getInt(\"type\");\n }\n dialogResult = new DlgChooseDirectory.Result() {\n @Override\n public void onChooseDirectory(String dir) {\n\n scanDir = dir;\n PreferenceManager.getDefaultSharedPreferences(activity).edit().putString(\"scanDir\", dir).commit();\n update(true);\n }\n };\n\n mViewPager = (ViewPager) aq.id(R.id.viewpager).getView();\n mViewPager.setOffscreenPageLimit(2);\n adpPagerAdapter = new AdpPagerAdapter(getSupportFragmentManager());\n mViewPager.setAdapter(adpPagerAdapter);\n\n mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);\n mSlidingTabLayout.setViewPager(mViewPager);\n\n mSlidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {\n\n @Override\n public int getIndicatorColor(int position) {\n return\n getResources().getColor(R.color.yellow);\n }\n\n @Override\n public int getDividerColor(int position) {\n return Color.GRAY;\n }\n\n });\n\n }\n\n public void setRefreshing(boolean refreshing) {\n this.refreshing = refreshing;\n }\n\n public void update(boolean refresh) {\n refreshing = true;\n setRefreshActionButtonState();\n Fragment fragment = adpPagerAdapter.getItem(mViewPager.getCurrentItem());\n if (fragment != null) {\n if (fragment instanceof FragmentFolders) {\n playlistFragment.update(activity, Constants.TYPE_FS, refresh);\n }\n if (fragment instanceof FragmentAlbums) {\n albumsFragment.update(activity, Constants.TYPE_MS, refresh);\n }\n if (fragment instanceof FragmentArtists) {\n artistsFragment.update(activity, Constants.TYPE_MS, refresh);\n }\n }\n }\n\n public AdpPlaylist getAdapter() {\n return playlistFragment.adapter;\n /*\n Fragment fragment = adpPagerAdapter.getItem(mViewPager.getCurrentItem());\n if (fragment!=null) {\n if (fragment instanceof FragmentFolders) {\n return playlistFragment.adapter;\n }\n }\n return null;\n */\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n this.optionsMenu = menu;\n MenuInflater inflater = getMenuInflater();\n inflater.inflate(R.menu.menu_playlist, menu);\n if (type == Constants.TYPE_FS) {\n MenuItem item = this.optionsMenu.add(R.string.setup_scandir);\n item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {\n @Override\n public boolean onMenuItemClick(MenuItem item) {\n DlgChooseDirectory dlgChooseDirectory = new DlgChooseDirectory(activity, dialogResult,\n scanDir);\n return true;\n }\n });\n\n\n }\n\n scanDir = PreferenceManager.getDefaultSharedPreferences(activity).getString(\"scanDir\", \"\");\n if (scanDir.equals(\"\")) {\n\n String s = Environment.getExternalStorageDirectory().getAbsolutePath();\n DlgChooseDirectory dlgChooseDirectory = new DlgChooseDirectory(activity, dialogResult,\n s);\n } else {\n update(false);\n }\n\n return super.onCreateOptionsMenu(menu);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n finish();\n return true;\n\n case R.id.menu_refresh:\n\n update(true);\n return true;\n case R.id.menu_save:\n\n save();\n return true;\n case R.id.menu_select_all:\n\n select_all();\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n public void setRefreshActionButtonState() {\n\n if (optionsMenu != null) {\n final MenuItem refreshItem = optionsMenu\n .findItem(R.id.menu_refresh);\n if (refreshItem != null) {\n if (refreshing) {\n MenuItemCompat.setActionView(refreshItem, R.layout.actionbar_progress);\n } else {\n MenuItemCompat.setActionView(refreshItem, null);\n }\n }\n }\n }\n\n public void save() {\n ArrayList<ClsTrack> tracks = null;\n if (getAdapter() != null) {\n tracks = getAdapter().getSelected();\n }\n String fileName = \"tracks\";\n if (tracks == null || tracks.size() == 0) {\n Toast.makeText(activity, getString(R.string.select_pls), Toast.LENGTH_LONG).show();\n return;\n }\n close(tracks);\n }\n\n public void close(ArrayList<ClsTrack> tracks) {\n if (FileUtils.writeObject(\"tracks\", activity, tracks)) {\n setResult(RESULT_OK, null);\n finish();\n }\n }\n\n public void select_all() {\n if (getAdapter() == null) {\n return;\n }\n ArrayList<ClsTrack> tracks = getAdapter().getSelected();\n if (tracks.size() > 0) {\n setSelection(false);\n } else {\n setSelection(true);\n }\n }\n\n public void setSelection(boolean isSelected) {\n if (getAdapter() == null) {\n return;\n }\n getAdapter().notifyDataSetInvalidated();\n for (int j = 0; j < getAdapter().data.size(); j++) {\n ClsArrTrack o = getAdapter().data.get(j);\n ArrayList<ClsTrack> tracks = o.getPlaylists();\n for (int i = 0; i < tracks.size(); i++) {\n ClsTrack t = tracks.get(i);\n t.setSelected(isSelected);\n tracks.set(i, t);\n }\n o.setPlaylists(tracks);\n getAdapter().data.set(j, o);\n }\n getAdapter().invalidate();\n }\n\n public void updateColor() {\n if (getAdapter() == null) {\n return;\n }\n ArrayList<ClsTrack> tmp = getAdapter().getSelected();\n if (tmp == null || tmp.size() == 0) {\n aq.id(R.id.textViewSave).textColor(Color.GRAY);\n } else {\n aq.id(R.id.textViewSave).textColor(getResources().getColor(R.color.yellow));\n }\n\n }\n\n @Override\n public void onDestroy() {\n\n FlurryAgent.onEndSession(activity);\n super.onDestroy();\n\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n }\n\n class AdpPagerAdapter extends FragmentPagerAdapter {\n\n public AdpPagerAdapter(FragmentManager fm) {\n super(fm);\n }\n\n @Override\n public int getCount() {\n return Constants.NUM_ITEMS;\n }\n\n @Override\n public Fragment getItem(int position) {\n switch (position) {\n case 0:\n return playlistFragment;\n case 1:\n return albumsFragment;\n case 2:\n return artistsFragment;\n }\n return null;\n }\n\n @Override\n public CharSequence getPageTitle(int position) {\n switch (position) {\n case 0:\n return getString(R.string.tab_folders);\n case 1:\n return getString(R.string.tab_albums);\n case 2:\n return getString(R.string.tab_artists);\n }\n return \"-\";\n }\n }\n}" ]
import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.format.Time; import android.view.Display; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.androidquery.AQuery; import com.androidquery.util.AQUtility; import com.flurry.android.FlurryAgent; import org.freemp.droid.ClsTrack; import org.freemp.droid.Constants; import org.freemp.droid.FileUtils; import org.freemp.droid.MediaUtils; import org.freemp.droid.R; import org.freemp.droid.UpdateUtils; import org.freemp.droid.playlist.ActPlaylist; import java.util.ArrayList; import java.util.Collections; import java.util.Random;
package org.freemp.droid.player; /** * Created with IntelliJ IDEA. * User: recoilme * Date: 28/11/13 * Time: 15:10 * To change this template use File | Settings | File Templates. */ public class ActPlayer extends AppCompatActivity implements InterfacePlayer, ActivityCompat.OnRequestPermissionsResultCallback { public static final int LOGIN_RESULT = 101; private static final int PLAYLIST_CODE = 100; public static int selected = -1; private static Random randomGenerator; private AQuery aq; private AdpPlayer adapter;
private ArrayList<ClsTrack> items;
0
jenkinsci/plugin-compat-tester
plugins-compat-tester/src/test/java/org/jenkins/tools/test/PluginCompatTesterTest.java
[ "public class PCTPlugin {\n private String name;\n private final String groupId;\n private VersionNumber version;\n\n public PCTPlugin(String name, String groupId, VersionNumber version) {\n this.name = name;\n this.groupId = groupId;\n this.version = version;\n }\n\n public String getName() {\n return name;\n }\n\n @CheckForNull\n public String getGroupId() {\n return groupId;\n }\n\n public VersionNumber getVersion() {\n return version;\n }\n}", "public class PomExecutionException extends Exception {\n private final List<Throwable> exceptionsThrown;\n public final List<String> succeededPluginArtifactIds;\n private final List<String> pomWarningMessages;\n private final ExecutedTestNamesDetails testDetails;\n\n public PomExecutionException(Throwable cause) {\n this(cause.toString(), Collections.emptyList(), Collections.singletonList(cause), Collections.emptyList(), new ExecutedTestNamesDetails());\n }\n\n public PomExecutionException(PomExecutionException exceptionToCopy){\n this(exceptionToCopy.getMessage(), exceptionToCopy.succeededPluginArtifactIds, exceptionToCopy.exceptionsThrown, exceptionToCopy.pomWarningMessages, exceptionToCopy.testDetails);\n }\n\n @SuppressFBWarnings(value = \"EI_EXPOSE_REP2\", justification = \"oh well\")\n public PomExecutionException(String message, List<String> succeededPluginArtifactIds, List<Throwable> exceptionsThrown, List<String> pomWarningMessages, ExecutedTestNamesDetails testDetails){\n super(message, exceptionsThrown.isEmpty() ? null : exceptionsThrown.iterator().next());\n this.exceptionsThrown = new ArrayList<>(exceptionsThrown);\n this.succeededPluginArtifactIds = new ArrayList<>(succeededPluginArtifactIds);\n this.pomWarningMessages = new ArrayList<>(pomWarningMessages);\n this.testDetails = testDetails;\n }\n\n public String getErrorMessage(){\n StringBuilder strBldr = new StringBuilder();\n strBldr.append(String.format(\"Message : %s %n %nExecuted plugins : %s %n %nStacktraces :%n\",\n this.getMessage(), Arrays.toString(succeededPluginArtifactIds.toArray())));\n for(Throwable t : exceptionsThrown){\n Writer writer = new StringWriter();\n PrintWriter printWriter = new PrintWriter(writer);\n t.printStackTrace(printWriter);\n strBldr.append(String.format(\"%s %n %n\", writer.toString()));\n }\n return strBldr.toString();\n }\n\n @SuppressFBWarnings(value = \"EI_EXPOSE_REP\", justification = \"deliberately mutable\")\n public List<String> getPomWarningMessages() {\n return pomWarningMessages;\n }\n \n @SuppressFBWarnings(value = \"EI_EXPOSE_REP\", justification = \"oh well\")\n public ExecutedTestNamesDetails getTestDetails() {\n return testDetails;\n }\n}", "public class MavenCoordinates implements Comparable<MavenCoordinates> {\n public final String groupId;\n public final String artifactId;\n public final String version;\n // No classifier/type for the moment...\n\n /**\n * Constructor.\n *\n * @throws IllegalArgumentException one of the parameters is invalid.\n */\n public MavenCoordinates(@Nonnull String groupId, @Nonnull String artifactId, @Nonnull String version){\n this.groupId = verifyInput( groupId, artifactId, version,\"groupId\", groupId);\n this.artifactId = verifyInput( groupId, artifactId, version,\"artifactId\", artifactId);\n this.version = verifyInput( groupId, artifactId, version,\"version\", version);\n }\n\n private static String verifyInput(String groupId, String artifactId, String version,\n String fieldName, String value) throws IllegalArgumentException {\n if (value == null || StringUtils.isBlank(value)) {\n throw new IllegalArgumentException(\n String.format(\"Invalid parameter passed for %s:%s:%s: Field %s; %s\",\n groupId, artifactId, version, fieldName, value));\n }\n return value.trim();\n }\n\n @Override\n public boolean equals(Object o){\n if (!(o instanceof MavenCoordinates)) {\n return false;\n }\n MavenCoordinates c2 = (MavenCoordinates)o;\n return new EqualsBuilder().append(groupId, c2.groupId).append(artifactId, c2.artifactId).append(version, c2.version).isEquals();\n }\n\n @Override\n public int hashCode(){\n return new HashCodeBuilder().append(groupId).append(artifactId).append(version).toHashCode();\n }\n\n @Override\n public String toString(){\n return \"MavenCoordinates[groupId=\"+groupId+\", artifactId=\"+artifactId+\", version=\"+version+\"]\";\n }\n\n public String toGAV(){\n return groupId+\":\"+artifactId+\":\"+version;\n }\n\n public static MavenCoordinates fromGAV(String gav){\n String[] chunks = gav.split(\":\");\n return new MavenCoordinates(chunks[0], chunks[1], chunks[2]);\n }\n\n @Override\n public int compareTo(MavenCoordinates o) {\n if((groupId+\":\"+artifactId).equals(o.groupId+\":\"+o.artifactId)){\n return compareVersionTo(o.version);\n } else {\n return (groupId+\":\"+artifactId).compareTo(o.groupId+\":\"+o.artifactId);\n }\n }\n\n public boolean matches(String groupId, String artifactId) {\n return this.groupId.equals(groupId) && this.artifactId.equals(artifactId);\n }\n\n public int compareVersionTo(String version) {\n return new VersionComparator().compare(this.version, version);\n }\n}", "public class PluginCompatReport {\n private Map<PluginInfos, List<PluginCompatResult>> pluginCompatTests;\n private SortedSet<MavenCoordinates> testedCoreCoordinates;\n private String testJavaVersion;\n\n public PluginCompatReport(){\n this.pluginCompatTests = new TreeMap<>();\n this.testedCoreCoordinates = new TreeSet<>();\n }\n\n public void add(PluginInfos infos, PluginCompatResult result){\n if(!this.pluginCompatTests.containsKey(infos)){\n this.pluginCompatTests.put(infos, new ArrayList<>());\n }\n\n List<PluginCompatResult> results = pluginCompatTests.get(infos);\n // Deleting existing result if it exists\n results.remove(result);\n results.add(result);\n\n // Updating maven testedMavenCoordinates\n this.testedCoreCoordinates.add(result.coreCoordinates);\n }\n\n public void save(File reportPath) throws IOException {\n // Ensuring every PluginCompatResult list is sorted\n for(List<PluginCompatResult> results : this.pluginCompatTests.values()){\n Collections.sort(results);\n }\n\n // Writing to a temporary report file ...\n File tempReportPath = new File(reportPath.getAbsolutePath() + \".tmp\");\n try (Writer out =\n Files.newBufferedWriter(tempReportPath.toPath(), Charset.defaultCharset())) {\n out.write(String.format(\"<?xml version=\\\"1.0\\\" encoding=\\\"ISO-8859-1\\\"?>%n\"));\n out.write(String.format(\"<?xml-stylesheet href=\\\"\" + getXslFilename(reportPath) + \"\\\" type=\\\"text/xsl\\\"?>%n\"));\n XStream xstream = createXStream();\n xstream.toXML(this, out);\n out.flush();\n }\n\n // When everything went well, let's overwrite old report XML file with the new one\n Files.move(tempReportPath.toPath(), reportPath.toPath(), StandardCopyOption.ATOMIC_MOVE);\n }\n\n public static String getXslFilename(@Nonnull File reportPath){\n return getBaseFilename(reportPath)+\".xsl\";\n }\n\n public static File getXslFilepath(@Nonnull File reportPath){\n return new File(getBaseFilepath(reportPath)+\".xsl\");\n }\n\n public static File getHtmlFilepath(@Nonnull File reportPath){\n return new File(getBaseFilepath(reportPath)+\".html\");\n }\n\n public static String getBaseFilepath(@Nonnull File reportPath){\n File parentFile = reportPath.getParentFile();\n if (parentFile == null) {\n throw new IllegalArgumentException(\"The report path \" + reportPath + \" does not have a directory specification. \" +\n \"A correct path should be something like 'out/pct-report.xml'\");\n }\n return parentFile.getAbsolutePath()+\"/\"+getBaseFilename(reportPath);\n }\n\n public static String getBaseFilename(File reportPath){\n return reportPath.getName().split(\"\\\\.\")[0];\n }\n\n public boolean isCompatTestResultAlreadyInCache(PluginInfos pluginInfos, MavenCoordinates coreCoord, long cacheTimeout, TestStatus cacheThresholdStatus){\n // Retrieving plugin compatibility results corresponding to pluginsInfos + coreCoord\n if(!pluginCompatTests.containsKey(pluginInfos)){\n // No data for this plugin version ? => no cache !\n return false;\n }\n\n List<PluginCompatResult> results = pluginCompatTests.get(pluginInfos);\n PluginCompatResult resultCorrespondingToGivenCoreCoords = null;\n for(PluginCompatResult r : results){\n if(r.coreCoordinates.equals(coreCoord)){\n resultCorrespondingToGivenCoreCoords = r;\n break;\n }\n }\n if(resultCorrespondingToGivenCoreCoords == null){\n // No data for this core coordinates ? => no cache !\n return false;\n }\n\n // Is the latest execution on this plugin compliant with the given cache timeout ?\n // If so, then cache will be activated !\n if(new Date().before(new Date(resultCorrespondingToGivenCoreCoords.compatTestExecutedOn.getTime() + cacheTimeout))){\n return true;\n }\n\n // Status was lower than cacheThresholdStatus ? => no cache !\n return (!resultCorrespondingToGivenCoreCoords.status.isLowerThan(cacheThresholdStatus));\n }\n\n /**\n * Reads a compatibility report\n *\n * @param reportPath Report file path\n * @return Report. If the file does not exist, an empty report will be returned\n * @throws IOException Unexpected read error.\n */\n @Nonnull\n public static PluginCompatReport fromXml(File reportPath) throws IOException {\n PluginCompatReport report;\n\n // Reading report file from reportPath\n XStream xstream = createXStream();\n try(FileInputStream istream = new FileInputStream(reportPath)) {\n report = (PluginCompatReport)xstream.fromXML(istream);\n } catch (FileNotFoundException e) {\n // Path doesn't exist => create a new report object\n report = new PluginCompatReport();\n }\n\n // Ensuring we are using a TreeMap for pluginCompatTests\n if(!(report.pluginCompatTests instanceof SortedMap)){\n report.pluginCompatTests = new TreeMap<>(report.pluginCompatTests);\n }\n\n return report;\n }\n\n private static XStream2 createXStream(){\n XStream2 xstream = new XStream2(new Xpp3DomDriver());\n xstream.setMode(XStream.NO_REFERENCES);\n xstream.alias(\"pluginInfos\", PluginInfos.class);\n xstream.alias(\"coord\", MavenCoordinates.class);\n xstream.alias(\"compatResult\", PluginCompatResult.class);\n xstream.alias(\"status\", TestStatus.class);\n xstream.alias(\"report\", PluginCompatReport.class);\n return xstream;\n }\n\n public SortedSet<MavenCoordinates> getTestedCoreCoordinates() {\n return new TreeSet<>(testedCoreCoordinates);\n }\n\n\n public void setTestJavaVersion(String testJavaVersion) {\n this.testJavaVersion = testJavaVersion;\n }\n\n public String getTestJavaVersion() {\n return testJavaVersion;\n }\n\n public Map<PluginInfos, List<PluginCompatResult>> getPluginCompatTests(){\n return new TreeMap<>(pluginCompatTests);\n }\n}", "public class PluginCompatResult implements Comparable<PluginCompatResult> {\n public final MavenCoordinates coreCoordinates;\n\n public final TestStatus status;\n public final Date compatTestExecutedOn;\n\n public final String errorMessage;\n public final List<String> warningMessages;\n\n private final Set<String> testDetails;\n\n private String buildLogPath = \"\";\n\n public PluginCompatResult(MavenCoordinates coreCoordinates, TestStatus status,\n String errorMessage, List<String> warningMessages, Set<String> testDetails,\n String buildLogPath){\n // Create new result with current date\n this(coreCoordinates, status, errorMessage, warningMessages, testDetails, buildLogPath, new Date());\n }\n private PluginCompatResult(MavenCoordinates coreCoordinates, TestStatus status,\n String errorMessage, List<String> warningMessages, Set<String> testDetails,\n String buildLogPath, Date compatTestExecutedOn){\n this.coreCoordinates = coreCoordinates;\n\n this.status = status;\n\n this.errorMessage = errorMessage;\n this.warningMessages = warningMessages;\n\n this.testDetails = testDetails;\n this.buildLogPath = buildLogPath;\n\n this.compatTestExecutedOn = compatTestExecutedOn;\n }\n\n @Override\n public boolean equals(Object o){\n if (!(o instanceof PluginCompatResult)) {\n return false;\n }\n PluginCompatResult res = (PluginCompatResult)o;\n return new EqualsBuilder().append(coreCoordinates, res.coreCoordinates).isEquals();\n }\n\n @Override\n public int hashCode(){\n return new HashCodeBuilder().append(coreCoordinates).toHashCode();\n }\n\n @Override\n public int compareTo(PluginCompatResult o) {\n return coreCoordinates.compareTo(o.coreCoordinates);\n }\n\n public String getBuildLogPath() {\n return buildLogPath;\n }\n\n public void setBuildLogPath(String buildLogPath) {\n this.buildLogPath = buildLogPath;\n }\n\n public Set<String> getTestsDetails() {\n return Collections.unmodifiableSet(testDetails);\n }\n}", "@SuppressFBWarnings(value = {\"EI_EXPOSE_REP\", \"EI_EXPOSE_REP2\"}, justification = \"limited callers should know not to mutate\")\npublic class PluginCompatTesterConfig {\n\n private static final Logger LOGGER = Logger.getLogger(PluginCompatTesterConfig.class.getName());\n\n public static final String DEFAULT_UPDATE_CENTER_URL = \"https://updates.jenkins.io/current/update-center.json\";\n public static final String DEFAULT_PARENT_GROUP = \"org.jenkins-ci.plugins\";\n public static final String DEFAULT_PARENT_ARTIFACT = \"plugin\";\n public static final String DEFAULT_PARENT_GAV = DEFAULT_PARENT_GROUP + \":\" + DEFAULT_PARENT_ARTIFACT;\n\n // Update center used to retrieve plugins informations\n public final String updateCenterUrl;\n\n // A working directory where the tested plugin's sources will be checked out\n public final File workDirectory;\n\n // A report file where will be generated testing report\n // If the file already exist, testing report will be merged into it\n public final File reportFile;\n\n // Path for maven settings file where repository will be provided allowing to\n // download jenkins-core artifact (and dependencies)\n private final File m2SettingsFile;\n\n // GroupId which will be used to replace tested plugin's parent groupId\n // If null, every recorded core coordinates (in report xml) will be played\n private String parentGroupId = null;\n // ArtifactId which will be used to replace tested plugin's parent artifactId\n // If null, every recorded core coordinates (in report xml) will be played\n private String parentArtifactId = null;\n // Version which will be used to replace tested plugin's parent version\n // If null, latest core version (retrieved via the update center) will be used\n private String parentVersion = null;\n\n private File war = null;\n\n /**\n * A Java HOME to be used for running tests in plugins.\n */\n @CheckForNull\n private File testJDKHome = null;\n\n @CheckForNull\n private String testJavaArgs = null;\n\n @CheckForNull\n private File externalMaven = null;\n\n // List of plugin artifact ids on which tests will be performed\n // If null, tests will be performed on every plugins retrieved from update center\n private List<String> includePlugins = null;\n\n // List of plugin artifact ids on which tests will be not performed\n // If null, tests will be performed on every includePlugins found\n private List<String> excludePlugins = null;\n\n // URL to be used as an alternative to download plugin source from fallback\n // organtizations, like your own fork\n private String fallbackGitHubOrganization = null;\n\n // Allows to skip a plugin test if this plugin test has already been performed\n // within testCacheTimeout ms\n private long testCacheTimeout = 1000L * 60 * 60 * 24 * 100;\n // Skips test cache : plugin will be tested, no matter the test cache is\n private boolean skipTestCache = false;\n // Allows to define a minimal cache threshold for TestStatus\n // That is to say, every results lower than this threshold won't be put\n // into the cache\n private TestStatus cacheThresholdStatus = TestStatus.COMPILATION_ERROR;\n\n // Allows to provide XSL report file near XML report file\n // Only if reportFile is not null\n private boolean provideXslReport = true;\n\n // Allows to generate HTML Report file\n // Only if reportFile is not null\n private boolean generateHtmlReport = true;\n\n private Map<String, String> mavenProperties = Collections.emptyMap();\n private String mavenPropertiesFile;\n \n // Classpath prefixes of the extra hooks\n private List<String> hookPrefixes = new ArrayList<>(Collections.singletonList(\"org.jenkins\"));\n \n // External hooks jar files path locations\n private List<File> externalHooksJars = new ArrayList<>();\n\n // Path for a folder containing a local (possibly modified) clone of a plugin repository\n private File localCheckoutDir;\n\n private List<PCTPlugin> overridenPlugins = new ArrayList<>();\n\n // Immediately if the PCT run fails for a plugin. Error status will be also reported as a return code\n private boolean failOnError;\n\n // Path to a BOM file to get plugin data\n private File bom;\n\n // Flag to indicate if we want to store all the tests names or only failed ones on PCT report files\n private boolean storeAll;\n\n public PluginCompatTesterConfig(File workDirectory, File reportFile, File m2SettingsFile){\n this(DEFAULT_UPDATE_CENTER_URL, DEFAULT_PARENT_GAV,\n workDirectory, reportFile, m2SettingsFile);\n }\n\n public PluginCompatTesterConfig(String updateCenterUrl, String parentGAV,\n File workDirectory, File reportFile, File m2SettingsFile){\n this.updateCenterUrl = updateCenterUrl;\n if(parentGAV != null && !\"\".equals(parentGAV)){\n String[] gavChunks = parentGAV.split(\":\");\n assert gavChunks.length == 3 || gavChunks.length == 2;\n this.parentGroupId = gavChunks[0];\n this.parentArtifactId = gavChunks[1];\n if(gavChunks.length == 3 && !\"\".equals(gavChunks[2])){\n this.setParentVersion(gavChunks[2]);\n }\n }\n this.workDirectory = workDirectory;\n this.reportFile = reportFile;\n this.m2SettingsFile = m2SettingsFile;\n }\n\n public String getParentVersion() {\n return parentVersion;\n }\n\n public void setParentVersion(String parentVersion) {\n this.parentVersion = parentVersion;\n }\n\n public List<String> getIncludePlugins() {\n return includePlugins;\n }\n\n public void setIncludePlugins(List<String> pluginsList) {\n this.includePlugins = pluginsList;\n }\n\n public File getM2SettingsFile() {\n return m2SettingsFile;\n }\n\n public long getTestCacheTimeout() {\n return testCacheTimeout;\n }\n\n public void setTestCacheTimeout(long testCacheTimeout) {\n this.testCacheTimeout = testCacheTimeout;\n }\n\n public boolean isSkipTestCache() {\n return skipTestCache;\n }\n\n public void setSkipTestCache(boolean skipTestCache) {\n this.skipTestCache = skipTestCache;\n }\n\n public boolean isProvideXslReport() {\n return provideXslReport;\n }\n\n public void setProvideXslReport(boolean provideXslReport) {\n this.provideXslReport = provideXslReport;\n }\n\n public boolean isGenerateHtmlReport() {\n return generateHtmlReport;\n }\n\n public void setGenerateHtmlReport(boolean generateHtmlReport) {\n this.generateHtmlReport = generateHtmlReport;\n }\n\n public String getParentGroupId() {\n return parentGroupId;\n }\n\n @CheckForNull\n public File getTestJDKHome() {\n return testJDKHome;\n }\n\n @CheckForNull\n public String getTestJavaArgs() {\n return testJavaArgs;\n }\n\n public String getParentArtifactId() {\n return parentArtifactId;\n }\n\n public List<String> getExcludePlugins() {\n return excludePlugins;\n }\n\n public void setExcludePlugins(List<String> excludePlugins) {\n this.excludePlugins = excludePlugins;\n }\n\n public String getFallbackGitHubOrganization() {\n return fallbackGitHubOrganization;\n }\n\n public void setFallbackGitHubOrganization(String fallbackGitHubOrganization) {\n this.fallbackGitHubOrganization = fallbackGitHubOrganization;\n }\n\n public void setMavenProperties(@Nonnull Map<String, String> mavenProperties) {\n this.mavenProperties = new HashMap<>(mavenProperties);\n }\n\n /**\n * Gets a list of Maven properties defined in the configuration. It is not a full list of\n * properties; {@link #retrieveMavenProperties()} should be used to construct it.\n */\n @Nonnull\n public Map<String, String> getMavenProperties() {\n return Collections.unmodifiableMap(mavenProperties);\n }\n\n public String getMavenPropertiesFile() {\n return mavenPropertiesFile;\n }\n\n public void setMavenPropertiesFiles( String mavenPropertiesFile ) {\n this.mavenPropertiesFile = mavenPropertiesFile;\n }\n\n @CheckForNull\n public File getBom() {\n return bom;\n }\n\n public void setBom(File bom) {\n this.bom = bom;\n }\n\n /**\n * Retrieves Maven Properties from available sources like {@link #mavenPropertiesFile}.\n *\n * @return Map of properties\n * @throws IOException Property read failure\n * @since TODO\n */\n public Map<String, String> retrieveMavenProperties() throws IOException {\n Map<String, String> res = new HashMap<>(mavenProperties);\n\n // Read properties from File\n if ( StringUtils.isNotBlank( mavenPropertiesFile )) {\n File file = new File (mavenPropertiesFile);\n if (file.exists() && file.isFile()) {\n try(FileInputStream fileInputStream = new FileInputStream(file)) {\n Properties properties = new Properties( );\n properties.load( fileInputStream );\n for (Map.Entry<Object,Object> entry : properties.entrySet()) {\n res.put((String) entry.getKey(), (String) entry.getValue());\n }\n }\n } else {\n throw new IOException(\"Extra Maven Properties File \" + mavenPropertiesFile + \" does not exist or not a File\" );\n }\n }\n\n // Read other explicit CLI arguments\n\n // Override JDK if passed explicitly\n if (testJDKHome != null) {\n if (!testJDKHome.exists() || !testJDKHome.isDirectory()) {\n throw new IOException(\"Wrong Test JDK Home passed as a parameter: \" + testJDKHome);\n }\n\n if (res.containsKey(\"jvm\")) {\n System.out.println(\"WARNING: Maven properties already contain the 'jvm' argument. \" +\n \"Overriding the previous Test JDK home value '\" + res.get(\"jvm\") +\n \"' by the explicit argument: \" + testJDKHome);\n } else {\n System.out.println(\"Using custom Test JDK home: \" + testJDKHome);\n }\n final String javaCmdAbsolutePath = getTestJavaCommandPath();\n res.put(\"jvm\", javaCmdAbsolutePath);\n }\n\n // Merge test Java args if needed\n if (StringUtils.isNotBlank(testJavaArgs)) {\n if (res.containsKey(\"argLine\")) {\n System.out.println(\"WARNING: Maven properties already contain the 'argLine' argument. \" +\n \"Merging value from properties and from the command line\");\n res.put(\"argLine\", res.get(\"argLine\") + \" \" + testJavaArgs);\n } else {\n res.put(\"argLine\", testJavaArgs);\n }\n }\n\n return res;\n }\n\n @CheckForNull\n private String getTestJavaCommandPath() {\n if(testJDKHome==null) {\n return null;\n }\n return new File(testJDKHome, \"bin/java\").getAbsolutePath();\n }\n\n /**\n * Gets the Java version used for testing, using the binary path to the <code>java</code>\n * command.\n *\n * @return a string identifying the jvm in use\n */\n public String getTestJavaVersion() throws IOException {\n String javaCmdAbsolutePath = getTestJavaCommandPath();\n if (javaCmdAbsolutePath == null) {\n LOGGER.info(\"testJdkHome unset, using java available from the PATH\");\n javaCmdAbsolutePath = \"java\";\n }\n final Process process = new ProcessBuilder().command(javaCmdAbsolutePath, \"-XshowSettings:properties -version\").redirectErrorStream(true).start();\n final String javaVersionOutput = IOUtils.toString(process.getInputStream());\n final String[] lines = javaVersionOutput.split(\"[\\\\r\\\\n]+\");\n for (String line: lines) {\n String trimmed = line.trim();\n if (trimmed.contains(\"java.specification.version\")) {\n //java.specification.version = version\n return trimmed.split(\"=\")[1].trim();\n }\n }\n // Default to fullversion output as before\n final Process process2 = new ProcessBuilder().command(javaCmdAbsolutePath, \"-fullversion\").redirectErrorStream(true).start();\n final String javaVersionOutput2 = IOUtils.toString(process2.getInputStream());\n // Expected format is something like openjdk full version \"1.8.0_181-8u181-b13-2~deb9u1-b13\"\n // We shorten it by removing the \"full version\" in the middle\n return javaVersionOutput2.\n replace(\" full version \", \" \").\n replaceAll(\"\\\"\", \"\");\n }\n\n public TestStatus getCacheThresholdStatus() {\n return cacheThresholdStatus;\n }\n\n public void setCacheThresholdStatus(TestStatus cacheThresholdStatus) {\n this.cacheThresholdStatus = cacheThresholdStatus;\n }\n\n public File getWar() {\n return war;\n }\n\n public void setWar(File war) {\n this.war = war;\n }\n\n @CheckForNull\n public File getExternalMaven() {\n return externalMaven;\n }\n\n public void setExternalMaven(File externalMaven) {\n this.externalMaven = externalMaven;\n }\n\n public List<String> getHookPrefixes() {\n return hookPrefixes;\n }\n \n public List<File> getExternalHooksJars() {\n return externalHooksJars;\n }\n\n public void setHookPrefixes(List<String> hookPrefixes) {\n // Want to also process the default\n this.hookPrefixes.addAll(hookPrefixes);\n }\n \n public void setExternalHooksJars(List<File> externalHooksJars) {\n this.externalHooksJars = externalHooksJars;\n }\n\n /**\n * Sets JDK Home for tests\n *\n * @param testJDKHome JDK home to be used. {@code null} for using default system one.\n */\n public void setTestJDKHome(@CheckForNull File testJDKHome) {\n this.testJDKHome = testJDKHome;\n }\n\n public void setTestJavaArgs(@CheckForNull String testJavaArgs) {\n this.testJavaArgs = testJavaArgs;\n }\n\n public File getLocalCheckoutDir() {\n return localCheckoutDir;\n }\n\n public void setLocalCheckoutDir(String localCheckoutDir) {\n this.localCheckoutDir = new File(localCheckoutDir);\n }\n\n public void setOverridenPlugins(List<PCTPlugin> overridenPlugins) {\n this.overridenPlugins = overridenPlugins;\n }\n\n public List<PCTPlugin> getOverridenPlugins() {\n return overridenPlugins;\n }\n\n public boolean isFailOnError() {\n return failOnError;\n }\n\n public void setFailOnError(boolean failOnError) {\n this.failOnError = failOnError;\n }\n\n public void setStoreAll(boolean storeAll) {\n this.storeAll = storeAll;\n }\n \n public boolean isStoreAll() {\n return storeAll;\n }\n}", "public class PluginInfos implements Comparable<PluginInfos> {\n public final String pluginName;\n public final String pluginVersion;\n public final String pluginUrl;\n\n public PluginInfos(String pluginName, String pluginVersion, String pluginUrl){\n this.pluginName = pluginName;\n this.pluginVersion = pluginVersion;\n this.pluginUrl = pluginUrl;\n }\n\n @Override\n public boolean equals(Object o){\n if (!(o instanceof PluginInfos)) {\n return false;\n }\n PluginInfos infos = (PluginInfos)o;\n return new EqualsBuilder().append(pluginName, infos.pluginName).append(pluginVersion, infos.pluginVersion).isEquals();\n }\n\n @Override\n public int hashCode(){\n return new HashCodeBuilder().append(pluginName).append(pluginVersion).toHashCode();\n }\n\n @Override\n public int compareTo(PluginInfos o) {\n if(pluginName.equals(o.pluginName)){\n return pluginVersion.compareTo(o.pluginVersion);\n }else{\n return pluginName.compareToIgnoreCase(o.pluginName);\n }\n }\n}", "public class PomData {\n public final String artifactId;\n public final String groupId;\n\n @Nonnull\n private final String packaging;\n\n @CheckForNull\n public final MavenCoordinates parent;\n private String connectionUrl;\n private String scmTag;\n private List<String> warningMessages = new ArrayList<>();\n\n public PomData(String artifactId, @CheckForNull String packaging, String connectionUrl, String scmTag, @CheckForNull MavenCoordinates parent, String groupId){\n this.artifactId = artifactId;\n this.groupId = groupId;\n this.packaging = packaging != null ? packaging : \"jar\";\n this.setConnectionUrl(connectionUrl);\n this.scmTag = scmTag;\n this.parent = parent;\n }\n\n public String getConnectionUrl() {\n return connectionUrl;\n }\n\n public void setConnectionUrl(String connectionUrl) {\n this.connectionUrl = connectionUrl;\n }\n\n @SuppressFBWarnings(value = \"EI_EXPOSE_REP\", justification = \"Deliberately mutable\")\n public List<String> getWarningMessages() {\n return warningMessages;\n }\n\n @Nonnull\n public String getPackaging() {\n return packaging;\n }\n\n public String getScmTag() {\n return scmTag;\n }\n\n public boolean isPluginPOM() {\n if (parent != null) {\n return parent.matches(\"org.jenkins-ci.plugins\", \"plugin\");\n } else { // Interpolate by packaging\n return \"hpi\".equalsIgnoreCase(packaging);\n }\n }\n}", "public enum TestStatus {\n INTERNAL_ERROR(0.0), COMPILATION_ERROR(1.0), TEST_FAILURES(2.0), SUCCESS(3.0);\n\n private final double weight;\n\n TestStatus(double weight){\n this.weight = weight;\n }\n\n public boolean isLowerThan(TestStatus s){\n return weight < s.weight;\n }\n}" ]
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import java.io.File; import org.jenkins.tools.test.model.PCTPlugin; import java.io.IOException; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.codehaus.plexus.PlexusContainerException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.jenkins.tools.test.exception.PomExecutionException; import org.jenkins.tools.test.model.MavenCoordinates; import org.jenkins.tools.test.model.PluginCompatReport; import org.jenkins.tools.test.model.PluginCompatResult; import org.jenkins.tools.test.model.PluginCompatTesterConfig; import org.jenkins.tools.test.model.PluginInfos; import org.jenkins.tools.test.model.PomData; import org.jenkins.tools.test.model.TestStatus; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.jvnet.hudson.test.Issue; import org.springframework.core.io.ClassPathResource; import com.google.common.collect.ImmutableList; import hudson.util.VersionNumber;
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe, * Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc. * * 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 org.jenkins.tools.test; /** * Main test class for plugin compatibility test frontend * * @author Frederic Camblor */ public class PluginCompatTesterTest { private static final String MAVEN_INSTALLATION_WINDOWS = "C:\\Jenkins\\tools\\hudson.tasks.Maven_MavenInstallation\\mvn\\bin\\mvn.cmd"; private static final String REPORT_FILE = String.format("%s%sreports%sPluginCompatReport.xml", System.getProperty("java.io.tmpdir"), File.separator, File.separator); @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Before public void setUp() throws Exception { SCMManagerFactory.getInstance().start(); File file = Paths.get(REPORT_FILE).toFile(); if (file.exists()) { FileUtils.deleteQuietly(file); } } @After public void tearDown() { SCMManagerFactory.getInstance().stop(); } @Ignore("TODO broken by https://github.com/jenkinsci/active-directory-plugin/releases/tag/active-directory-2.17; figure out how to pin a version") @Test public void testWithUrl() throws Throwable { PluginCompatTesterConfig config = getConfig(ImmutableList.of("active-directory")); config.setStoreAll(true); PluginCompatTester tester = new PluginCompatTester(config);
PluginCompatReport report = tester.testPlugins();
3
ErnestOrt/Trampoline
trampoline/src/main/java/org/ernest/applications/trampoline/controller/InstancesController.java
[ "@Component\npublic class InstanceInfoCollector {\n\n private static final Logger log = LoggerFactory.getLogger(InstanceInfoCollector.class);\n\n @Autowired\n EcosystemManager ecosystemManager;\n\n public InstanceGitInfo getInfo(String idInstance) {\n InstanceGitInfo info = new InstanceGitInfo();\n\n Instance instance = ecosystemManager.getEcosystem().getInstances().stream().filter(i -> i.getId().equals(idInstance)).findAny().get();\n info.setPomLocation(instance.getPomLocation());\n info.setBranch(\"-\");\n info.setCommitMessage(\"-\");\n info.setCommitOwner(\"-\");\n info.setCommitDate(\"-\");\n try {\n String url = instance.buildActuatorUrl() + \"/info\";\n\n log.info(\"Reading GIT info Spring Boot 1.x for instance id: [{}] using url: [{}]\", idInstance, url);\n JSONObject infoJson = new JSONObject(new RestTemplate().getForObject(url, String.class));\n info.setBranch(infoJson.getJSONObject(\"git\").get(\"branch\").toString());\n info.setCommitMessage(infoJson.getJSONObject(\"git\").getJSONObject(\"commit\").getJSONObject(\"message\").get(\"full\").toString());\n info.setCommitOwner(infoJson.getJSONObject(\"git\").getJSONObject(\"commit\").getJSONObject(\"user\").get(\"name\").toString() + \"[\"+infoJson.getJSONObject(\"git\").getJSONObject(\"commit\").getJSONObject(\"user\").get(\"email\").toString()+\"]\");\n\n try {\n log.info(\"Reading GIT info Spring Boot 2.x for instance id: [{}] using url: [{}]\", idInstance, url);\n Long timestamp = Long.valueOf(infoJson.getJSONObject(\"git\").getJSONObject(\"commit\").get(\"time\").toString());\n info.setCommitDate(new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\").format(new Date(new Timestamp(timestamp).getTime())));\n }catch (NumberFormatException e){\n info.setCommitDate(infoJson.getJSONObject(\"git\").getJSONObject(\"commit\").get(\"time\").toString());\n }\n }catch (Exception e){\n log.error(\"Not possible to retrieve git info for instance: [\"+instance.getId()+\"] hosted on port: [\"+instance.getPort()+\"]\", e);\n }\n return info;\n }\n}", "@Component\npublic class EcosystemManager {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(TraceCollector.class);\n\n\t@Autowired\n\tFileManager fileManager;\n\t\n\tpublic Ecosystem getEcosystem() throws CreatingSettingsFolderException, ReadingEcosystemException {\n\t\treturn fileManager.getEcosystem();\n\t}\n\t\n\tpublic void setMavenBinaryLocation(String path) throws CreatingSettingsFolderException, ReadingEcosystemException, SavingEcosystemException {\n\t\tlog.info(\"Saving Maven Binary Location path [{}]\", path);\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tecosystem.setMavenBinaryLocation(path);\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\t\n\tpublic void setMavenHomeLocation(String path) throws CreatingSettingsFolderException, ReadingEcosystemException, SavingEcosystemException {\n\t\tlog.info(\"Saving Maven Home Location path [{}]\", path);\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tecosystem.setMavenHomeLocation(path);\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\t\n\tpublic void setNewMicroservice(String name, String pomLocation, String defaultPort, String actuatorPrefix, String vmArguments, String buildTool, String gitLocation) throws CreatingSettingsFolderException, ReadingEcosystemException, CreatingMicroserviceScriptException, SavingEcosystemException {\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\n\t\tlog.info(\"Creating new microservice name: [{}]\", name);\n\t\tMicroservice microservice = new Microservice();\n\t\tmicroservice.setId(UUID.randomUUID().toString());\n\t\tmicroservice.setName(name);\n\t\tmicroservice.setPomLocation(pomLocation);\n\t\tmicroservice.setDefaultPort(defaultPort);\n\t\tmicroservice.setActuatorPrefix(actuatorPrefix);\n\t\tmicroservice.setVmArguments(vmArguments);\n\t\tmicroservice.setBuildTool(BuildTools.getByCode(buildTool));\n\t\tmicroservice.setGitLocation(gitLocation);\n\t\tfileManager.createScript(microservice);\n\n\t\tlog.info(\"Saving microservice: [{}]\", microservice.toString());\n\t\tecosystem.getMicroservices().add(microservice);\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\t\n\tpublic void removeMicroservice(String idToBeDeleted) throws CreatingSettingsFolderException, ReadingEcosystemException, SavingEcosystemException {\n\t\tlog.info(\"Removing microservice id: [{}]\", idToBeDeleted);\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tecosystem.setMicroservices(ecosystem.getMicroservices().stream().filter(m -> !m.getId().equals(idToBeDeleted)).collect(Collectors.toList()));\n\t\tecosystem.getMicroservicesGroups().forEach(g-> g.setMicroservicesIds(g.getMicroservicesIds().stream().filter(id -> !id.equals(idToBeDeleted)).collect(Collectors.toList())));\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\n\tpublic void setMicroserviceGroup(String name, List<String> idsMicroservicesGroup, List<Integer> delaysMicroservicesGroup) {\n\t\tlog.info(\"Creating group name: [{}] with microservices [{}]\", name, idsMicroservicesGroup.stream().collect(Collectors.joining(\",\")));\n\t\tMicroservicesGroup microservicesGroup = new MicroservicesGroup();\n\t\tmicroservicesGroup.setId(UUID.randomUUID().toString());\n\t\tmicroservicesGroup.setName(name);\n\t\tmicroservicesGroup.setMicroservicesIds(idsMicroservicesGroup);\n\t\tmicroservicesGroup.setMicroservicesDelays(delaysMicroservicesGroup);\n\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tecosystem.getMicroservicesGroups().add(microservicesGroup);\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\n\tpublic void removeGroup(String id) {\n\t\tlog.info(\"Removing group id: [{}]\", id);\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tecosystem.setMicroservicesGroups(ecosystem.getMicroservicesGroups().stream().filter(g -> !g.getId().equals(id)).collect(Collectors.toList()));\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\n\tpublic void startInstance(String id, String port, String vmArguments, Integer startingDelay) throws CreatingSettingsFolderException, ReadingEcosystemException, RunningMicroserviceScriptException, SavingEcosystemException, InterruptedException {\n\t\tlog.info(\"Starting instances id: [{}] port: [{}] vmArguments: [{}] startingDelay: [{}]\", id, port, vmArguments, startingDelay);\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\t\n\t\tMicroservice microservice = ecosystem.getMicroservices().stream().filter(m -> m.getId().equals(id)).findAny().get();\n\t\tThread.sleep(startingDelay*1000);\n\t\tlog.info(\"Launching script to start instances id: [{}]\", id);\n\t\tfileManager.runScript(microservice, ecosystem.getMavenBinaryLocation(), ecosystem.getMavenHomeLocation(), port, vmArguments);\n\t\t\n\t\tInstance instance = new Instance();\n\t\tinstance.setId(UUID.randomUUID().toString());\n\t\tinstance.setIp(\"127.0.0.1\");\n\t\tinstance.setPort(port);\n\t\tinstance.setName(microservice.getName());\n\t\tinstance.setPomLocation(microservice.getPomLocation());\n\t\tinstance.setActuatorPrefix(microservice.getActuatorPrefix());\n\t\tinstance.setVmArguments(vmArguments);\n\t\tinstance.setMicroserviceId(id);\n\t\tecosystem.getInstances().add(instance);\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\n\tpublic void killInstance(String id) throws CreatingSettingsFolderException, ReadingEcosystemException, SavingEcosystemException, ShuttingDownInstanceException {\n\t\tlog.info(\"Removing instance id: [{}]\", id);\n\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tInstance instance = ecosystem.getInstances().stream().filter(i -> i.getId().equals(id)).collect(Collectors.toList()).get(0);\n\n\t\tif (instance.getIp().equals(\"127.0.0.1\")) {\n\t\t\tlog.info(\"Stopping instance id: [{}]\", id);\n\t\t\ttry {\n\t\t\t\tnew ClientRequest(instance.buildActuatorUrl() + \"/shutdown\").post(String.class);\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.error(\"Stopping instance id: [{}]\", id);\n\t\t\t}\n\t\t}\n\n\t\tecosystem.setInstances(ecosystem.getInstances().stream().filter(i -> !i.getId().equals(id)).collect(Collectors.toList()));\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\n\tpublic String getStatusInstance(String id) throws CreatingSettingsFolderException, ReadingEcosystemException {\n\t\tlog.info(\"Checking status instances id: [{}]\", id);\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tList<Instance> instances = ecosystem.getInstances().stream().filter(i -> i.getId().equals(id)).collect(Collectors.toList());\n\t\tif(!instances.isEmpty() && isDeployed(instances.get(0))){\n\t\t\treturn StatusInstance.DEPLOYED.getCode();\n\t\t}\n\t\treturn StatusInstance.NOT_DEPLOYED.getCode();\n\t}\n\n\tprivate boolean isDeployed(Instance instance) {\n\t\ttry{\n\t\t\tnew ClientRequest(instance.buildActuatorUrl() + \"/env\").get(String.class);\n\t\t}catch(Exception e){\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic void startGroup(String id) throws InterruptedException {\n\t\tlog.info(\"Starting group id: [{}]\", id);\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tMicroservicesGroup group = ecosystem.getMicroservicesGroups().stream().filter(g -> g.getId().equals(id)).findFirst().get();\n\n\t\tfor(int index = 0; index < group.getMicroservicesIds().size(); index++){\n\t\t\tint microserviceIndex = index;\n\t\t\tMicroservice microservice = ecosystem.getMicroservices().stream().filter(m->m.getId().equals(group.getMicroservicesIds().get(microserviceIndex))).findAny().get();\n\t\t\tprepareMicroservice(microservice, group.getMicroservicesDelays().get(microserviceIndex));\n\t\t}\n\t}\n\n\tprivate void prepareMicroservice(Microservice microservice, Integer startingDelay) throws InterruptedException {\n\t\tint port = Integer.parseInt(microservice.getDefaultPort());\n\t\tboolean instanceStarted = false;\n\t\tList<Instance> instances = fileManager.getEcosystem().getInstances();\n\n\t\twhile(!instanceStarted) {\n\t\t\tfinal int portToBeLaunched = port;\n\t\t\tif (PortsChecker.available(portToBeLaunched) && !instances.stream().anyMatch(i -> i.getPort().equals(String.valueOf(portToBeLaunched)))) {\n\t\t\t\tstartInstance(microservice.getId(), String.valueOf(port), microservice.getVmArguments(), startingDelay);\n\t\t\t\tinstanceStarted = true;\n\t\t\t}else{\n\t\t\t\tport++;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void updateMicroservice(String id, String pomLocation, String defaultPort, String actuatorPrefix, String vmArguments, String gitLocation) {\n\t\tlog.info(\"Updating microservice id: [{}]\", id);\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\n\t\tMicroservice microservice = ecosystem.getMicroservices().stream().filter(m -> m.getId().equals(id)).findAny().get();\n\t\tmicroservice.setPomLocation(pomLocation);\n\t\tmicroservice.setDefaultPort(defaultPort);\n\t\tmicroservice.setActuatorPrefix(actuatorPrefix);\n\t\tmicroservice.setVmArguments(vmArguments);\n\t\tmicroservice.setGitLocation(gitLocation);\n\n\t\tfileManager.createScript(microservice);\n\n\t\tlog.info(\"Saving microservice: [{}]\", microservice.toString());\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\n\tpublic void restartInstance(String instanceId) throws InterruptedException {\n\t\tlog.info(\"Restarting instance id: [{}]\", instanceId);\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tInstance instance = ecosystem.getInstances().stream().filter(i -> i.getId().equals(instanceId)).findFirst().get();\n\t\tkillInstance(instance.getId());\n\t\tstartInstance(instance.getMicroserviceId(), instance.getPort(), instance.getVmArguments(), 0);\n\t}\n\n\tpublic void saveGitHttpsCred(String user, String pass) {\n\t\tlog.info(\"Saving GIT HTTPS Credentials\");\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tGitCredentials gitCredentials = ecosystem.getGitCredentials();\n\t\tif (gitCredentials.getHttpsSettings() != null) {\n\t\t\tgitCredentials.getHttpsSettings().setUsername(user);\n\t\t\tgitCredentials.getHttpsSettings().setPass(pass);\n\t\t} else {\n\t\t\tecosystem.setGitCredentials(new GitCredentials(new GitCredentials.HttpsSettings(user, pass)));\n\t\t}\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\n\tpublic void saveGitSshCred(String privateKeyLocation, String sshKeyPassword) {\n\t\tlog.info(\"Saving GIT SSH Credentials\");\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tGitCredentials gitCredentials = ecosystem.getGitCredentials();\n\t\tif (gitCredentials.getSshSettings() != null) {\n\t\t\tgitCredentials.getSshSettings().setSshKeyLocation(privateKeyLocation);\n\t\t\tgitCredentials.getSshSettings().setSshKeyPassword(sshKeyPassword);\n\t\t} else {\n\t\t\tecosystem.setGitCredentials(new GitCredentials(new SshSettings(privateKeyLocation, sshKeyPassword)));\n\t\t}\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\n\tpublic void cleanGitCred() {\n\t\tlog.info(\"Cleaning GIT Credentials\");\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tecosystem.setGitCredentials(new GitCredentials());\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\n public void setNewExternalInstance(String name, String port, String actuatorPrefix, String ip) {\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\n\t\tlog.info(\"Creating new external instance: [{}]\", name);\n\t\tExternalInstance externalInstance = new ExternalInstance();\n\t\texternalInstance.setId(UUID.randomUUID().toString());\n\t\texternalInstance.setName(name);\n\t\texternalInstance.setIp(ip);\n\t\texternalInstance.setActuatorPrefix(actuatorPrefix);\n\t\texternalInstance.setPort(port);\n\n\t\tlog.info(\"Saving external instance: [{}]\", externalInstance.toString());\n\t\tecosystem.getExternalInstances().add(externalInstance);\n\t\tfileManager.saveEcosystem(ecosystem);\n }\n\n\tpublic void removeExternalInstance(String idToBeDeleted) {\n\t\tlog.info(\"Removing microservice id: [{}]\", idToBeDeleted);\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\t\tecosystem.setExternalInstances(ecosystem.getExternalInstances().stream().filter(i -> !i.getId().equals(idToBeDeleted)).collect(Collectors.toList()));\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n\n\tpublic void addExternalInstance(String id) {\n\t\tlog.info(\"Adding external instance id: [{}]\", id);\n\t\tEcosystem ecosystem = fileManager.getEcosystem();\n\n\t\tExternalInstance externalInstance = ecosystem.getExternalInstances().stream().filter(i -> i.getId().equals(id)).findAny().get();\n\n\t\tInstance instance = new Instance();\n\t\tinstance.setId(UUID.randomUUID().toString());\n\t\tinstance.setIp(externalInstance.getIp());\n\t\tinstance.setPort(externalInstance.getPort());\n\t\tinstance.setName(externalInstance.getName());\n\t\tinstance.setActuatorPrefix(externalInstance.getActuatorPrefix());\n\t\tinstance.setMicroserviceId(id);\n\t\tecosystem.getInstances().add(instance);\n\t\tfileManager.saveEcosystem(ecosystem);\n\t}\n}", "@Component\npublic class MetricsCollector {\n\n private static final Logger log = LoggerFactory.getLogger(MetricsCollector.class);\n\n @Autowired\n EcosystemManager ecosystemManager;\n\n private Map<String, Queue<Metrics>> metricsMap = new HashMap<>();\n\n @Scheduled(fixedDelay=30000)\n public void collectMetrics() throws JSONException, InterruptedException, CreatingSettingsFolderException, ReadingEcosystemException {\n\n ecosystemManager.getEcosystem().getInstances().forEach(instance ->{\n try {\n Metrics metrics;\n try {\n metrics = buildMetricsFromJsonResponseV1x(instance);\n }catch (Exception e){\n metrics = buildMetricsFromJsonResponseV2x(instance);\n }\n\n if (metricsMap.containsKey(instance.getId())) {\n metricsMap.get(instance.getId()).add(metrics);\n } else {\n Queue<Metrics> queue = new CircularFifoQueue(20);\n queue.add(metrics);\n metricsMap.put(instance.getId(), queue);\n }\n }catch (Exception e){\n log.error(\"Not possible to retrieve metrics for instance: [\"+instance.getId()+\"] hosted on port: [\"+instance.getPort()+\"]\");\n }\n });\n\n removeNotActiveInstances();\n }\n\n public Queue<Metrics> getInstanceMetrics(String id){\n return metricsMap.get(id);\n }\n\n private void removeNotActiveInstances() {\n List<String> idsToBeDeleted = metricsMap.keySet().stream().filter(id -> {\n try {\n return !ecosystemManager.getEcosystem().getInstances().stream().anyMatch(i -> i.getId().equals(id));\n } catch (CreatingSettingsFolderException e) {\n e.printStackTrace();\n } catch (ReadingEcosystemException e) {\n e.printStackTrace();\n }\n return true;\n }).collect(Collectors.toList());\n\n idsToBeDeleted.stream().forEach(id-> metricsMap.remove(id));\n }\n\n private Metrics buildMetricsFromJsonResponseV1x(Instance instance) throws JSONException {\n Metrics metrics = new Metrics();\n\n String url = instance.buildActuatorUrl() + \"/metrics\";\n log.info(\"Reading metrics Spring Boot 1.x for instance id: [{}] using url: [{}]\", instance.getId(), url);\n\n JSONObject metricsJson = new JSONObject(new RestTemplate().getForObject(url, String.class));\n metrics.setTotalMemoryKB(Long.valueOf(metricsJson.get(\"mem\").toString()));\n metrics.setFreeMemoryKB(Long.valueOf(metricsJson.get(\"mem.free\").toString()));\n metrics.setHeapKB(Long.valueOf(metricsJson.get(\"heap\").toString()));\n metrics.setInitHeapKB(Long.valueOf(metricsJson.get(\"heap.init\").toString()));\n metrics.setUsedHeapKB(Long.valueOf(metricsJson.get(\"heap.used\").toString()));\n metrics.setDate(new SimpleDateFormat(\"HH:mm:ss\").format(new Date()));\n\n return metrics;\n }\n\n private Metrics buildMetricsFromJsonResponseV2x(Instance instance) throws JSONException {\n log.info(\"Reading metrics Spring Boot 2.x for instance id: [{}]\", instance.getId());\n\n Metrics metrics = new Metrics();\n metrics.setTotalMemoryKB(getValueMetric(instance, \"jvm.memory.max\"));\n metrics.setHeapKB(0L);\n metrics.setInitHeapKB(0L);\n metrics.setUsedHeapKB(getValueMetric(instance, \"jvm.memory.used\"));\n metrics.setFreeMemoryKB(metrics.getTotalMemoryKB() - metrics.getUsedHeapKB());\n metrics.setDate(new SimpleDateFormat(\"HH:mm:ss\").format(new Date()));\n\n return metrics;\n }\n\n private Long getValueMetric(Instance instance, String key) throws JSONException {\n JSONObject metricsJson = new JSONObject(new RestTemplate().getForObject(\"http://\"+instance.getIp()+\":\" + instance.getPort() + \"/\" + instance.getActuatorPrefix() + \"/metrics/\"+key, String.class));\n return Long.valueOf(metricsJson.getJSONArray(\"measurements\").getJSONObject(0).getInt(\"value\"));\n }\n}", "@Component\npublic class TraceCollector {\n\n private static final Logger log = LoggerFactory.getLogger(TraceCollector.class);\n\n @Autowired\n EcosystemManager ecosystemManager;\n\n public List<TraceActuator> getTraces(String idInstance) throws CreatingSettingsFolderException, ReadingEcosystemException, JSONException {\n List<TraceActuator> traces = new ArrayList<>();\n\n Instance instance = ecosystemManager.getEcosystem().getInstances().stream().filter(i -> i.getId().equals(idInstance)).findAny().get();\n JSONArray traceArrayJson;\n\n String url;\n try {\n url = instance.buildActuatorUrl() + \"/trace\";\n log.info(\"Reading traces Spring Boot 1.x for instance id: [{}] using url: [{}]\", idInstance, url);\n traceArrayJson = new JSONArray(new RestTemplate().getForObject(url, String.class));\n buildTracesV1x(traces, traceArrayJson);\n }catch (Exception e){\n url = instance.buildActuatorUrl() + \"/httptrace\";\n log.info(\"Reading traces Spring Boot 2.x for instance id: [{}] using url: [{}]\", idInstance, url);\n traceArrayJson = new JSONObject(new RestTemplate().getForObject(url, String.class)).getJSONArray(\"traces\");\n buildTracesV2x(traces, traceArrayJson);\n }\n\n return traces;\n }\n\n private void buildTracesV2x(List<TraceActuator> traces, JSONArray traceArrayJson) throws JSONException {\n for (int i = 0; i < traceArrayJson.length(); i++) {\n JSONObject traceJson = traceArrayJson.getJSONObject(i);\n\n org.ernest.applications.trampoline.entities.TraceActuator traceActuator = new org.ernest.applications.trampoline.entities.TraceActuator();\n traceActuator.setDate(traceJson.getString(\"timestamp\"));\n traceActuator.setMethod(traceJson.getJSONObject(\"request\").getString(\"method\"));\n traceActuator.setPath(traceJson.getJSONObject(\"request\").getString(\"uri\"));\n traceActuator.setStatus(String.valueOf(traceJson.getJSONObject(\"response\").getInt(\"status\")));\n traces.add(traceActuator);\n }\n\n }\n\n private void buildTracesV1x(List<TraceActuator> traces, JSONArray traceArrayJson) throws JSONException {\n for (int i = 0; i < traceArrayJson.length(); i++) {\n JSONObject traceJson = traceArrayJson.getJSONObject(i);\n\n TraceActuator traceActuator = new TraceActuator();\n traceActuator.setDate(new SimpleDateFormat(\"HH:mm:ss\").format(traceJson.getLong(\"timestamp\")));\n traceActuator.setMethod(traceJson.getJSONObject(\"info\").getString(\"method\"));\n traceActuator.setPath(traceJson.getJSONObject(\"info\").getString(\"path\"));\n traceActuator.setStatus(traceJson.getJSONObject(\"info\").getJSONObject(\"headers\").getJSONObject(\"response\").getString(\"status\"));\n traces.add(traceActuator);\n }\n }\n}", "public class PortsChecker {\n\n private static final Logger log = LoggerFactory.getLogger(PortsChecker.class);\n\n public static boolean available(int port) {\n log.info(\"Checking port [{}]\", port);\n ServerSocket ss = null;\n DatagramSocket ds = null;\n try {\n ss = new ServerSocket(port);\n ss.setReuseAddress(true);\n ds = new DatagramSocket(port);\n ds.setReuseAddress(true);\n return true;\n } catch (IOException e) {\n } finally {\n if (ds != null) { ds.close(); }\n if (ss != null) { try { ss.close(); } catch (IOException e) {}}\n }\n return false;\n }\n}" ]
import org.ernest.applications.trampoline.collectors.InstanceInfoCollector; import org.ernest.applications.trampoline.entities.*; import org.ernest.applications.trampoline.exceptions.*; import org.ernest.applications.trampoline.services.EcosystemManager; import org.ernest.applications.trampoline.collectors.MetricsCollector; import org.ernest.applications.trampoline.collectors.TraceCollector; import org.ernest.applications.trampoline.utils.PortsChecker; import org.json.JSONException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; import java.util.Queue;
package org.ernest.applications.trampoline.controller; @Controller @RequestMapping("/instances") public class InstancesController { private static final String INSTANCES_VIEW = "instances"; @Autowired EcosystemManager ecosystemManager; @Autowired MetricsCollector metricsCollector; @Autowired TraceCollector traceCollector; @Autowired InstanceInfoCollector instanceInfoCollector; @RequestMapping("") public String getInstanceView(Model model) { Ecosystem ecosystem = ecosystemManager.getEcosystem(); model.addAttribute("microservices", ecosystem.getMicroservices()); model.addAttribute("externalInstances", ecosystem.getExternalInstances()); model.addAttribute("instances", ecosystem.getInstances()); model.addAttribute("microservicesgroups", ecosystem.getMicroservicesGroups()); return INSTANCES_VIEW; } @RequestMapping(value= "/health", method = RequestMethod.POST) @ResponseBody public String checkStatusInstance(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException { return ecosystemManager.getStatusInstance(id); } @RequestMapping(value= "/instanceinfo", method = RequestMethod.POST) @ResponseBody public Microservice getInstanceInfo(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException { return ecosystemManager.getEcosystem().getMicroservices().stream().filter(m-> m.getId().equals(id)).findFirst().get(); } @RequestMapping(value= "/startinstance", method = RequestMethod.POST) @ResponseBody public void startInstance(@RequestParam(value="id") String id, @RequestParam(value="port") String port, @RequestParam(value="vmArguments") String vmArguments) throws CreatingSettingsFolderException, ReadingEcosystemException, RunningMicroserviceScriptException, SavingEcosystemException, InterruptedException { ecosystemManager.startInstance(id, port, vmArguments, 0); } @RequestMapping(value= "/restartinstance", method = RequestMethod.POST) @ResponseBody public void restartInstance(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException, SavingEcosystemException, ShuttingDownInstanceException, InterruptedException { ecosystemManager.restartInstance(id); } @RequestMapping(value= "/killinstance", method = RequestMethod.POST) @ResponseBody public void killInstance(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException, SavingEcosystemException, ShuttingDownInstanceException { ecosystemManager.killInstance(id); } @RequestMapping(value= "/metrics", method = RequestMethod.POST) @ResponseBody public Queue<Metrics> getMetrics(@RequestParam(value="id") String id) { return metricsCollector.getInstanceMetrics(id); } @RequestMapping(value= "/traces", method = RequestMethod.POST) @ResponseBody public List<TraceActuator> getTraces(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException, JSONException { return traceCollector.getTraces(id); } @RequestMapping(value= "/info", method = RequestMethod.POST) @ResponseBody public InstanceGitInfo getInstanceInfoWhenDeployed(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException { return instanceInfoCollector.getInfo(id); } @RequestMapping(value= "/checkport", method = RequestMethod.POST) @ResponseBody public boolean checkPort(@RequestParam(value="port") int port) throws CreatingSettingsFolderException, ReadingEcosystemException { boolean declaredInstanceOnPort = ecosystemManager.getEcosystem().getInstances().stream().anyMatch(i -> i.getPort().equals(String.valueOf(port)));
return declaredInstanceOnPort == false ? PortsChecker.available(port) : false;
4
mike10004/xvfb-manager-java
xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/XvfbManagerTest.java
[ "public class ProcessTrackerRule extends ExternalResource {\n\n private static final Duration DEFAULT_DESTROY_TIMEOUT = Duration.ofMillis(1000);\n\n private final TestWatcher watcher;\n private final AtomicBoolean passage;\n private BasicProcessTracker processTracker;\n private final Duration processDestroyTimeout;\n\n public ProcessTrackerRule() {\n this(DEFAULT_DESTROY_TIMEOUT);\n }\n\n public ProcessTrackerRule(Duration processDestroyTimeout) {\n this.processDestroyTimeout = requireNonNull(processDestroyTimeout, \"processDestroyTimeout\");\n passage = new AtomicBoolean(false);\n watcher = new TestWatcher() {\n @Override\n protected void succeeded(Description description) {\n passage.set(true);\n }\n };\n }\n\n @Override\n public Statement apply(Statement base, Description description) {\n watcher.apply(base, description);\n return super.apply(base, description);\n }\n\n @Override\n protected void before() {\n processTracker = new BasicProcessTracker();\n }\n\n @Override\n protected void after() {\n BasicProcessTracker processTracker = this.processTracker;\n if (processTracker != null) {\n boolean testPassed = passage.get();\n if (testPassed) {\n if (processTracker.activeCount() > 0) {\n System.err.format(\"%d active processes in context%n\", processTracker.activeCount());\n }\n } else {\n processTracker.destroyAll(processDestroyTimeout.toMillis(), TimeUnit.MILLISECONDS);\n assertEquals(\"number of active processes in context must be zero\", 0, processTracker.activeCount());\n }\n }\n }\n\n public ProcessTracker getTracker() {\n return processTracker;\n }\n}", "class XWindow {\n\n /**\n * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.\n */\n public final String id;\n\n /**\n * Window title. Null means the window has no title. The title may also\n * be empty, though that is not common.\n */\n public final @Nullable String title;\n\n /**\n * The line of output from which this window instance was parsed. This is a\n * line from {@code }\n */\n public final String line;\n\n /**\n * Constructs a new instance of the class.\n * @param id window id\n * @param title window title\n * @param line line of output from which this window information was parsed\n */\n public XWindow(String id, @Nullable String title, String line) {\n this.id = id;\n this.title = title;\n this.line = line;\n }\n\n @Override\n public String toString() {\n return \"XWindow{\" +\n \"id=\" + id +\n \", title='\" + title + '\\'' +\n \", length=\" + (line == null ? -1 : line.length()) +\n '}';\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 XWindow xWindow = (XWindow) o;\n\n if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;\n if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;\n return line != null ? line.equals(xWindow.line) : xWindow.line == null;\n }\n\n @Override\n public int hashCode() {\n int result = id != null ? id.hashCode() : 0;\n result = 31 * result + (title != null ? title.hashCode() : 0);\n result = 31 * result + (line != null ? line.hashCode() : 0);\n return result;\n }\n}", "@SuppressWarnings({\"unused\", \"BooleanParameter\"})\npublic class Assumptions {\n\n public static final String SYSPROP_VIOLATIONS_ARE_FATAL = \"Assumptions.fatal\";\n public static final String SYSPROP_ASSUMER = \"Assumptions.assumer\";\n public static final String DEFAULT_ASSUMER = JUnitAssumer.class.getName();\n public static final String FATAL_ASSUMER = FatalAssumer.class.getName();\n\n private static final Supplier<Assumer> assumerSupplier = Suppliers.memoize(new SystemPropertiesAssumerCreator());\n\n static class SystemPropertiesAssumerCreator implements Supplier<Assumer> {\n\n @Override\n public Assumer get() {\n boolean fatal = Boolean.parseBoolean(System.getProperty(SYSPROP_VIOLATIONS_ARE_FATAL, \"false\"));\n String assumerClassname;\n if (fatal) {\n assumerClassname = FATAL_ASSUMER;\n } else {\n assumerClassname = DEFAULT_ASSUMER;\n }\n assumerClassname = System.getProperty(SYSPROP_ASSUMER, assumerClassname);\n try {\n return (Assumer) Class.forName(assumerClassname).newInstance();\n } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {\n throw new AssertionError(\"could not create assumer from system properties\");\n }\n }\n }\n\n\n public static Assumer getAssumer() {\n return assumerSupplier.get();\n }\n\n public static void assumeTrue(boolean b) {\n getAssumer().assumeTrue(b);\n }\n\n public static void assumeFalse(boolean b) {\n getAssumer().assumeFalse(b);\n }\n\n public static void assumeTrue(String message, boolean b) {\n getAssumer().assumeTrue(message, b);\n }\n\n public static void assumeFalse(String message, boolean b) {\n getAssumer().assumeFalse(message, b);\n }\n\n public static void assumeNotNull(Object... objects) {\n getAssumer().assumeNotNull(objects);\n }\n\n public static <T> void assumeThat(T actual, Matcher<T> matcher) {\n getAssumer().assumeThat(actual, matcher);\n }\n\n public static <T> void assumeThat(String message, T actual, Matcher<T> matcher) {\n getAssumer().assumeThat(message, actual, matcher);\n }\n\n public static void assumeNoException(Throwable e) {\n getAssumer().assumeNoException(e);\n }\n\n public static void assumeNoException(String message, Throwable e) {\n getAssumer().assumeNoException(message, e);\n }\n}", "public abstract class PackageManager {\n\n private static final Logger log = Logger.getLogger(PackageManager.class.getName());\n\n private final Whicher whicher;\n\n PackageManager() {\n whicher = Whicher.gnu();\n }\n\n public boolean queryCommandExecutable(String command) throws IOException {\n java.util.Optional<File> executable = whicher.which(command);\n return executable.isPresent();\n }\n\n public abstract boolean queryPackageInstalled(String packageName) throws IOException;\n\n public abstract String queryPackageVersion(String packageName) throws IOException;\n\n public boolean checkImageMagickInstalled() throws IOException {\n return queryAllCommandsExecutable(getImageMagickCommands());\n }\n\n public boolean checkPackageVersion(String packageName, int minimumMajor, int minimumMinor) throws IOException {\n return checkPackageVersion(packageName, minimumMajorMinorPredicate(minimumMajor, minimumMinor));\n }\n\n public boolean checkPackageVersion(String packageName, Predicate<String> versionPredicate) throws IOException {\n String version = queryPackageVersion(packageName);\n return versionPredicate.apply(version);\n }\n\n protected static int[] parseMajorMinor(String version) throws IllegalArgumentException {\n Matcher m = Pattern.compile(\"^(?:\\\\d+:)?(\\\\d+)\\\\.(\\\\d+)(?:\\\\D.*)?$\").matcher(version);\n if (m.find()) {\n String majorStr = m.group(1);\n String minorStr = m.group(2);\n checkArgument(!Strings.isNullOrEmpty(majorStr), \"pattern matched but major is null or empty in '%s'\", version);\n checkArgument(!Strings.isNullOrEmpty(minorStr), \"pattern matched but minor is null or empty in '%s'\", version);\n int major = Integer.parseInt(majorStr), minor = Integer.parseInt(minorStr);\n log.finer(String.format(\"version \\\"%s\\\" parsed to (major, minor) = (%d, %d)%n\", version, major, minor));\n return new int[]{major, minor};\n } else {\n throw new IllegalArgumentException(\"version does not match expected pattern: \" + version);\n }\n }\n\n protected static Predicate<String> minimumMajorMinorPredicate(final int minimumMajor, int minimumMinor) {\n return new Predicate<String>() {\n @Override\n public boolean apply(String version) {\n int[] majorMinor;\n try {\n majorMinor = parseMajorMinor(version);\n } catch (IllegalArgumentException e) {\n log.warning(\"could not parse major/minor from version due to \" + e);\n return false;\n }\n int major = majorMinor[0], minor = majorMinor[1];\n return major > minimumMajor || (major >= minimumMajor && minor >= minimumMinor);\n }\n };\n }\n\n private static final Supplier<PackageManager> instanceSupplier = Suppliers.memoize(new Supplier<PackageManager>() {\n\n @Override\n public PackageManager get() {\n Whicher whicher = Whicher.gnu();\n if (whicher.which(\"dpkg\").isPresent()) {\n return new DebianPackageManager();\n } else if (whicher.which(\"dnf\").isPresent()) {\n return new FedoraPackageManager();\n } else {\n Logger.getLogger(PackageManager.class.getName()).warning(\"operating system not fully supported; \" +\n \"will not be able to determine installation status of packages\");\n return new FalseyPackageManager();\n }\n }\n });\n\n public static PackageManager getInstance() {\n return instanceSupplier.get();\n }\n\n private static final ImmutableSet<String> imageMagickCommands = ImmutableSet.of(\"mogrify\", \"identify\", \"convert\");\n\n public static Iterable<String> getImageMagickCommands() {\n return imageMagickCommands;\n }\n\n public boolean queryAutoDisplaySupport() throws IOException {\n // https://stackoverflow.com/questions/2520704/find-a-free-x11-display-number\n return checkPackageVersion(\"xvfb\", 1, 13);\n }\n\n /**\n * Checks whether each of a list of commands has a corresponding executable\n * on the system path with the same name.\n * @param commands the commands\n * @return true iff all commands have corresponding executables\n */\n public boolean queryAllCommandsExecutable(Iterable<String> commands) throws IOException {\n for (String command : commands) {\n if (!queryCommandExecutable(command)) {\n return false;\n }\n }\n return true;\n }\n\n public boolean queryAnyCommandExecutable(Iterable<String> commands) throws IOException {\n for (String command : commands) {\n if (queryCommandExecutable(command)) {\n return true;\n }\n }\n return false;\n }\n\n private static class FalseyPackageManager extends PackageManager {\n\n @Override\n public boolean queryPackageInstalled(String packageName) throws IOException {\n return false;\n }\n\n @Override\n public boolean checkImageMagickInstalled() throws IOException {\n return false;\n }\n\n @Override\n public boolean queryAutoDisplaySupport() throws IOException {\n return false;\n }\n\n @Override\n public boolean checkPackageVersion(String packageName, int minimumMajor, int minimumMinor) throws IOException {\n return false;\n }\n\n @Override\n public boolean checkPackageVersion(String packageName, Predicate<String> versionPredicate) throws IOException {\n return false;\n }\n\n @Override\n public String queryPackageVersion(String packageName) throws IOException {\n throw new IOException(\"unable to determine package version of \" + StringUtils.abbreviate(packageName, 64));\n }\n }\n\n}", "public class XDiagnosticRule extends ExternalResource {\n\n private final PrintStream out;\n private final boolean disabled;\n private volatile Set<Path> directories = null;\n\n public XDiagnosticRule() {\n this(System.out);\n }\n\n public XDiagnosticRule(PrintStream out) {\n this(out, false);\n }\n\n protected XDiagnosticRule(PrintStream out, boolean disabled) {\n this.out = checkNotNull(out);\n this.disabled = disabled;\n }\n\n private static final XDiagnosticRule disabledInstance = new XDiagnosticRule(System.out, true);\n\n public static XDiagnosticRule getDisabledInstance() {\n return disabledInstance;\n }\n\n @Override\n protected void before() throws Throwable {\n if (disabled) {\n return;\n }\n printDotXFiles(\"before\");\n }\n\n @Override\n protected void after() {\n if (disabled) {\n return;\n }\n printDotXFiles(\"after\");\n }\n\n protected Set<Path> getDirectories() {\n if (directories == null) {\n directories = findTempDirectories();\n }\n return directories;\n }\n\n protected void printDotXFiles(String label) {\n Set<Path> directories_ = getDirectories();\n out.format(\"%-10s XDiagnosticRule: printing .X files from %d temp-like directories%n\", label, directories_.size());\n int n = 0;\n for (Path directory : directories_) {\n List<Path> files;\n try {\n files = listDotXFiles(directory);\n } catch (IOException | RuntimeException e) {\n out.format(\"XDiagnosticRule: failed to gather file list from %s due to %s%n\", directory, e);\n e.printStackTrace(out);\n continue;\n }\n for (Path file : files) {\n n++;\n out.format(\" %s%n\", file);\n }\n }\n out.format(\"%-10s XDiagnosticRule: finished printing %d files from %d directories%n\", label, n, directories_.size());\n }\n\n\n protected List<Path> listDotXFiles(Path directory) throws IOException {\n List<Path> files = new ArrayList<>();\n DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>(){\n @Override\n public boolean accept(Path entry) throws IOException {\n return entry.toFile().getName().toLowerCase().startsWith(\".x\");\n }\n };\n try (DirectoryStream<Path> listing = Files.newDirectoryStream(directory, filter)) {\n Iterables.addAll(files, listing);\n }\n return files;\n }\n\n protected Set<Path> findTempDirectories() {\n Set<String> paths = new HashSet<>(3);\n paths.add(\"/tmp\");\n paths.add(FileUtils.getTempDirectory().getAbsolutePath());\n paths.add(System.getProperty(\"java.io.tmpdir\"));\n for (String envVarName : new String[]{\"TMP\", \"TEMP\", \"TEMPDIR\", \"TMPDIR\"}) {\n String envVarValue = System.getenv(envVarName);\n if (envVarValue != null) {\n paths.add(envVarValue);\n }\n }\n return paths.stream()\n .map(p -> new File(FilenameUtils.normalizeNoEndSeparator(p)))\n .filter(f -> f.isDirectory())\n .map(f -> f.toPath()).collect(Collectors.toSet());\n }\n}" ]
import com.galenframework.rainbow4j.Rainbow4J; import com.galenframework.rainbow4j.Spectrum; import com.galenframework.rainbow4j.colorscheme.ColorDistribution; import com.github.mike10004.common.image.ImageInfo; import com.github.mike10004.common.image.ImageInfos; import com.github.mike10004.xvfbunittesthelp.ProcessTrackerRule; import io.github.mike10004.subprocess.ProcessMonitor; import io.github.mike10004.subprocess.ProcessResult; import io.github.mike10004.subprocess.ProcessTracker; import io.github.mike10004.subprocess.Subprocess; import com.github.mike10004.xvfbmanager.XvfbController.XWindow; import com.github.mike10004.xvfbunittesthelp.Assumptions; import com.github.mike10004.xvfbunittesthelp.PackageManager; import com.github.mike10004.xvfbunittesthelp.XDiagnosticRule; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.io.Files; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import javax.annotation.Nullable; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package com.github.mike10004.xvfbmanager; public class XvfbManagerTest { private static final int _PRESUMABLY_VACANT_DISPLAY_NUM = 88; @Rule public ProcessTrackerRule processTrackerRule = new ProcessTrackerRule(); @Rule public XDiagnosticRule diagnostic = Tests.isDiagnosticEnabled() ? new XDiagnosticRule() : XDiagnosticRule.getDisabledInstance(); @Rule public TemporaryFolder tmp = new TemporaryFolder(); @Test public void toDisplayValue() { System.out.println("\ntoDisplayValue\n"); assertEquals("display", ":123", XvfbManager.toDisplayValue(123)); } @Test(expected=IllegalArgumentException.class) public void toDisplayValue_negative() { System.out.println("\ntoDisplayValue_negative\n"); XvfbManager.toDisplayValue(-1); } @BeforeClass public static void checkPrerequisities() throws IOException { PackageManager packageManager = PackageManager.getInstance(); Iterable<String> requiredExecutables = Iterables.concat(Collections.singletonList("Xvfb"), DefaultXvfbController.getRequiredPrograms()); for (String program : requiredExecutables) { boolean installed = packageManager.queryCommandExecutable(program);
Assumptions.assumeTrue(program + " must be installed for these tests to be executed", installed);
2
ppasupat/web-entity-extractor-ACL2014
src/edu/stanford/nlp/semparse/open/model/feature/FeatureTypeHoleBased.java
[ "public class BrownClusterTable {\n public static class Options {\n @Option public String brownClusterFilename = null;\n }\n public static Options opts = new Options();\n\n public static Map<String, String> wordClusterMap;\n public static Map<String, Integer> wordFrequencyMap;\n \n public static void initModels() {\n if (wordClusterMap != null || opts.brownClusterFilename == null || opts.brownClusterFilename.isEmpty()) return;\n Path dataPath = Paths.get(opts.brownClusterFilename);\n LogInfo.logs(\"Reading Brown clusters from %s\", dataPath);\n try (BufferedReader in = Files.newBufferedReader(dataPath, Charset.forName(\"UTF-8\"))) {\n wordClusterMap = new HashMap<>();\n wordFrequencyMap = new HashMap<>();\n String line = null;\n while ((line = in.readLine()) != null) {\n String[] tokens = line.split(\"\\t\");\n wordClusterMap.put(tokens[1], tokens[0].intern());\n wordFrequencyMap.put(tokens[1], Integer.parseInt(tokens[2]));\n }\n } catch (IOException e) {\n LogInfo.fails(\"Cannot load Brown cluster from %s\", dataPath);\n }\n }\n \n public static String getCluster(String word) {\n initModels();\n return wordClusterMap.get(word);\n }\n \n public static String getClusterPrefix(String word, int length) {\n initModels();\n String answer = wordClusterMap.get(word);\n if (answer == null) return null;\n return answer.substring(0, Math.min(length, answer.length()));\n }\n \n public static final int[] DEFAULT_PREFIXES = {4, 6, 10, 20};\n \n public static List<String> getDefaultClusterPrefixes(String cluster) {\n List<String> answer = new ArrayList<>();\n if (cluster != null)\n for (int length : DEFAULT_PREFIXES)\n answer.add(\"[\" + length + \"]\" + cluster.substring(0, Math.min(length, cluster.length())));\n return answer;\n }\n \n public static List<String> getDefaultClusterPrefixesFromWord(String word) {\n return getDefaultClusterPrefixes(getCluster(word));\n }\n \n public static List<String> getDefaultClusterPrefixes(String cluster1, String cluster2) {\n List<String> answer = new ArrayList<>();\n for (int length : DEFAULT_PREFIXES) {\n answer.add(cluster1.substring(0, Math.min(length, cluster1.length()))\n + \"|\" + cluster2.substring(0, Math.min(length, cluster2.length())));\n }\n return answer;\n }\n \n public static int getSmoothedFrequency(String word) {\n initModels();\n Integer frequency = wordFrequencyMap.get(word);\n if (frequency == null) return 1;\n return frequency + 1;\n }\n}", "@JsonIgnoreProperties(ignoreUnknown=true)\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class LingData {\n public static class Options {\n @Option(gloss = \"What CoreNLP annotators to run\")\n public List<String> annotators = Arrays.asList(\"tokenize\", \"ssplit\", \"pos\", \"lemma\", \"ner\");\n\n @Option(gloss = \"Whether to use CoreNLP annotators\")\n public boolean useAnnotators = true;\n\n @Option(gloss = \"Whether to be case sensitive\")\n public boolean caseSensitive = true;\n \n @Option(gloss = \"Linguistic cache filename\")\n public String lingCacheFilename = null;\n \n @Option(gloss = \"Frequency of saving linguistic cache periodically\")\n public int saveLingCacheFrequency = 50000;\n }\n public static Options opts = new Options();\n public static StanfordCoreNLP pipeline = null;\n \n // Update this when changing LingData's structure.\n private static final String VERSION = \"4\";\n \n private static final Set<String> AUX_VERBS = new HashSet<>(Arrays.asList(\n \"is\", \"are\", \"was\", \"were\", \"am\", \"be\", \"been\", \"will\",\n \"shall\", \"have\", \"has\", \"had\", \"would\", \"could\", \"should\", \n \"do\", \"does\", \"did\", \"can\", \"may\", \"might\", \"must\", \"seem\"));\n \n public static final Set<String> OPEN_CLASS_POS_TAGS = new HashSet<>(Arrays.asList(\n \"CD\", \"FW\", \"JJ\", \"JJR\", \"JJS\", \"NN\", \"NNP\", \"NNPS\", \"NNS\", \"RB\",\n \"RBR\", \"RBS\", \"VB\", \"VBD\", \"VBG\", \"VBN\", \"VBP\", \"VBZ\"));\n \n /**\n * OPEN = nouns, general verbs, adjectives, adverbs, numbers\n * AUX = auxiliary verbs (which is a special case of CLOSE)\n * CLOSE = other POS\n */\n public enum POSType { OPEN, AUX, CLOSE };\n\n // Tokenization of input.\n @JsonProperty\n public final List<String> tokens;\n @JsonProperty\n public final List<String> lemmaTokens; // Lemmatized version\n\n // Syntactic information from JavaNLP.\n @JsonProperty\n public final List<String> posTags; // POS tags\n @JsonProperty\n public final List<POSType> posTypes; // type of POS tag\n @JsonProperty\n public final List<String> nerTags; // NER tags\n @JsonProperty\n public final List<String> nerValues; // NER values (contains times, dates, etc.)\n @JsonIgnore\n public final int length;\n\n public LingData(String utterance) {\n // Stanford tokenizer doesn't break hyphens.\n // Replace hyphens with spaces for utterances like\n // \"Spanish-speaking countries\" but not for \"2012-03-28\".\n StringBuilder buf = new StringBuilder(utterance);\n for (int i = 0; i < buf.length(); i++) {\n if (buf.charAt(i) == '-' && (i+1 < buf.length() && Character.isLetter(buf.charAt(i+1))))\n buf.setCharAt(i, ' ');\n }\n utterance = buf.toString();\n \n tokens = new ArrayList<>();\n posTags = new ArrayList<>();\n posTypes = new ArrayList<>();\n nerTags = new ArrayList<>();\n nerValues = new ArrayList<>();\n lemmaTokens = new ArrayList<>();\n\n if (opts.useAnnotators) {\n initModels();\n Annotation annotation = pipeline.process(utterance);\n\n for (CoreLabel token : annotation.get(CoreAnnotations.TokensAnnotation.class)) {\n String word = token.get(TextAnnotation.class);\n String wordLower = word.toLowerCase();\n if (opts.caseSensitive) {\n tokens.add(word);\n } else {\n tokens.add(wordLower);\n }\n String pos = token.get(PartOfSpeechAnnotation.class).intern();\n posTags.add(pos);\n posTypes.add(getPOSType(pos, word));\n \n nerTags.add(token.get(NamedEntityTagAnnotation.class).intern());\n lemmaTokens.add(token.get(LemmaAnnotation.class));\n nerValues.add(token.get(NormalizedNamedEntityTagAnnotation.class));\n }\n \n } else {\n // Create tokens crudely\n for (String token : utterance.trim().split(\"\\\\s+\")) {\n tokens.add(token);\n lemmaTokens.add(token);\n try {\n Double.parseDouble(token);\n posTags.add(\"CD\");\n posTypes.add(POSType.OPEN);\n nerTags.add(\"NUMBER\");\n nerValues.add(token);\n } catch (NumberFormatException e ){\n posTags.add(\"UNK\");\n posTypes.add(POSType.OPEN);\n nerTags.add(\"UNK\");\n nerValues.add(\"UNK\");\n }\n }\n }\n \n this.length = tokens.size();\n }\n \n private static POSType getPOSType(String pos, String word) {\n if (AUX_VERBS.contains(word.toLowerCase()) && pos.charAt(0) == 'V')\n return POSType.AUX;\n if (OPEN_CLASS_POS_TAGS.contains(pos))\n return POSType.OPEN;\n return POSType.CLOSE;\n }\n\n @JsonCreator\n public LingData(@JsonProperty(\"tokens\") List<String> tokens,\n @JsonProperty(\"lemmaTokens\") List<String> lemmaTokens,\n @JsonProperty(\"posTags\") List<String> posTags,\n @JsonProperty(\"posTypes\") List<POSType> posTypes,\n @JsonProperty(\"nerTags\") List<String> nerTags,\n @JsonProperty(\"nerValues\") List<String> nerValues) {\n this.tokens = tokens;\n this.lemmaTokens = lemmaTokens;\n this.posTags = posTags;\n this.posTypes = posTypes;\n this.nerTags = nerTags;\n this.nerValues = nerValues;\n this.length = tokens.size();\n }\n \n public static void initModels() {\n initCoreNLPModels();\n BrownClusterTable.initModels();\n WordVectorTable.initModels();\n FrequencyTable.initModels();\n WordNetClusterTable.initModels();\n QueryTypeTable.initModels();\n }\n\n public static void initCoreNLPModels() {\n if (pipeline != null) return;\n LogInfo.begin_track(\"Initializing Core NLP Models ...\");\n Properties props = new Properties();\n props.put(\"annotators\", String.join(\",\", opts.annotators));\n if (opts.caseSensitive) {\n props.put(\"pos.model\", \"edu/stanford/nlp/models/pos-tagger/english-bidirectional/english-bidirectional-distsim.tagger\");\n props.put(\"ner.model\", \"edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz,edu/stanford/nlp/models/ner/english.conll.4class.distsim.crf.ser.gz\");\n } else {\n props.put(\"pos.model\", \"edu/stanford/nlp/models/pos-tagger/english-caseless-left3words-distsim.tagger\");\n props.put(\"ner.model\", \"edu/stanford/nlp/models/ner/english.all.3class.caseless.distsim.crf.ser.gz,edu/stanford/nlp/models/ner/english.conll.4class.caseless.distsim.crf.ser.gz\");\n }\n pipeline = new StanfordCoreNLP(props);\n LogInfo.end_track();\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 LingData that = (LingData) o;\n if (!lemmaTokens.equals(that.lemmaTokens)) return false;\n if (!nerTags.equals(that.nerTags)) return false;\n if (!posTags.equals(that.posTags)) return false;\n if (!tokens.equals(that.tokens)) return false;\n return true;\n }\n\n // Return a string representing the tokens between start and end.\n public String phrase(int start, int end) {\n return sliceSequence(tokens, start, end);\n }\n public String lemmaPhrase(int start, int end) {\n return sliceSequence(lemmaTokens, start, end);\n }\n\n private static String sliceSequence(List<String> items, int start, int end) {\n if (start >= end) throw new RuntimeException(\"Bad indices\");\n if (end - start == 1) return items.get(start);\n StringBuilder out = new StringBuilder();\n for (int i = start; i < end; i++) {\n if (out.length() > 0) out.append(' ');\n out.append(items.get(i));\n }\n return out.toString();\n }\n\n // If all the tokens in [start, end) have the same nerValues, but not\n // start-1 and end+1 (in other words, [start, end) is maximal), then return\n // the normalizedTag. Example: queryNerTag = \"DATE\".\n public String getNormalizedNerSpan(String queryTag, int start, int end) {\n String value = nerValues.get(start);\n if (!queryTag.equals(nerTags.get(start))) return null;\n if (start-1 >= 0 && value.equals(nerValues.get(start-1))) return null;\n if (end < nerValues.size() && value.equals(nerValues.get(end))) return null;\n for (int i = start+1; i < end; i++)\n if (!value.equals(nerValues.get(i))) return null;\n return value;\n }\n\n public String getCanonicalPos(int index) {\n return getCanonicalPos(posTags.get(index));\n }\n\n private String getCanonicalPos(String pos) {\n if (pos.startsWith(\"N\")) return \"N\";\n if (pos.startsWith(\"V\")) return \"V\";\n if (pos.startsWith(\"W\")) return \"W\";\n return pos;\n }\n \n // ============================================================\n // Caching\n // ============================================================\n \n protected static Map<String, LingData> cache = new ConcurrentHashMap<>();\n \n public static LingData get(String string) {\n LingData data = cache.get(string);\n if (data == null) {\n data = new LingData(string);\n cache.put(string, data);\n if (opts.saveLingCacheFrequency > 0 && cache.size() % opts.saveLingCacheFrequency == 0) {\n LogInfo.logs(\"Linguistic Cache size: %d\", cache.size());\n saveCache();\n }\n }\n return data;\n }\n\n public static LingData getNoCache(String string) {\n LingData data = cache.get(string);\n if (data == null) {\n data = new LingData(string);\n }\n return data;\n }\n \n private static String getCachePath(String version) {\n String path = opts.lingCacheFilename;\n if (path == null) {\n path = \"cache/ling-\" + Main.opts.dataset + \".v\" + version + \".json.gz\";\n }\n new File(path).getParentFile().mkdirs();\n return path;\n }\n \n private static int lastSavedCacheSize = 0; \n \n public synchronized static void saveCache() {\n LogInfo.begin_track(\"Saving linguistic data to cache ...\");\n if (cache.size() == lastSavedCacheSize) {\n LogInfo.log(\"Cache unchanged.\"); // Do nothing\n } else {\n String cachePath = getCachePath(VERSION);\n try (FileOutputStream out = new FileOutputStream(cachePath);\n GZIPOutputStream so = new GZIPOutputStream(out)) {\n out.getChannel().lock();\n ObjectMapper mapper = new ObjectMapper();\n lastSavedCacheSize = cache.size();\n mapper.writeValue(so, cache);\n LogInfo.logs(\"Written cache to %s\", cachePath);\n } catch (Exception e) {\n LogInfo.warnings(\"Cache cannot be saved to %s!\", cachePath);\n LogInfo.warning(e);\n e.printStackTrace();\n }\n }\n LogInfo.end_track();\n }\n\n public static void loadCache() {\n LogInfo.begin_track(\"Loading linguistic data from cache ...\");\n String cachePath = getCachePath(VERSION);\n try (GZIPInputStream si = new GZIPInputStream(new FileInputStream(cachePath))) {\n ObjectMapper mapper = new ObjectMapper();\n cache = mapper.readValue(si, new TypeReference<ConcurrentHashMap<String, LingData>>(){});\n lastSavedCacheSize = cache.size();\n LogInfo.logs(\"Cache loaded from %s\", cachePath);\n } catch (FileNotFoundException e) {\n LogInfo.warnings(\"Cache cannot be loaded: File %s does not exist\", cachePath);\n } catch (Exception e) {\n LogInfo.warnings(\"Cache cannot be loaded: Cache corruped!\");\n LogInfo.warning(e);\n }\n LogInfo.end_track();\n }\n\n // ============================================================\n // Getters\n // ============================================================\n \n /**\n * @param lemmatized\n * whether to use lemmatized tokens\n * @param onlyOpenPOS\n * whether to return only tokens with open-class POS tags (noun, verb, adjective, adverb)\n * @return A set of tokens\n */\n public Set<String> getTokens(boolean lemmatized, boolean onlyOpenPOS) {\n Set<String> answer = new HashSet<>();\n for (int i = 0; i < length; i++) {\n if (!onlyOpenPOS || posTypes.get(i) == POSType.OPEN) {\n if (lemmatized) {\n answer.add(lemmaTokens.get(i));\n } else {\n answer.add(tokens.get(i));\n }\n }\n }\n return answer;\n }\n}", "public class LingUtils {\n \n // Compute an abstraction of a string\n public static String computePhraseShape(String x) {\n StringBuilder buf = new StringBuilder();\n char lastc = 0;\n for (int i = 0; i < x.length(); i++) {\n char c = x.charAt(i);\n if (Character.isDigit(c)) c = '0';\n else if (Character.isLetter(c)) c = Character.isLowerCase(c) ? 'a' : 'A';\n else if (Character.isWhitespace(c) || Character.isSpaceChar(c)) c = ' ';\n if (c != lastc) buf.append(c);\n lastc = c;\n }\n return buf.toString();\n }\n \n /** Collapse consecutive duplicated tokens */\n public static String collapse(String x) {\n return collapse(x.split(\" \"));\n }\n \n /** Collapse consecutive duplicated tokens */\n public static String collapse(String[] x) {\n StringBuilder sb = new StringBuilder();\n String lastToken = \"\";\n for (String token : x) {\n if (!lastToken.equals(token)) {\n sb.append(token).append(\" \");\n lastToken = token;\n }\n }\n return sb.toString().trim();\n }\n \n /** Collapse consecutive duplicated tokens */\n public static String collapse(List<String> x) {\n StringBuilder sb = new StringBuilder();\n String lastToken = \"\";\n for (String token : x) {\n if (!lastToken.equals(token)) {\n sb.append(token).append(\" \");\n lastToken = token;\n }\n }\n return sb.toString().trim();\n }\n \n /** Join into string */\n public static String join(String[] x) {\n StringBuilder sb = new StringBuilder();\n for (String token : x) {\n sb.append(token).append(\" \");\n }\n return sb.toString().trim();\n }\n \n /** Join into string */\n public static String join(List<String> x) {\n StringBuilder sb = new StringBuilder();\n for (String token : x) {\n sb.append(token).append(\" \");\n }\n return sb.toString().trim();\n }\n\n public static final Pattern ALPHANUMERIC = Pattern.compile(\"[A-Za-z0-9]+\");\n \n public static Set<String> getBagOfWords(String string) {\n Set<String> answer = new HashSet<>();\n Matcher matcher = ALPHANUMERIC.matcher(string.replaceAll(\"[0-9]+\", \"0\"));\n while (matcher.find()) {\n answer.add(matcher.group());\n }\n return answer;\n }\n \n public static final Pattern ALPHA_OR_NUMERIC = Pattern.compile(\"[a-z]+|[0-9]+\");\n \n public static List<String> getAlphaOrNumericTokens(String string) {\n List<String> answer = new ArrayList<>();\n Matcher matcher = ALPHA_OR_NUMERIC.matcher(string.toLowerCase());\n while (matcher.find()) {\n answer.add(matcher.group());\n }\n return answer;\n }\n \n public static String whitespaceNormalize(String x) {\n return x.replaceAll(\"\\\\s+\", \" \").trim();\n }\n \n /**\n * Simple normalization. (Include whitespace normalization)\n */\n public static String simpleNormalize(String string) {\n // Remove diacritics\n string = Normalizer.normalize(string, Normalizer.Form.NFD).replaceAll(\"[\\u0300-\\u036F]\", \"\");\n // Special symbols\n string = string\n .replaceAll(\"‚\", \",\")\n .replaceAll(\"„\", \",,\")\n .replaceAll(\"·\", \".\")\n .replaceAll(\"…\", \"...\")\n .replaceAll(\"ˆ\", \"^\")\n .replaceAll(\"˜\", \"~\")\n .replaceAll(\"‹\", \"<\")\n .replaceAll(\"›\", \">\")\n .replaceAll(\"[‘’´`]\", \"'\")\n .replaceAll(\"[“”«»]\", \"\\\"\")\n .replaceAll(\"[•†‡]\", \"\")\n .replaceAll(\"[‐‑–—]\", \"-\")\n .replaceAll(\"[\\\\u2E00-\\\\uFFFF]\", \"\"); // Remove all Han characters\n // Citation\n string = string.replaceAll(\"\\\\[(nb ?)?\\\\d+\\\\]\", \"\");\n string = string.replaceAll(\"\\\\*+$\", \"\");\n // Year in parentheses\n string = string.replaceAll(\"\\\\(\\\\d* ?-? ?\\\\d*\\\\)\", \"\");\n // Outside Quote\n string = string.replaceAll(\"^\\\"(.*)\\\"$\", \"$1\");\n // Numbering\n if (!string.matches(\"^[0-9.]+$\"))\n string = string.replaceAll(\"^\\\\d+\\\\.\", \"\");\n return string.replaceAll(\"\\\\s+\", \" \").trim();\n }\n \n /**\n * More aggressive normalization. (Include simple and whitespace normalization)\n */\n public static String aggressiveNormalize(String string) {\n // Dashed / Parenthesized information\n string = simpleNormalize(string);\n string = string.trim().replaceAll(\"\\\\[[^\\\\]]*\\\\]\", \"\");\n string = string.trim().replaceAll(\"[\\\\u007F-\\\\uFFFF]\", \"\");\n string = string.trim().replaceAll(\" - .*$\", \"\");\n string = string.trim().replaceAll(\"\\\\([^)]*\\\\)$\", \"\");\n return string.replaceAll(\"\\\\s+\", \" \").trim();\n }\n \n /**\n * Normalize text depending on the level.\n * - <= 0 : no normalization\n * - 1 : strip whitespace\n * - 2 : simple\n * - >= 3 : aggressive\n */\n public static String normalize(String string, int level) {\n if (level == 1) return whitespaceNormalize(string);\n if (level == 2) return simpleNormalize(string);\n if (level >= 3) return aggressiveNormalize(string);\n return string;\n }\n \n /**\n * Find the head word of the phrase (lemmatized).\n * The algorithm is approximate, so the answer may be incorrect\n * (especially when there are proper names with prepositions)\n * \n * Algorithm:\n * - If there is a preposition, wh-word, or \"that\", return the last noun preceding it.\n * - Otherwise, return the last non-number token.\n */\n public static String findHeadWord(String phrase, boolean lemmatized) {\n LingData lingData = LingData.get(phrase);\n int index = findHeadWordIndex(phrase);\n if (index >= 0)\n return lemmatized ? lingData.lemmaTokens.get(index) : lingData.tokens.get(index);\n return \"\";\n }\n \n public static String findHeadWord(String phrase) {\n return findHeadWord(phrase, true);\n }\n \n public static int findHeadWordIndex(String phrase) {\n phrase = hackPhrase(phrase);\n LingData lingData = LingData.get(phrase);\n int modifierIndex = -1;\n for (int i = 1; i < lingData.length; i++) {\n String posTag = lingData.posTags.get(i);\n if (\"IN\".equals(posTag) || \"WP\".equals(posTag) || \"WDT\".equals(posTag) || \"TO\".equals(posTag)) {\n modifierIndex = i;\n break;\n }\n }\n if (modifierIndex > 0 && \"O\".equals(lingData.nerTags.get(modifierIndex - 1))) {\n for (int i = modifierIndex - 1; i >= 0; i--) {\n if (lingData.posTags.get(i).charAt(0) == 'N') return i;\n }\n return modifierIndex - 1;\n } else {\n // Find the last non-digit\n for (int i = lingData.length - 1; i >= 0; i--) {\n if (!\"CD\".equals(lingData.posTags.get(i)) && !\"DATE\".equals(lingData.nerTags.get(i))) {\n return i;\n }\n }\n return lingData.length - 1;\n }\n }\n \n private static String hackPhrase(String phrase) {\n phrase = phrase.replaceAll(\" wiki(pedia)?$\", \"\");\n phrase = phrase.replaceAll(\"^(type|name) of \", \"\");\n phrase = phrase.replaceAll(\" (episodes?) (season \\\\d+)$\", \" $1 of $2\");\n return phrase;\n }\n \n /**\n * Find the last word (lemmatized).\n */\n public static String findLastWord(String phrase, boolean lemmatized) {\n LingData lingData = LingData.get(phrase);\n int index = findLastWordIndex(phrase);\n if (index >= 0)\n return lemmatized ? lingData.lemmaTokens.get(index) : lingData.tokens.get(index);\n return \"\";\n }\n \n public static String findLastWord(String phrase) {\n return findLastWord(phrase, true);\n }\n \n public static int findLastWordIndex(String phrase) {\n return LingData.get(phrase).length - 1;\n }\n \n /**\n * Find the last noun (lemmatized).\n */\n public static String findLastNoun(String phrase, boolean lemmatized) {\n LingData lingData = LingData.get(phrase);\n int index = findLastNounIndex(phrase);\n if (index >= 0)\n return lemmatized ? lingData.lemmaTokens.get(index) : lingData.tokens.get(index);\n return \"\";\n }\n \n public static String findLastNoun(String phrase) {\n return findLastNoun(phrase, true);\n }\n \n public static int findLastNounIndex(String phrase) {\n LingData lingData = LingData.get(phrase);\n for (int i = lingData.length - 1; i >= 0 ; i--) {\n if (lingData.posTags.get(i).charAt(0) == 'N')\n return i;\n }\n return -1;\n }\n \n public static void main(String[] args) {\n // Test\n LogInfo.log(simpleNormalize(\"This is a book†[a][1]\"));\n LogInfo.log(aggressiveNormalize(\"This is a book†[a][1]\"));\n LogInfo.log(simpleNormalize(\"Apollo 11 (1969) 「阿波罗」\"));\n LogInfo.log(simpleNormalize(\"\\\"Apollo 11 (1969)\\\"\"));\n LogInfo.log(simpleNormalize(\"“Erdős café – ε’s delight”\"));\n LogInfo.log(aggressiveNormalize(\"“Erdős café – ε’s delight”\"));\n LogInfo.log(simpleNormalize(\"1. 3.14 is Pi\"));\n LogInfo.log(simpleNormalize(\"3.14\"));\n LogInfo.log(simpleNormalize(\"314\"));\n //LogInfo.log(findHeadWord(\"the mentalist episodes season 2\"));\n }\n \n}", "public class Candidate {\n public final Example ex;\n public final CandidateGroup group;\n public final TreePattern pattern;\n public final List<String> predictedEntities;\n public FeatureVector features;\n \n public Candidate(CandidateGroup group, TreePattern pattern) {\n this.pattern = pattern;\n this.group = group;\n group.candidates.add(this);\n // Perform shallow copy\n this.ex = group.ex;\n this.predictedEntities = group.predictedEntities;\n }\n \n public int numEntities() {\n return group.numEntities();\n }\n \n public double getReward() {\n return group.ex.expectedAnswer.reward(this);\n }\n \n public Map<String, Double> getCombinedFeatures() {\n Map<String, Double> map = new HashMap<>();\n features.increment(1, map);\n group.features.increment(1, map);\n return map;\n }\n \n // ============================================================\n // Debug Print\n // ============================================================\n \n public String sampleEntities() {\n return group.sampleEntities();\n }\n \n public String allEntities() {\n return group.allEntities();\n }\n}", "public class CandidateGroup {\n public static class Options {\n @Option(gloss = \"level of entity string normalization when creating candidate group \"\n + \"(0 = none / 1 = whitespace / 2 = simple / 3 = aggressive)\")\n public int lateNormalizeEntities = 2;\n }\n public static Options opts = new Options();\n\n public final Example ex;\n public final List<KNode> selectedNodes;\n public final List<String> predictedEntities;\n final List<Candidate> candidates;\n public FeatureVector features;\n public AveragedWordVector averagedWordVector;\n \n public CandidateGroup(Example ex, List<KNode> selectedNodes) {\n this.ex = ex;\n this.selectedNodes = new ArrayList<>(selectedNodes);\n List<String> entities = new ArrayList<>();\n for (KNode node : selectedNodes) {\n entities.add(LingUtils.normalize(node.fullText, opts.lateNormalizeEntities));\n }\n predictedEntities = new ArrayList<>(entities);\n candidates = new ArrayList<>();\n }\n \n public void initAveragedWordVector() {\n if (averagedWordVector == null)\n averagedWordVector = new AveragedWordVector(predictedEntities);\n }\n \n public int numEntities() {\n return predictedEntities.size();\n }\n \n public int numCandidate() {\n return candidates.size();\n }\n \n public List<Candidate> getCandidates() {\n return Collections.unmodifiableList(candidates);\n }\n \n public Candidate addCandidate(TreePattern pattern) {\n return new Candidate(this, pattern);\n }\n \n public double getReward() {\n return ex.expectedAnswer.reward(this);\n }\n \n // ============================================================\n // Debug Print\n // ============================================================\n \n public String sampleEntities() {\n return StringSampler.sampleEntities(predictedEntities, StringSampler.DEFAULT_LIMIT);\n }\n\n public String allEntities() {\n return StringSampler.sampleEntities(predictedEntities);\n }\n\n}", "public class KNode {\n public enum Type { QUERY, URL, TAG, ATTR, TEXT };\n \n public final Type type;\n public final String value;\n private final List<KNode> children;\n private final List<KNode> attributes;\n \n // fullText == '' if the node is empty\n // fullText == null if the full text is longer than the specified length.\n public final String fullText;\n \n // parent of root node is null\n public final KNode parent;\n \n // depth of root node is 0\n public final int depth;\n \n // timestamps of depth first search (used for firing range features) \n public int timestampIn, timestampOut, timestampInCollapsed;\n\n public KNode(KNode parent, Type type, String value) {\n this(parent, type, value, \"\");\n }\n \n public KNode(KNode parent, Type type, String value, String fullText) {\n this.type = type;\n this.value = value;\n this.children = new ArrayList<>();\n this.attributes = new ArrayList<>();\n this.fullText = fullText;\n \n this.parent = parent;\n if (this.parent == null) {\n this.depth = 0;\n } else {\n this.depth = this.parent.depth + 1;\n if (type == Type.ATTR) {\n this.parent.attributes.add(this);\n } else {\n this.parent.children.add(this);\n }\n }\n }\n \n /**\n * Create a child and return the child.\n */\n public KNode createChild(Type type, String value) {\n return new KNode(this, type, value);\n }\n \n /**\n * Create a child and return the child.\n */\n public KNode createChild(Type type, String value, String fullText) {\n return new KNode(this, type, value, fullText);\n }\n \n /**\n * Create a child using the information from the `original` node and return the child. \n */\n public KNode createChild(KNode original) {\n return new KNode(this, original.type, original.value, original.fullText);\n }\n \n public KNode createAttribute(String attributeName, String attributeValue) {\n KNode attributeNode = createChild(Type.ATTR, attributeName, attributeValue);\n attributeNode.createChild(Type.TEXT, attributeValue, attributeValue);\n return attributeNode;\n }\n \n // Getters\n \n public List<KNode> getChildren() {\n return Collections.unmodifiableList(children);\n }\n \n public List<KNode> getChildrenOfTag(String tag) {\n List<KNode> answer = new ArrayList<>();\n for (KNode child : children) {\n if (child.type == Type.TAG && (tag.equals(child.value) || tag.equals(\"*\"))) {\n answer.add(child);\n }\n }\n return answer;\n }\n \n // The index is 0-based\n public KNode getChildrenOfTag(String tag, int index) {\n int count = 0;\n for (KNode child : children) {\n if (child.type == Type.TAG && (tag.equals(child.value) || tag.equals(\"*\"))) {\n if (count == index) return child;\n count++;\n }\n }\n return null;\n }\n \n public List<KNode> getAttributes() {\n return Collections.unmodifiableList(attributes);\n }\n \n public String getAttribute(String attributeName) {\n for (KNode attributeNode : attributes) {\n if (attributeNode.value.equals(attributeName))\n return attributeNode.fullText;\n }\n return \"\";\n }\n \n public String[] getAttributeList(String attributeName) {\n for (KNode attributeNode : attributes) {\n if (attributeNode.value.equals(attributeName) && !attributeNode.fullText.isEmpty())\n return attributeNode.fullText.split(\" \");\n }\n return new String[0];\n }\n \n // The index is 0-based\n public int getChildIndex() {\n return this.parent.children.indexOf(this);\n }\n \n // The index is 0-based\n public int getChildIndexOfSameTag() {\n int count = 0;\n for (KNode child : this.parent.children) {\n if (child.type == Type.TAG && child.value.equals(this.value)){\n if (child == this) return count;\n count++;\n }\n }\n return -1;\n }\n \n public int countChildren() {\n return this.children.size();\n }\n \n public int countChildren(String tag) {\n int count = 0;\n for (KNode child : children) {\n if (child.type == Type.TAG && child.value.equals(tag)) count++;\n }\n return count;\n }\n \n // Debug Print\n \n public void debugPrint(int indent) {\n LogInfo.logs(StrUtils.repeat(\" \", indent) + \"%s '%s'\", type, value);\n for (KNode child : children) {\n child.debugPrint(indent + 2);\n }\n }\n \n // Timestamp\n \n public void generateTimestamp() {\n generateTimestamp(1);\n generateTimestampInCollapsed(1);\n }\n \n protected int generateTimestamp(int currentTimestamp) {\n timestampIn = currentTimestamp++;\n for (KNode node : children) {\n currentTimestamp = node.generateTimestamp(currentTimestamp);\n }\n timestampOut = currentTimestamp++;\n return currentTimestamp;\n }\n \n protected int generateTimestampInCollapsed(int currentTimestampInCollapsed) {\n timestampInCollapsed = currentTimestampInCollapsed++;\n for (KNode node : children) {\n currentTimestampInCollapsed = node.generateTimestampInCollapsed(currentTimestampInCollapsed);\n }\n return currentTimestampInCollapsed;\n }\n \n}", "public class Multiset<T> {\n protected final HashMap<T, Integer> map = new HashMap<>();\n protected int size = 0;\n\n public void add(T entry) {\n Integer count = map.get(entry);\n if (count == null)\n count = 0;\n map.put(entry, count + 1);\n size++;\n }\n \n public void add(T entry, int incr) {\n Integer count = map.get(entry);\n if (count == null)\n count = 0;\n map.put(entry, count + incr);\n size += incr;\n }\n\n public boolean contains(T entry) {\n return map.containsKey(entry);\n }\n\n public int count(T entry) {\n Integer count = map.get(entry);\n if (count == null)\n count = 0;\n return count;\n }\n\n public Set<T> elementSet() {\n return map.keySet();\n }\n\n public Set<Map.Entry<T, Integer>> entrySet() {\n return map.entrySet();\n }\n\n public int size() {\n return size;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n \n public Multiset<T> getPrunedByCount(int minCount) {\n Multiset<T> pruned = new Multiset<>();\n for (Map.Entry<T, Integer> entry : map.entrySet()) {\n if (entry.getValue() >= minCount)\n pruned.add(entry.getKey(), entry.getValue());\n }\n return pruned;\n }\n}" ]
import java.util.*; import edu.stanford.nlp.semparse.open.ling.BrownClusterTable; import edu.stanford.nlp.semparse.open.ling.LingData; import edu.stanford.nlp.semparse.open.ling.LingUtils; import edu.stanford.nlp.semparse.open.model.candidate.Candidate; import edu.stanford.nlp.semparse.open.model.candidate.CandidateGroup; import edu.stanford.nlp.semparse.open.model.tree.KNode; import edu.stanford.nlp.semparse.open.util.Multiset; import fig.basic.LogInfo; import fig.basic.Option;
package edu.stanford.nlp.semparse.open.model.feature; /** * Fire features based on the existence of holes in the selected nodes (or ancestors). * * This won't work for wildcard PathEntry. */ public class FeatureTypeHoleBased extends FeatureType { public static class Options { @Option public boolean holeUseTag = true; @Option public List<Integer> headerPrefixes = new ArrayList<>(); @Option public boolean headerBinary = false; } public static Options opts = new Options(); @Override public void extract(Candidate candidate) { // Do nothing } @Override public void extract(CandidateGroup group) { extractHoleBasedFeatures(group); } protected void extractHoleBasedFeatures(CandidateGroup group) { if (isAllowedDomain("hole") || isAllowedDomain("header")) {
List<KNode> currentKNodes = group.selectedNodes;
5
Azure/azure-storage-android
microsoft-azure-storage-test/src/com/microsoft/azure/storage/StorageUriTests.java
[ "public interface CloudTests {\n}", "public interface DevFabricTests {\n}", "public interface DevStoreTests {\n}", "public final class CloudBlobContainer {\n\n /**\n * Converts the ACL string to a BlobContainerPermissions object.\n * \n * @param aclString\n * A <code>String</code> which specifies the ACLs to convert.\n * \n * @return A {@link BlobContainerPermissions} object which represents the ACLs.\n */\n static BlobContainerPermissions getContainerAcl(final String aclString) {\n BlobContainerPublicAccessType accessType = BlobContainerPublicAccessType.parse(aclString);\n\n final BlobContainerPermissions retVal = new BlobContainerPermissions();\n retVal.setPublicAccess(accessType);\n\n return retVal;\n }\n\n /**\n * Represents the container metadata.\n */\n protected HashMap<String, String> metadata = new HashMap<String, String>();\n\n /**\n * Holds the container properties.\n */\n BlobContainerProperties properties = new BlobContainerProperties();\n\n /**\n * Holds the name of the container.\n */\n String name;\n\n /**\n * Holds the list of URIs for all locations.\n */\n private StorageUri storageUri;\n\n /**\n * Holds a reference to the associated service client.\n */\n private CloudBlobClient blobServiceClient;\n \n /**\n * Creates an instance of the <code>CloudBlobContainer</code> class using the specified URI. The blob URI should\n * include a SAS token unless anonymous access is to be used.\n * \n * @param uri\n * A <code>java.net.URI</code> object which represents the URI of the container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudBlobContainer(final URI uri) throws StorageException {\n this(new StorageUri(uri));\n }\n\n /**\n * Creates an instance of the <code>CloudBlobContainer</code> class using the specified URI. The blob URI should\n * include a SAS token unless anonymous access is to be used.\n * \n * @param storageUri\n * A {@link StorageUri} object which represents the URI of the container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudBlobContainer(final StorageUri storageUri) throws StorageException {\n this(storageUri, (StorageCredentials) null);\n }\n \n /**\n * Creates an instance of the <code>CloudBlobContainer</code> class using the specified URI and credentials.\n * \n * @param uri\n * A <code>java.net.URI</code> object that represents the absolute URI of the container.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudBlobContainer(final URI uri, final StorageCredentials credentials) throws StorageException {\n this(new StorageUri(uri), credentials);\n }\n\n /**\n * Creates an instance of the <code>CloudBlobContainer</code> class using the specified StorageUri and credentials.\n * \n * @param storageUri\n * A {@link StorageUri} object which represents the absolute StorageUri of the container.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudBlobContainer(final StorageUri storageUri, final StorageCredentials credentials)\n throws StorageException {\n this.parseQueryAndVerify(storageUri, credentials);\n }\n\n /**\n * Creates an instance of the <code>CloudBlobContainer</code> class using the specified name and client.\n * \n * @param containerName\n * A <code>String</code> which represents the name of the container, which must adhere to container\n * naming rules.\n * The container name should not include any path separator characters (/).\n * Container names must be lowercase, between 3-63 characters long and must start with a letter or\n * number. Container names may contain only letters, numbers, and the dash (-) character.\n * @param client\n * A {@link CloudBlobClient} object that represents the associated service client, and that specifies the\n * endpoint for the Blob service. *\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI constructed based on the containerName is invalid.\n * \n * @see <a href=\"http://msdn.microsoft.com/library/azure/dd135715.aspx\">Naming and Referencing Containers, Blobs,\n * and Metadata</a>\n */\n protected CloudBlobContainer(final String containerName, final CloudBlobClient client) throws URISyntaxException,\n StorageException {\n Utility.assertNotNull(\"client\", client);\n Utility.assertNotNull(\"containerName\", containerName);\n\n this.storageUri = PathUtility.appendPathToUri(client.getStorageUri(), containerName);\n this.name = containerName;\n this.blobServiceClient = client;\n }\n\n /**\n * Creates the container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void create() throws StorageException {\n this.create(BlobContainerPublicAccessType.OFF, null /* options */, null /* opContext */);\n }\n\n /**\n * Creates the container using the specified options and operation context.\n *\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void create(BlobRequestOptions options, OperationContext opContext) throws StorageException {\n this.create(BlobContainerPublicAccessType.OFF, options, opContext);\n }\n\n /**\n * Creates the container using the specified options and operation context.\n *\n * @param accessType\n * A {@link BlobContainerPublicAccessType} object that specifies whether data in the container may be\n * accessed publicly and what level of access is to be allowed.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void create(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext opContext) throws StorageException {\n if (accessType == BlobContainerPublicAccessType.UNKNOWN) {\n throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.ARGUMENT_OUT_OF_RANGE_ERROR, \"accessType\", accessType));\n }\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(\n this.blobServiceClient, this, createImpl(options, accessType),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlobContainer, Void> createImpl(\n final BlobRequestOptions options, final BlobContainerPublicAccessType accessType) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, Void> putRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, Void>(\n options, this.getStorageUri()) {\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n final HttpURLConnection request = BlobRequest.createContainer(\n container.getTransformedAddress().getUri(this.getCurrentLocation()), options, context, accessType);\n return request;\n }\n\n @Override\n public void setHeaders(HttpURLConnection connection, CloudBlobContainer container, OperationContext context) {\n BlobRequest.addMetadata(connection, container.metadata, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n // Set attributes\n final BlobContainerAttributes attributes = BlobResponse.getBlobContainerAttributes(\n this.getConnection(), client.isUsePathStyleUris());\n container.properties = attributes.getProperties();\n container.name = attributes.getName();\n if (accessType != null) {\n container.properties.setPublicAccess(accessType);\n }\n else {\n container.properties.setPublicAccess(BlobContainerPublicAccessType.OFF);\n }\n\n return null;\n }\n };\n\n return putRequest;\n }\n\n /**\n * Creates the container if it does not exist.\n * \n * @return <code>true</code> if the container did not already exist and was created; otherwise, <code>false</code>.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public boolean createIfNotExists() throws StorageException {\n return this.createIfNotExists(BlobContainerPublicAccessType.OFF, null /* options */, null /* opContext */);\n }\n\n /**\n * Creates the container if it does not exist, using the specified request options and operation context.\n *\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request.\n * Specifying <code>null</code> will use the default request options from the associated service client\n * ({@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return <code>true</code> if the container did not already exist and was created; otherwise, <code>false</code>.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public boolean createIfNotExists(BlobRequestOptions options, OperationContext opContext) throws StorageException {\n return this.createIfNotExists(BlobContainerPublicAccessType.OFF, options, opContext);\n }\n\n /**\n * Creates the container if it does not exist, using the specified request options and operation context.\n * \n * @param accessType\n * A {@link BlobContainerPublicAccessType} object that specifies whether data in the container may be\n * accessed publicly and what level of access is to be allowed.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request.\n * Specifying <code>null</code> will use the default request options from the associated service client\n * ({@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return <code>true</code> if the container did not already exist and was created; otherwise, <code>false</code>.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public boolean createIfNotExists(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext opContext) throws StorageException {\n if (accessType == BlobContainerPublicAccessType.UNKNOWN) {\n throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.ARGUMENT_OUT_OF_RANGE_ERROR, \"accessType\", accessType));\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n boolean exists = this.exists(true /* primaryOnly */, null /* accessCondition */, options, opContext);\n if (exists) {\n return false;\n }\n else {\n try {\n this.create(accessType, options, opContext);\n return true;\n }\n catch (StorageException e) {\n if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT\n && StorageErrorCodeStrings.CONTAINER_ALREADY_EXISTS.equals(e.getErrorCode())) {\n return false;\n }\n else {\n throw e;\n }\n }\n }\n }\n\n /**\n * Deletes the container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void delete() throws StorageException {\n this.delete(null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Deletes the container using the specified request options and operation context.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the container.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void delete(AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this, deleteImpl(accessCondition, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlobContainer, Void> deleteImpl(\n final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, Void> putRequest =\n new StorageRequest<CloudBlobClient, CloudBlobContainer, Void>(options, this.getStorageUri()) {\n @Override\n public HttpURLConnection buildRequest(\n CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception {\n return BlobRequest.deleteContainer(\n container.getTransformedAddress().getPrimaryUri(), options, context, accessCondition);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n };\n\n return putRequest;\n }\n\n /**\n * Deletes the container if it exists.\n * \n * @return <code>true</code> if the container did not already exist and was created; otherwise, <code>false</code>.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public boolean deleteIfExists() throws StorageException {\n return this.deleteIfExists(null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Deletes the container if it exists using the specified request options and operation context.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the container.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return <code>true</code> if the container existed and was deleted; otherwise, <code>false</code>.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public boolean deleteIfExists(AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n boolean exists = this.exists(true /* primaryOnly */, accessCondition, options, opContext);\n if (exists) {\n try {\n this.delete(accessCondition, options, opContext);\n return true;\n }\n catch (StorageException e) {\n if (e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND\n && StorageErrorCodeStrings.CONTAINER_NOT_FOUND.equals(e.getErrorCode())) {\n return false;\n }\n else {\n throw e;\n }\n }\n }\n else {\n return false;\n }\n }\n\n /**\n * Downloads the container's attributes, which consist of metadata and properties.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void downloadAttributes() throws StorageException {\n this.downloadAttributes(null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Downloads the container's attributes, which consist of metadata and properties, using the specified request\n * options and operation context.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the container.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void downloadAttributes(AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.downloadAttributesImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlobContainer, Void> downloadAttributesImpl(\n final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, Void> getRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n return BlobRequest.getContainerProperties(\n container.getTransformedAddress().getUri(this.getCurrentLocation()), options, context,\n accessCondition);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n // Set attributes\n final BlobContainerAttributes attributes = BlobResponse.getBlobContainerAttributes(\n this.getConnection(), client.isUsePathStyleUris());\n container.metadata = attributes.getMetadata();\n container.properties = attributes.getProperties();\n container.name = attributes.getName();\n return null;\n }\n };\n\n return getRequest;\n }\n\n /**\n * Downloads the permission settings for the container.\n * \n * @return A {@link BlobContainerPermissions} object that represents the container's permissions.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public BlobContainerPermissions downloadPermissions() throws StorageException {\n return this.downloadPermissions(null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Downloads the permissions settings for the container using the specified request options and operation context.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the container.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A {@link BlobContainerPermissions} object that represents the container's permissions.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public BlobContainerPermissions downloadPermissions(AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n downloadPermissionsImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlobContainer, BlobContainerPermissions> downloadPermissionsImpl(\n final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, BlobContainerPermissions> getRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, BlobContainerPermissions>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n return BlobRequest.getAcl(container.getTransformedAddress().getUri(this.getCurrentLocation()), options,\n accessCondition, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public BlobContainerPermissions preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n container.updatePropertiesFromResponse(this.getConnection());\n final String aclString = BlobResponse.getAcl(this.getConnection());\n final BlobContainerPermissions containerAcl = getContainerAcl(aclString);\n container.properties.setPublicAccess(containerAcl.getPublicAccess());\n return containerAcl;\n }\n\n @Override\n public BlobContainerPermissions postProcessResponse(HttpURLConnection connection,\n CloudBlobContainer container, CloudBlobClient client, OperationContext context,\n BlobContainerPermissions containerAcl) throws Exception {\n HashMap<String, SharedAccessBlobPolicy> accessIds = SharedAccessPolicyHandler.getAccessIdentifiers(this\n .getConnection().getInputStream(), SharedAccessBlobPolicy.class);\n\n for (final String key : accessIds.keySet()) {\n containerAcl.getSharedAccessPolicies().put(key, accessIds.get(key));\n }\n\n return containerAcl;\n }\n };\n\n return getRequest;\n }\n\n /**\n * Returns a value that indicates whether the container exists.\n * \n * @return <code>true</code> if the container exists, otherwise <code>false</code>.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public boolean exists() throws StorageException {\n return this.exists(null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Returns a value that indicates whether the container exists, using the specified request options and operation\n * context.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the container.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return <code>true</code> if the container exists, otherwise <code>false</code>.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public boolean exists(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException {\n return this.exists(false, accessCondition, options, opContext);\n }\n\n @DoesServiceRequest\n private boolean exists(final boolean primaryOnly, final AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.existsImpl(primaryOnly, accessCondition, options), options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlobContainer, Boolean> existsImpl(final boolean primaryOnly,\n final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, Boolean> getRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, Boolean>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(primaryOnly ? RequestLocationMode.PRIMARY_ONLY\n : RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n return BlobRequest.getContainerProperties(\n container.getTransformedAddress().getUri(this.getCurrentLocation()), options, context,\n accessCondition);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public Boolean preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_OK) {\n // Set attributes\n final BlobContainerAttributes attributes = BlobResponse.getBlobContainerAttributes(\n this.getConnection(), client.isUsePathStyleUris());\n container.metadata = attributes.getMetadata();\n container.properties = attributes.getProperties();\n container.name = attributes.getName();\n return Boolean.valueOf(true);\n }\n else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {\n return Boolean.valueOf(false);\n }\n else {\n this.setNonExceptionedRetryableFailure(true);\n // return false instead of null to avoid SCA issues\n return false;\n }\n }\n };\n\n return getRequest;\n }\n\n /**\n * Returns a shared access signature for the container. Note this does not contain the leading \"?\".\n * \n * @param policy\n * An {@link SharedAccessBlobPolicy} object that represents the access policy for the shared access\n * signature.\n * @param groupPolicyIdentifier\n * A <code>String</code> which represents the container-level access policy.\n * \n * @return A <code>String</code> which represents a shared access signature for the container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws InvalidKeyException\n * If the key is invalid.\n */\n public String generateSharedAccessSignature(final SharedAccessBlobPolicy policy, final String groupPolicyIdentifier)\n throws InvalidKeyException, StorageException {\n\n return this.generateSharedAccessSignature(\n policy, groupPolicyIdentifier, null /* IP range */, null /* protocols */);\n }\n \n /**\n * Returns a shared access signature for the container. Note this does not contain the leading \"?\".\n * \n * @param policy\n * An {@link SharedAccessBlobPolicy} object that represents the access policy for the shared access\n * signature.\n * @param groupPolicyIdentifier\n * A <code>String</code> which represents the container-level access policy.\n * @param ipRange\n * A {@link IPRange} object containing the range of allowed IP addresses.\n * @param protocols\n * A {@link SharedAccessProtocols} representing the allowed Internet protocols.\n * \n * @return A <code>String</code> which represents a shared access signature for the container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws InvalidKeyException\n * If the key is invalid.\n */\n public String generateSharedAccessSignature(final SharedAccessBlobPolicy policy,\n final String groupPolicyIdentifier, final IPRange ipRange, final SharedAccessProtocols protocols)\n throws InvalidKeyException, StorageException {\n if (!StorageCredentialsHelper.canCredentialsSignRequest(this.blobServiceClient.getCredentials())) {\n final String errorMessage = SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY;\n throw new IllegalArgumentException(errorMessage);\n }\n \n final String resourceName = this.getSharedAccessCanonicalName();\n\n final String signature = SharedAccessSignatureHelper.generateSharedAccessSignatureHashForBlobAndFile(\n policy, null /* SharedAccessBlobHeaders */, groupPolicyIdentifier, resourceName,\n ipRange, protocols, this.blobServiceClient);\n\n final UriQueryBuilder builder = SharedAccessSignatureHelper.generateSharedAccessSignatureForBlobAndFile(policy,\n null /* SharedAccessBlobHeaders */, groupPolicyIdentifier, \"c\", ipRange, protocols, signature);\n\n return builder.toString();\n }\n\n /**\n * Returns a reference to a {@link CloudAppendBlob} object that represents an append blob in this container.\n * \n * @param blobName\n * A <code>String</code> that represents the name of the blob.\n * \n * @return A {@link CloudAppendBlob} object that represents a reference to the specified append blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n public CloudAppendBlob getAppendBlobReference(final String blobName) throws URISyntaxException, StorageException {\n return this.getAppendBlobReference(blobName, null);\n }\n\n /**\n * Returns a reference to a {@link CloudAppendBlob} object that represents an append blob in the container, using the\n * specified snapshot ID.\n * \n * @param blobName\n * A <code>String</code> that represents the name of the blob.\n * @param snapshotID\n * A <code>String</code> that represents the snapshot ID of the blob.\n * \n * @return A {@link CloudAppendBlob} object that represents a reference to the specified append blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n public CloudAppendBlob getAppendBlobReference(final String blobName, final String snapshotID)\n throws URISyntaxException, StorageException {\n return new CloudAppendBlob(blobName, snapshotID, this);\n }\n \n /**\n * Returns a reference to a {@link CloudBlockBlob} object that represents a block blob in this container.\n * \n * @param blobName\n * A <code>String</code> that represents the name of the blob.\n * \n * @return A {@link CloudBlockBlob} object that represents a reference to the specified block blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n public CloudBlockBlob getBlockBlobReference(final String blobName) throws URISyntaxException, StorageException {\n return this.getBlockBlobReference(blobName, null);\n }\n\n /**\n * Returns a reference to a {@link CloudBlockBlob} object that represents a block blob in this container, using the\n * specified snapshot ID.\n * \n * @param blobName\n * A <code>String</code> that represents the name of the blob.\n * @param snapshotID\n * A <code>String</code> that represents the snapshot ID of the blob.\n * \n * @return A {@link CloudBlockBlob} object that represents a reference to the specified block blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n public CloudBlockBlob getBlockBlobReference(final String blobName, final String snapshotID)\n throws URISyntaxException, StorageException {\n return new CloudBlockBlob(blobName, snapshotID, this);\n }\n\n /**\n * Returns a reference to a {@link CloudBlobDirectory} object that represents a virtual blob directory within this\n * container.\n * \n * @param directoryName\n * A <code>String</code> that represents the name of the virtual blob directory. If the root directory\n * (the directory representing the container itself) is desired, use an empty string.\n * @return A {@link CloudBlobDirectory} that represents a virtual blob directory within this container.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n public CloudBlobDirectory getDirectoryReference(String directoryName) throws URISyntaxException {\n Utility.assertNotNull(\"directoryName\", directoryName);\n\n // if the directory name does not end in the delimiter, add the delimiter\n if (!directoryName.isEmpty() && !directoryName.endsWith(this.blobServiceClient.getDirectoryDelimiter())) {\n directoryName = directoryName.concat(this.blobServiceClient.getDirectoryDelimiter());\n }\n\n final StorageUri address = PathUtility.appendPathToUri(this.storageUri, directoryName);\n\n return new CloudBlobDirectory(address, directoryName, this.blobServiceClient, this);\n }\n \n \n /**\n * Gets a reference to a blob in this container. The blob must already exist on the service.\n * \n * Unlike the other get*Reference methods, this method does a service request to retrieve the blob's metadata and \n * properties. The returned blob may be used directly as a CloudBlob or cast using either instanceof or \n * getProperties().getBlobType() to determine its subtype.\n *\n * @param blobName\n * A <code>String</code> that represents the name of the blob.\n *\n * @return A {@link CloudBlob} object that represents a reference to the specified blob.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n @DoesServiceRequest\n public final CloudBlob getBlobReferenceFromServer(final String blobName) throws URISyntaxException, StorageException {\n return this.getBlobReferenceFromServer(blobName, null, null, null, null);\n }\n\n /**\n * Gets a reference to a blob in this container. The blob must already exist on the service.\n * \n * Unlike the other get*Reference methods, this method does a service request to retrieve the blob's metadata and\n * properties. The returned blob may be used directly as a CloudBlob or cast using either instanceof or\n * getProperties().getBlobType() to determine its subtype.\n * \n * @param blobName\n * A <code>String</code> that represents the name of the blob.\n * @param snapshotID\n * A <code>String</code> that represents the snapshot ID of the blob.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A {@link CloudBlob} object that represents a reference to the specified blob.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n @DoesServiceRequest\n public final CloudBlob getBlobReferenceFromServer(final String blobName, final String snapshotID,\n AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext)\n throws URISyntaxException, StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n \n StorageUri blobUri = PathUtility.appendPathToUri(this.getStorageUri(), blobName);\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.getBlobReferenceFromServerImpl(blobName, blobUri, snapshotID, accessCondition, options), options.getRetryPolicyFactory(), opContext);\n }\n \n private StorageRequest<CloudBlobClient, CloudBlobContainer, CloudBlob> getBlobReferenceFromServerImpl(\n final String blobName, final StorageUri blobUri, final String snapshotID, final AccessCondition accessCondition,\n final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, CloudBlob> getRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, CloudBlob>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n StorageUri transformedblobUri = CloudBlobContainer.this.getServiceClient().getCredentials().transformUri(blobUri, context); \n return BlobRequest.getBlobProperties(transformedblobUri.getUri(this.getCurrentLocation()), options, context, accessCondition, snapshotID);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public CloudBlob preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n // Set attributes\n final BlobAttributes retrievedAttributes = BlobResponse.getBlobAttributes(this.getConnection(),\n blobUri, snapshotID);\n\n CloudBlob blob;\n switch (retrievedAttributes.getProperties().getBlobType()) {\n case APPEND_BLOB:\n blob = container.getAppendBlobReference(blobName, snapshotID);\n break;\n \n case BLOCK_BLOB:\n blob = container.getBlockBlobReference(blobName, snapshotID);\n break;\n \n case PAGE_BLOB:\n blob = container.getPageBlobReference(blobName, snapshotID);\n break;\n \n default:\n throw new StorageException(StorageErrorCodeStrings.INCORRECT_BLOB_TYPE,\n SR.INVALID_RESPONSE_RECEIVED, Constants.HeaderConstants.HTTP_UNUSED_306, null, null);\n }\n\n blob.properties = retrievedAttributes.getProperties();\n blob.metadata = retrievedAttributes.getMetadata();\n\n return blob;\n }\n };\n\n return getRequest;\n }\n \n /**\n * Returns the metadata for the container. This value is initialized with the metadata from the queue by a call to\n * {@link #downloadAttributes}, and is set on the queue with a call to {@link #uploadMetadata}.\n * \n * @return A <code>java.util.HashMap</code> object that represents the metadata for the container.\n */\n public HashMap<String, String> getMetadata() {\n return this.metadata;\n }\n\n /**\n * Returns the name of the container.\n * \n * @return A <code>String</code> that represents the name of the container.\n */\n public String getName() {\n return this.name;\n }\n\n /**\n * Returns the list of URIs for all locations.\n * \n * @return A {@link StorageUri} object which represents the list of URIs for all locations..\n */\n public StorageUri getStorageUri() {\n return this.storageUri;\n }\n\n /**\n * Returns a reference to a {@link CloudPageBlob} object that represents a page blob in this container.\n * \n * @param blobName\n * A <code>String</code> that represents the name of the blob.\n * \n * @return A {@link CloudPageBlob} object that represents a reference to the specified page blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n public CloudPageBlob getPageBlobReference(final String blobName) throws URISyntaxException, StorageException {\n return this.getPageBlobReference(blobName, null);\n }\n\n /**\n * Returns a reference to a {@link CloudPageBlob} object that represents a page blob in the container, using the\n * specified snapshot ID.\n * \n * @param blobName\n * A <code>String</code> that represents the name of the blob.\n * @param snapshotID\n * A <code>String</code> that represents the snapshot ID of the blob.\n * \n * @return A {@link CloudPageBlob} object that represents a reference to the specified page blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n public CloudPageBlob getPageBlobReference(final String blobName, final String snapshotID)\n throws URISyntaxException, StorageException {\n return new CloudPageBlob(blobName, snapshotID, this);\n }\n\n /**\n * Returns the properties for the container.\n * \n * @return A {@link BlobContainerProperties} object that represents the properties for the container.\n */\n public BlobContainerProperties getProperties() {\n return this.properties;\n }\n\n /**\n * Returns the Blob service client associated with this container.\n * \n * @return A {@link CloudBlobClient} object that represents the service client associated with this container.\n */\n public CloudBlobClient getServiceClient() {\n return this.blobServiceClient;\n }\n\n /**\n * Returns the canonical name for shared access.\n * \n * @return the canonical name for shared access.\n */\n private String getSharedAccessCanonicalName() {\n String accountName = this.getServiceClient().getCredentials().getAccountName();\n String containerName = this.getName();\n\n return String.format(\"/%s/%s/%s\", SR.BLOB, accountName, containerName);\n }\n\n /**\n * Returns the URI after applying the authentication transformation.\n * \n * @return A <code>java.net.URI</code> object that represents the URI after applying the authentication\n * transformation.\n * \n * @throws IllegalArgumentException\n * If an unexpected value is passed.\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n private StorageUri getTransformedAddress() throws URISyntaxException, StorageException {\n return this.blobServiceClient.getCredentials().transformUri(this.storageUri);\n }\n\n /**\n * Returns the URI for this container.\n * \n * @return The absolute URI to the container.\n */\n public URI getUri() {\n return this.storageUri.getPrimaryUri();\n }\n\n /**\n * Returns an enumerable collection of blob items for the container.\n * \n * @return An enumerable collection of {@link ListBlobItem} objects retrieved lazily that represents the items in\n * this container.\n */\n @DoesServiceRequest\n public Iterable<ListBlobItem> listBlobs() {\n return this.listBlobs(null, false, EnumSet.noneOf(BlobListingDetails.class), null, null);\n }\n\n /**\n * Returns an enumerable collection of blob items for the container whose names begin with the specified prefix.\n * \n * @param prefix\n * A <code>String</code> that represents the blob name prefix. This value must be preceded either by the\n * name of the container or by the absolute path to the container.\n * \n * @return An enumerable collection of {@link ListBlobItem} objects retrieved lazily that represents the\n * items whose names begin with the specified prefix in this container.\n */\n @DoesServiceRequest\n public Iterable<ListBlobItem> listBlobs(final String prefix) {\n return this.listBlobs(prefix, false);\n }\n \n /**\n * Returns an enumerable collection of blob items for the container whose names begin with the specified prefix\n * using the specified flat or hierarchical option.\n * \n * @param prefix\n * A <code>String</code> that represents the blob name prefix. This value must be preceded either by the\n * name of the container or by the absolute path to the container.\n * @param useFlatBlobListing\n * <code>true</code> to indicate that the returned list will be flat; <code>false</code> to indicate that\n * the returned list will be hierarchical.\n * @return An enumerable collection of {@link ListBlobItem} objects retrieved lazily that represents the\n * items whose names begin with the specified prefix in this container.\n */\n @DoesServiceRequest\n public Iterable<ListBlobItem> listBlobs(final String prefix, final boolean useFlatBlobListing) {\n return this.listBlobs(prefix, useFlatBlobListing, EnumSet.noneOf(BlobListingDetails.class), null, null);\n }\n\n /**\n * Returns an enumerable collection of blob items for the container whose names begin with the specified prefix, \n * using the specified flat or hierarchical option, listing details options, request options, and operation context.\n * \n * @param prefix\n * A <code>String</code> that represents the blob name prefix. This value must be preceded either by the\n * name of the container or by the absolute path to the container.\n * @param useFlatBlobListing\n * <code>true</code> to indicate that the returned list will be flat; <code>false</code> to indicate that\n * the returned list will be hierarchical.\n * @param listingDetails\n * A <code>java.util.EnumSet</code> object that contains {@link BlobListingDetails} values that indicate\n * whether snapshots, metadata, and/or uncommitted blocks are returned. Committed blocks are always\n * returned.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * @return An enumerable collection of {@link ListBlobItem} objects retrieved lazily that represents the\n * items whose names begin with the specified prefix in this container.\n */\n @DoesServiceRequest\n public Iterable<ListBlobItem> listBlobs(final String prefix, final boolean useFlatBlobListing,\n final EnumSet<BlobListingDetails> listingDetails, BlobRequestOptions options, OperationContext opContext) {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n if (!useFlatBlobListing && listingDetails != null && listingDetails.contains(BlobListingDetails.SNAPSHOTS)) {\n throw new IllegalArgumentException(SR.SNAPSHOT_LISTING_ERROR);\n }\n\n SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest();\n\n return new LazySegmentedIterable<CloudBlobClient, CloudBlobContainer, ListBlobItem>(\n this.listBlobsSegmentedImpl(prefix, useFlatBlobListing, listingDetails, null, options, segmentedRequest),\n this.blobServiceClient, this, options.getRetryPolicyFactory(), opContext);\n }\n\n /**\n * Returns a result segment of an enumerable collection of blob items in the container.\n * \n * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of\n * {@link ListBlobItem} objects that represent the blob items in the container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public ResultSegment<ListBlobItem> listBlobsSegmented() throws StorageException {\n return this.listBlobsSegmented(null, false, EnumSet.noneOf(BlobListingDetails.class), null, null, null, null);\n }\n\n /**\n * Returns a result segment containing a collection of blob items whose names begin with the specified prefix.\n * \n * @param prefix\n * A <code>String</code> that represents the prefix of the blob name.\n * \n * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of\n * {@link ListBlobItem} objects that represent the blob items whose names begin with the specified prefix in\n * the container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public ResultSegment<ListBlobItem> listBlobsSegmented(final String prefix) throws StorageException {\n return this.listBlobsSegmented(prefix, false, EnumSet.noneOf(BlobListingDetails.class), null, null, null, null);\n }\n\n /**\n * Returns a result segment containing a collection of blob items whose names begin with the\n * specified prefix, using the specified flat or hierarchical option, listing details options,\n * request options, and operation context.\n * \n * @param prefix\n * A <code>String</code> that represents the prefix of the blob name.\n * @param useFlatBlobListing\n * <code>true</code> to indicate that the returned list will be flat;\n * <code>false</code> to indicate that the returned list will be hierarchical.\n * @param listingDetails\n * A <code>java.util.EnumSet</code> object that contains {@link BlobListingDetails} \n * values that indicate whether snapshots, metadata, and/or uncommitted blocks\n * are returned. Committed blocks are always returned.\n * @param maxResults\n * The maximum number of results to retrieve. If <code>null</code> or greater\n * than 5000, the server will return up to 5,000 items. Must be at least 1.\n * @param continuationToken\n * A {@link ResultContinuation} object that represents a continuation token returned\n * by a previous listing operation.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the\n * request. Specifying <code>null</code> will use the default request options from\n * the associated service client ({@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current\n * operation. This object is used to track requests to the storage service,\n * and to provide additional runtime information about the operation.\n * \n * @return A {@link ResultSegment} object that contains a segment of the enumerable collection\n * of {@link ListBlobItem} objects that represent the block items whose names begin\n * with the specified prefix in the container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public ResultSegment<ListBlobItem> listBlobsSegmented(final String prefix, final boolean useFlatBlobListing,\n final EnumSet<BlobListingDetails> listingDetails, final Integer maxResults,\n final ResultContinuation continuationToken, BlobRequestOptions options, OperationContext opContext)\n throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n Utility.assertContinuationType(continuationToken, ResultContinuationType.BLOB);\n\n if (!useFlatBlobListing && listingDetails != null && listingDetails.contains(BlobListingDetails.SNAPSHOTS)) {\n throw new IllegalArgumentException(SR.SNAPSHOT_LISTING_ERROR);\n }\n\n SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest();\n segmentedRequest.setToken(continuationToken);\n\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.listBlobsSegmentedImpl(prefix,\n useFlatBlobListing, listingDetails, maxResults, options, segmentedRequest), options\n .getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlobContainer, ResultSegment<ListBlobItem>> listBlobsSegmentedImpl(\n final String prefix, final boolean useFlatBlobListing, final EnumSet<BlobListingDetails> listingDetails,\n final Integer maxResults, final BlobRequestOptions options, final SegmentedStorageRequest segmentedRequest) {\n\n Utility.assertContinuationType(segmentedRequest.getToken(), ResultContinuationType.BLOB);\n Utility.assertNotNull(\"options\", options);\n\n final String delimiter = useFlatBlobListing ? null : this.blobServiceClient.getDirectoryDelimiter();\n\n final BlobListingContext listingContext = new BlobListingContext(prefix, maxResults, delimiter, listingDetails);\n\n final StorageRequest<CloudBlobClient, CloudBlobContainer, ResultSegment<ListBlobItem>> getRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, ResultSegment<ListBlobItem>>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(Utility.getListingLocationMode(segmentedRequest.getToken()));\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n listingContext.setMarker(segmentedRequest.getToken() != null ? segmentedRequest.getToken()\n .getNextMarker() : null);\n return BlobRequest.listBlobs(container.getTransformedAddress().getUri(this.getCurrentLocation()),\n options, context, listingContext);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public ResultSegment<ListBlobItem> preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n\n @Override\n public ResultSegment<ListBlobItem> postProcessResponse(HttpURLConnection connection,\n CloudBlobContainer container, CloudBlobClient client, OperationContext context,\n ResultSegment<ListBlobItem> storageObject) throws Exception {\n final ListBlobsResponse response = BlobListHandler.getBlobList(connection.getInputStream(), container);\n\n ResultContinuation newToken = null;\n\n if (response.getNextMarker() != null) {\n newToken = new ResultContinuation();\n newToken.setNextMarker(response.getNextMarker());\n newToken.setContinuationType(ResultContinuationType.BLOB);\n newToken.setTargetLocation(this.getResult().getTargetLocation());\n }\n\n final ResultSegment<ListBlobItem> resSegment = new ResultSegment<ListBlobItem>(response.getResults(),\n response.getMaxResults(), newToken);\n\n // Important for listBlobs because this is required by the lazy iterator between executions.\n segmentedRequest.setToken(resSegment.getContinuationToken());\n\n return resSegment;\n }\n };\n\n return getRequest;\n }\n\n /**\n * Returns an enumerable collection of containers for the service client associated with this container.\n * \n * @return An enumerable collection of {@link CloudBlobContainer} objects retrieved lazily that represent the\n * containers for the service client associated with this container.\n */\n @DoesServiceRequest\n public Iterable<CloudBlobContainer> listContainers() {\n return this.blobServiceClient.listContainers();\n }\n\n /**\n * Returns an enumerable collection of containers whose names begin with the specified prefix for the service client\n * associated with this container.\n * \n * @param prefix\n * A <code>String</code> that represents the container name prefix.\n * \n * @return An enumerable collection of {@link CloudBlobContainer} objects retrieved lazily that represent the\n * containers whose names begin with the specified prefix for the service client associated with this\n * container.\n */\n @DoesServiceRequest\n public Iterable<CloudBlobContainer> listContainers(final String prefix) {\n return this.blobServiceClient.listContainers(prefix);\n }\n\n /**\n * Returns an enumerable collection of containers whose names begin with the specified prefix for the service client\n * associated with this container, using the specified details setting, request options, and operation context.\n * \n * @param prefix\n * A <code>String</code> that represents the container name prefix.\n * @param detailsIncluded\n * A {@link ContainerListingDetails} value that indicates whether container metadata will be returned.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return An enumerable collection of {@link CloudBlobContainer} objects retrieved lazily that represents the\n * containers for the\n * service client associated with this container.\n */\n @DoesServiceRequest\n public Iterable<CloudBlobContainer> listContainers(final String prefix,\n final ContainerListingDetails detailsIncluded, final BlobRequestOptions options,\n final OperationContext opContext) {\n return this.blobServiceClient.listContainers(prefix, detailsIncluded, options, opContext);\n }\n\n /**\n * Returns a result segment of an enumerable collection of containers for the service client associated with this\n * container.\n * \n * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of\n * {@link CloudBlobContainer} objects that represent the containers for the service client associated with\n * this container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public ResultSegment<CloudBlobContainer> listContainersSegmented() throws StorageException {\n return this.blobServiceClient.listContainersSegmented();\n }\n\n /**\n * Returns a result segment of an enumerable collection of containers whose names begin with the specified prefix\n * for the service client associated with this container.\n * \n * @param prefix\n * A <code>String</code> that represents the blob name prefix.\n * \n * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of\n * {@link CloudBlobContainer} objects that represent the containers whose names begin with the specified\n * prefix for the service client associated with this container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public ResultSegment<CloudBlobContainer> listContainersSegmented(final String prefix) throws StorageException {\n return this.blobServiceClient.listContainersSegmented(prefix);\n }\n\n /**\n * Returns a result segment containing a collection of containers whose names begin with\n * the specified prefix for the service client associated with this container,\n * using the specified listing details options, request options, and operation context.\n * \n * @param prefix\n * A <code>String</code> that represents the prefix of the container name.\n * @param detailsIncluded\n * A {@link ContainerListingDetails} object that indicates whether metadata is included.\n * @param maxResults\n * The maximum number of results to retrieve. If <code>null</code> or greater\n * than 5000, the server will return up to 5,000 items. Must be at least 1.\n * @param continuationToken\n * A {@link ResultContinuation} object that represents a continuation token\n * returned by a previous listing operation.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the\n * request. Specifying <code>null</code> will use the default request options from\n * the associated service client ( {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current\n * operation. This object is used to track requests to the storage service,\n * and to provide additional runtime information about the operation.\n * \n * @return A {@link ResultSegment} object that contains a segment of the enumerable collection\n * of {@link CloudBlobContainer} objects that represent the containers whose names\n * begin with the specified prefix for the service client associated with this container.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * \n */\n @DoesServiceRequest\n public ResultSegment<CloudBlobContainer> listContainersSegmented(final String prefix,\n final ContainerListingDetails detailsIncluded, final Integer maxResults,\n final ResultContinuation continuationToken, final BlobRequestOptions options,\n final OperationContext opContext) throws StorageException {\n return this.blobServiceClient.listContainersSegmented(prefix, detailsIncluded, maxResults, continuationToken,\n options, opContext);\n }\n\n /**\n * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.\n * \n * @param completeUri\n * A {@link StorageUri} object which represents the complete URI.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * @throws StorageException\n * If a storage service error occurred.\n */\n private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials)\n throws StorageException {\n Utility.assertNotNull(\"completeUri\", completeUri);\n\n if (!completeUri.isAbsolute()) {\n throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));\n }\n\n this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);\n \n final StorageCredentialsSharedAccessSignature parsedCredentials = \n SharedAccessSignatureHelper.parseQuery(completeUri);\n\n if (credentials != null && parsedCredentials != null) {\n throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);\n }\n\n try {\n final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());\n this.blobServiceClient = new CloudBlobClient(PathUtility.getServiceClientBaseAddress(\n this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);\n this.name = PathUtility.getContainerNameFromUri(this.storageUri.getPrimaryUri(), usePathStyleUris);\n }\n catch (final URISyntaxException e) {\n throw Utility.generateNewUnexpectedStorageException(e);\n }\n }\n\n void updatePropertiesFromResponse(HttpURLConnection request) {\n // ETag\n this.getProperties().setEtag(request.getHeaderField(Constants.HeaderConstants.ETAG));\n\n // Last Modified\n if (0 != request.getLastModified()) {\n final Calendar lastModifiedCalendar = Calendar.getInstance(Utility.LOCALE_US);\n lastModifiedCalendar.setTimeZone(Utility.UTC_ZONE);\n lastModifiedCalendar.setTime(new Date(request.getLastModified()));\n this.getProperties().setLastModified(lastModifiedCalendar.getTime());\n }\n }\n\n /**\n * Sets the metadata collection of name-value pairs to be set on the container with an {@link #uploadMetadata} call.\n * This collection will overwrite any existing container metadata. If this is set to an empty collection, the\n * container metadata will be cleared on an {@link #uploadMetadata} call.\n * \n * @param metadata\n * A <code>java.util.HashMap</code> object that represents the metadata being assigned to the container.\n */\n public void setMetadata(final HashMap<String, String> metadata) {\n this.metadata = metadata;\n }\n\n /**\n * Sets the list of URIs for all locations.\n * \n * @param storageUri\n * A {@link StorageUri} object which represents the list of URIs for all locations.\n */\n protected void setStorageUri(final StorageUri storageUri) {\n this.storageUri = storageUri;\n }\n\n /**\n * Sets the properties for the container.\n * \n * @param properties\n * A {@link BlobContainerProperties} object that represents the properties being assigned to the\n * container.\n */\n protected void setProperties(final BlobContainerProperties properties) {\n this.properties = properties;\n }\n\n /**\n * Uploads the container's metadata.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadMetadata() throws StorageException {\n this.uploadMetadata(null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Uploads the container's metadata using the specified request options and operation context.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the container.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadMetadata(AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.uploadMetadataImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext);\n\n }\n\n @DoesServiceRequest\n private StorageRequest<CloudBlobClient, CloudBlobContainer, Void> uploadMetadataImpl(\n final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, Void> putRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n return BlobRequest.setContainerMetadata(\n container.getTransformedAddress().getUri(this.getCurrentLocation()),\n options, context, accessCondition);\n }\n\n @Override\n public void setHeaders(HttpURLConnection connection, CloudBlobContainer container, OperationContext context) {\n BlobRequest.addMetadata(connection, container.metadata, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n container.updatePropertiesFromResponse(this.getConnection());\n return null;\n }\n };\n\n return putRequest;\n }\n\n /**\n * Uploads the container's permissions.\n * \n * @param permissions\n * A {@link BlobContainerPermissions} object that represents the permissions to upload.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadPermissions(final BlobContainerPermissions permissions) throws StorageException {\n this.uploadPermissions(permissions, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Uploads the container's permissions using the specified request options and operation context.\n * \n * @param permissions\n * A {@link BlobContainerPermissions} object that represents the permissions to upload.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the container.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadPermissions(final BlobContainerPermissions permissions, final AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException {\n if (permissions.getPublicAccess() == BlobContainerPublicAccessType.UNKNOWN) {\n throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.ARGUMENT_OUT_OF_RANGE_ERROR, \"accessType\", permissions.getPublicAccess()));\n }\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n uploadPermissionsImpl(permissions, accessCondition, options), options.getRetryPolicyFactory(),\n opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlobContainer, Void> uploadPermissionsImpl(\n final BlobContainerPermissions permissions, final AccessCondition accessCondition,\n final BlobRequestOptions options) throws StorageException {\n try {\n final StringWriter outBuffer = new StringWriter();\n SharedAccessPolicySerializer.writeSharedAccessIdentifiersToStream(permissions.getSharedAccessPolicies(),\n outBuffer);\n final byte[] aclBytes = outBuffer.toString().getBytes(Constants.UTF8_CHARSET);\n final StorageRequest<CloudBlobClient, CloudBlobContainer, Void> putRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, Void>(\n options, this.getStorageUri()) {\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n this.setSendStream(new ByteArrayInputStream(aclBytes));\n this.setLength((long) aclBytes.length);\n return BlobRequest.setAcl(container.getTransformedAddress().getUri(this.getCurrentLocation()),\n options, context, accessCondition, permissions.getPublicAccess());\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, aclBytes.length, context);\n }\n\n @Override\n public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n container.updatePropertiesFromResponse(this.getConnection());\n container.getProperties().setPublicAccess(permissions.getPublicAccess());\n return null;\n }\n };\n\n return putRequest;\n }\n catch (IllegalArgumentException e) {\n // The request was not even made. There was an error while trying to write the permissions. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IllegalStateException e) {\n // The request was not even made. There was an error while trying to write the permissions. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IOException e) {\n // The request was not even made. There was an error while trying to write the permissions. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n }\n\n /**\n * Acquires a new infinite lease on the container.\n *\n * @return A <code>String</code> that represents the lease ID.\n *\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public final String acquireLease() throws StorageException {\n return this.acquireLease(null /* leaseTimeInSeconds */, null /* proposedLeaseId */);\n }\n\n /**\n * Acquires a new lease on the container with the specified lease time and proposed lease ID.\n * \n * @param leaseTimeInSeconds\n * An <code>Integer</code> which specifies the span of time for which to acquire the lease, in seconds.\n * If null, an infinite lease will be acquired. If not null, the value must be greater than\n * zero.\n * \n * @param proposedLeaseId\n * A <code>String</code> that represents the proposed lease ID for the new lease,\n * or null if no lease ID is proposed.\n * \n * @return A <code>String</code> that represents the lease ID.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public final String acquireLease(final Integer leaseTimeInSeconds, final String proposedLeaseId)\n throws StorageException {\n return this.acquireLease(leaseTimeInSeconds, proposedLeaseId, null /* accessCondition */, null /* options */,\n null /* opContext */);\n }\n\n /**\n * Acquires a new lease on the container with the specified lease time, proposed lease ID, request\n * options, and operation context.\n * \n * @param leaseTimeInSeconds\n * An <code>Integer</code> which specifies the span of time for which to acquire the lease, in seconds.\n * If null, an infinite lease will be acquired. If not null, the value must be greater than\n * zero.\n * \n * @param proposedLeaseId\n * A <code>String</code> that represents the proposed lease ID for the new lease,\n * or null if no lease ID is proposed.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the container.\n * \n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client\n * ({@link CloudBlobClient}).\n * \n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. The context\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A <code>String</code> that represents the lease ID.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public final String acquireLease(final Integer leaseTimeInSeconds, final String proposedLeaseId,\n final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.acquireLeaseImpl(leaseTimeInSeconds, proposedLeaseId, accessCondition, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlobContainer, String> acquireLeaseImpl(\n final Integer leaseTimeInSeconds, final String proposedLeaseId, final AccessCondition accessCondition,\n final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, String> putRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, String>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n return BlobRequest.leaseContainer(container.getTransformedAddress().getUri(this.getCurrentLocation()),\n options, context, accessCondition, LeaseAction.ACQUIRE, leaseTimeInSeconds, proposedLeaseId,\n null /* breakPeriodInSeconds */);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n\n @Override\n public String preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n container.updatePropertiesFromResponse(this.getConnection());\n\n return BlobResponse.getLeaseID(this.getConnection());\n }\n\n };\n\n return putRequest;\n }\n\n /**\n * Renews an existing lease with the specified access conditions.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the container. The lease\n * ID is required to be set with an access condition.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public final void renewLease(final AccessCondition accessCondition) throws StorageException {\n this.renewLease(accessCondition, null /* options */, null /* opContext */);\n }\n\n /**\n * Renews an existing lease with the specified access conditions, request options, and operation context.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is\n * required to be set with an access condition.\n * \n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client\n * ({@link CloudBlobClient}).\n * \n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. The context\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public final void renewLease(final AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n Utility.assertNotNull(\"accessCondition\", accessCondition);\n Utility.assertNotNullOrEmpty(\"leaseID\", accessCondition.getLeaseID());\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.renewLeaseImpl(accessCondition, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlobContainer, Void> renewLeaseImpl(\n final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, Void> putRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n return BlobRequest.leaseContainer(container.getTransformedAddress().getUri(this.getCurrentLocation()),\n options, context, accessCondition, LeaseAction.RENEW, null /* leaseTimeInSeconds */,\n null /* proposedLeaseId */, null /* breakPeriodInseconds */);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n container.updatePropertiesFromResponse(this.getConnection());\n return null;\n }\n };\n\n return putRequest;\n }\n\n /**\n * Releases the lease on the container.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is\n * required to be set with an access condition.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public final void releaseLease(final AccessCondition accessCondition) throws StorageException {\n this.releaseLease(accessCondition, null /* options */, null /* opContext */);\n }\n\n /**\n * Releases the lease on the container using the specified access conditions, request options, and operation\n * context.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is\n * required to be set with an access condition.\n * \n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client\n * ({@link CloudBlobClient}).\n * \n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. The context\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public final void releaseLease(final AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n Utility.assertNotNull(\"accessCondition\", accessCondition);\n Utility.assertNotNullOrEmpty(\"leaseID\", accessCondition.getLeaseID());\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.releaseLeaseImpl(accessCondition, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlobContainer, Void> releaseLeaseImpl(\n final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, Void> putRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n return BlobRequest.leaseContainer(container.getTransformedAddress().getUri(this.getCurrentLocation()),\n options, context, accessCondition, LeaseAction.RELEASE, null, null, null);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n container.updatePropertiesFromResponse(this.getConnection());\n return null;\n }\n };\n\n return putRequest;\n }\n\n /**\n * Breaks the lease and ensures that another client cannot acquire a new lease until the current lease\n * period has expired.\n * \n * @param breakPeriodInSeconds\n * An <code>Integer</code> which specifies the time to wait, in seconds, until the current lease is\n * broken.\n * If null, the break period is the remainder of the current lease, or zero for infinite leases.\n * \n * @return The time, in seconds, remaining in the lease period.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public final long breakLease(final Integer breakPeriodInSeconds) throws StorageException {\n return this.breakLease(breakPeriodInSeconds, null /* accessCondition */, null, null);\n }\n\n /**\n * Breaks the existing lease, using the specified request options and operation context, and ensures that\n * another client cannot acquire a new lease until the current lease period has expired.\n * \n * @param breakPeriodInSeconds\n * An <code>Integer</code> which specifies the time to wait, in seconds, until the current lease is\n * broken.\n * If null, the break period is the remainder of the current lease, or zero for infinite leases.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client\n * ({@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. The context\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return The time, in seconds, remaining in the lease period.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public final long breakLease(final Integer breakPeriodInSeconds, final AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n if (breakPeriodInSeconds != null) {\n Utility.assertGreaterThanOrEqual(\"breakPeriodInSeconds\", breakPeriodInSeconds, 0);\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.breakLeaseImpl(breakPeriodInSeconds, accessCondition, options), options.getRetryPolicyFactory(),\n opContext);\n }\n\n private final StorageRequest<CloudBlobClient, CloudBlobContainer, Long> breakLeaseImpl(\n final Integer breakPeriodInSeconds, final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, Long> putCmd = new StorageRequest<CloudBlobClient, CloudBlobContainer, Long>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n return BlobRequest.leaseContainer(container.getTransformedAddress().getUri(this.getCurrentLocation()),\n options, context, accessCondition, LeaseAction.BREAK, null, null, breakPeriodInSeconds);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n\n @Override\n public Long preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) {\n this.setNonExceptionedRetryableFailure(true);\n return -1L;\n }\n\n container.updatePropertiesFromResponse(this.getConnection());\n final String leaseTime = BlobResponse.getLeaseTime(this.getConnection());\n return Utility.isNullOrEmpty(leaseTime) ? -1L : Long.parseLong(leaseTime);\n }\n };\n\n return putCmd;\n }\n\n /**\n * Changes the existing lease ID to the proposed lease ID.\n * \n * @param proposedLeaseId\n * A <code>String</code> that represents the proposed lease ID for the new lease,\n * or null if no lease ID is proposed.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is\n * required to be set with an access condition.\n * @return A <code>String</code> that represents the new lease ID.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public final String changeLease(final String proposedLeaseId, final AccessCondition accessCondition)\n throws StorageException {\n return this.changeLease(proposedLeaseId, accessCondition, null, null);\n }\n\n /**\n * Changes the existing lease ID to the proposed lease Id with the specified access conditions, request options,\n * and operation context.\n * \n * @param proposedLeaseId\n * A <code>String</code> that represents the proposed lease ID for the new lease. This cannot be null.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is\n * required to be set with an access condition.\n * \n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client\n * ({@link CloudBlobClient}).\n * \n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. The context\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * @return A <code>String</code> that represents the new lease ID.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public final String changeLease(final String proposedLeaseId, final AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException {\n Utility.assertNotNull(\"proposedLeaseId\", proposedLeaseId);\n Utility.assertNotNull(\"accessCondition\", accessCondition);\n Utility.assertNotNullOrEmpty(\"leaseID\", accessCondition.getLeaseID());\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.changeLeaseImpl(proposedLeaseId, accessCondition, options), options.getRetryPolicyFactory(),\n opContext);\n }\n\n private final StorageRequest<CloudBlobClient, CloudBlobContainer, String> changeLeaseImpl(\n final String proposedLeaseId, final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlobContainer, String> putRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, String>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container,\n OperationContext context) throws Exception {\n return BlobRequest.leaseContainer(container.getTransformedAddress().getUri(this.getCurrentLocation()),\n options, context, accessCondition, LeaseAction.CHANGE, null, proposedLeaseId, null);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n\n @Override\n public String preProcessResponse(CloudBlobContainer container, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n container.updatePropertiesFromResponse(this.getConnection());\n return BlobResponse.getLeaseID(this.getConnection());\n }\n };\n\n return putRequest;\n }\n}", "public final class CloudBlockBlob extends CloudBlob {\n\n /**\n * Creates an instance of the <code>CloudBlockBlob</code> class using the specified absolute URI.\n * \n * @param blobAbsoluteUri\n * A <code>java.net.URI</code> object that represents the absolute URI to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudBlockBlob(final URI blobAbsoluteUri) throws StorageException {\n this(new StorageUri(blobAbsoluteUri));\n }\n\n /**\n * Creates an instance of the <code>CloudBlockBlob</code> class using the specified absolute StorageUri.\n * \n * @param blobAbsoluteUri\n * A {@link StorageUri} object that represents the absolute URI to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudBlockBlob(final StorageUri blobAbsoluteUri) throws StorageException {\n this(blobAbsoluteUri, (StorageCredentials)null);\n }\n\n /**\n * Creates an instance of the <code>CloudBlockBlob</code> class by copying values from another cloud block blob.\n * \n * @param otherBlob\n * A <code>CloudBlockBlob</code> object that represents the block blob to copy.\n */\n public CloudBlockBlob(final CloudBlockBlob otherBlob) {\n super(otherBlob);\n }\n\n /**\n * Creates an instance of the <code>CloudBlockBlob</code> class using the specified absolute URI and credentials.\n * \n * @param blobAbsoluteUri\n * A <code>java.net.URI</code> object that represents the absolute URI to the blob.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudBlockBlob(final URI blobAbsoluteUri, final StorageCredentials credentials) throws StorageException {\n this(new StorageUri(blobAbsoluteUri), credentials);\n }\n\n /**\n * Creates an instance of the <code>CloudBlockBlob</code> class using the specified absolute StorageUri and credentials.\n * \n * @param blobAbsoluteUri\n * A {@link StorageUri} object that represents the absolute StorageUri to the blob.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudBlockBlob(final StorageUri blobAbsoluteUri, final StorageCredentials credentials) throws StorageException {\n this(blobAbsoluteUri, null /* snapshotID */, credentials);\n }\n\n /**\n * Creates an instance of the <code>CloudBlockBlob</code> class using the specified absolute URI, snapshot ID, and\n * credentials.\n * \n * @param blobAbsoluteUri\n * A <code>java.net.URI</code> object that represents the absolute URI to the blob.\n * @param snapshotID\n * A <code>String</code> that represents the snapshot version, if applicable.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudBlockBlob(final URI blobAbsoluteUri, final String snapshotID, final StorageCredentials credentials)\n throws StorageException {\n this(new StorageUri(blobAbsoluteUri), snapshotID, credentials);\n }\n\n /**\n * Creates an instance of the <code>CloudBlockBlob</code> class using the specified absolute StorageUri, snapshot\n * ID, and credentials.\n * \n * @param blobAbsoluteUri\n * A {@link StorageUri} object that represents the absolute StorageUri to the blob.\n * @param snapshotID\n * A <code>String</code> that represents the snapshot version, if applicable.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudBlockBlob(final StorageUri blobAbsoluteUri, final String snapshotID, final StorageCredentials credentials)\n throws StorageException {\n super(BlobType.BLOCK_BLOB, blobAbsoluteUri, snapshotID, credentials);\n }\n \n /**\n * Creates an instance of the <code>CloudBlockBlob</code> class using the specified type, name, snapshot ID, and\n * container.\n *\n * @param blobName\n * Name of the blob.\n * @param snapshotID\n * A <code>String</code> that represents the snapshot version, if applicable.\n * @param container\n * The reference to the parent container.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n protected CloudBlockBlob(String blobName, String snapshotID, CloudBlobContainer container)\n throws URISyntaxException {\n super(BlobType.BLOCK_BLOB, blobName, snapshotID, container);\n }\n \n /**\n * Requests the service to start copying a block blob's contents, properties, and metadata to a new block blob.\n *\n * @param sourceBlob\n * A <code>CloudBlockBlob</code> object that represents the source blob to copy.\n *\n * @return A <code>String</code> which represents the copy ID associated with the copy operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n */\n @DoesServiceRequest\n public final String startCopy(final CloudBlockBlob sourceBlob) throws StorageException, URISyntaxException {\n return this.startCopy(sourceBlob, null /* sourceAccessCondition */,\n null /* destinationAccessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Requests the service to start copying a block blob's contents, properties, and metadata to a new block blob,\n * using the specified access conditions, lease ID, request options, and operation context.\n *\n * @param sourceBlob\n * A <code>CloudBlockBlob</code> object that represents the source blob to copy.\n * @param sourceAccessCondition\n * An {@link AccessCondition} object that represents the access conditions for the source blob.\n * @param destinationAccessCondition\n * An {@link AccessCondition} object that represents the access conditions for the destination blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @return A <code>String</code> which represents the copy ID associated with the copy operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n *\n */\n @DoesServiceRequest\n public final String startCopy(final CloudBlockBlob sourceBlob, final AccessCondition sourceAccessCondition,\n final AccessCondition destinationAccessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException, URISyntaxException {\n Utility.assertNotNull(\"sourceBlob\", sourceBlob);\n\n URI source = sourceBlob.getSnapshotQualifiedUri();\n if (sourceBlob.getServiceClient() != null && sourceBlob.getServiceClient().getCredentials() != null)\n {\n source = sourceBlob.getServiceClient().getCredentials().transformUri(sourceBlob.getSnapshotQualifiedUri());\n }\n\n return this.startCopy(source, sourceAccessCondition, destinationAccessCondition, options, opContext);\n }\n\n /**\n * Requests the service to start copying a file's contents, properties, and metadata to a new block blob.\n *\n * @param sourceFile\n * A <code>CloudFile</code> object that represents the source file to copy.\n *\n * @return A <code>String</code> which represents the copy ID associated with the copy operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n */\n @DoesServiceRequest\n public final String startCopy(final CloudFile sourceFile) throws StorageException, URISyntaxException {\n return this.startCopy(sourceFile, null /* sourceAccessCondition */,\n null /* destinationAccessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Requests the service to start copying a file's contents, properties, and metadata to a new block blob,\n * using the specified access conditions, lease ID, request options, and operation context.\n *\n * @param sourceFile\n * A <code>CloudFile</code> object that represents the source file to copy.\n * @param sourceAccessCondition\n * An {@link AccessCondition} object that represents the access conditions for the source file.\n * @param destinationAccessCondition\n * An {@link AccessCondition} object that represents the access conditions for the destination block blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request.\n * Specifying <code>null</code> will use the default request options from the associated\n * service client ({@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation.\n * This object is used to track requests to the storage service, and to provide additional\n * runtime information about the operation.\n *\n * @return A <code>String</code> which represents the copy ID associated with the copy operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n @DoesServiceRequest\n public final String startCopy(final CloudFile sourceFile, final AccessCondition sourceAccessCondition,\n final AccessCondition destinationAccessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException, URISyntaxException {\n Utility.assertNotNull(\"sourceFile\", sourceFile);\n return this.startCopy(\n sourceFile.getServiceClient().getCredentials().transformUri(sourceFile.getUri()),\n sourceAccessCondition, destinationAccessCondition, options, opContext);\n }\n\n /**\n * Commits a block list to the storage service. In order to be written as part of a blob, a block must have been\n * successfully written to the server in a prior uploadBlock operation.\n * \n * @param blockList\n * An enumerable collection of {@link BlockEntry} objects that represents the list block items being\n * committed. The <code>size</code> field is ignored.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void commitBlockList(final Iterable<BlockEntry> blockList) throws StorageException {\n this.commitBlockList(blockList, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Commits a block list to the storage service using the specified lease ID, request options, and operation context.\n * In order to be written as part of a blob, a block must have been successfully written to the server in a prior\n * uploadBlock operation.\n * \n * @param blockList\n * An enumerable collection of {@link BlockEntry} objects that represents the list block items being\n * committed. The size field is ignored.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void commitBlockList(final Iterable<BlockEntry> blockList, final AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException {\n assertNoWriteOperationForSnapshot();\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.BLOCK_BLOB, this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.commitBlockListImpl(blockList, accessCondition, options, opContext),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlob, Void> commitBlockListImpl(final Iterable<BlockEntry> blockList,\n final AccessCondition accessCondition, final BlobRequestOptions options, final OperationContext opContext)\n throws StorageException {\n\n byte[] blockListBytes;\n try {\n blockListBytes = BlockEntryListSerializer.writeBlockListToStream(blockList, opContext);\n\n final ByteArrayInputStream blockListInputStream = new ByteArrayInputStream(blockListBytes);\n\n // This also marks the stream. Therefore no need to mark it in buildRequest.\n final StreamMd5AndLength descriptor = Utility.analyzeStream(blockListInputStream, -1L, -1L,\n true /* rewindSourceStream */, options.getUseTransactionalContentMD5() /* calculateMD5 */);\n\n final StorageRequest<CloudBlobClient, CloudBlob, Void> putRequest = new StorageRequest<CloudBlobClient, CloudBlob, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlob blob, OperationContext context)\n throws Exception {\n this.setSendStream(blockListInputStream);\n this.setLength(descriptor.getLength());\n return BlobRequest.putBlockList(\n blob.getTransformedAddress(context).getUri(this.getCurrentLocation()), options, context,\n accessCondition, blob.properties);\n }\n\n @Override\n public void setHeaders(HttpURLConnection connection, CloudBlob blob, OperationContext context) {\n BlobRequest.addMetadata(connection, blob.metadata, context);\n\n if (options.getUseTransactionalContentMD5()) {\n connection.setRequestProperty(Constants.HeaderConstants.CONTENT_MD5, descriptor.getMd5());\n }\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, this.getLength(), context);\n }\n\n @Override\n public Void preProcessResponse(CloudBlob blob, CloudBlobClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n blob.updateEtagAndLastModifiedFromResponse(this.getConnection());\n this.getResult().setRequestServiceEncrypted(BaseResponse.isServerRequestEncrypted(this.getConnection()));\n return null;\n }\n\n @Override\n public void recoveryAction(OperationContext context) throws IOException {\n blockListInputStream.reset();\n blockListInputStream.mark(Constants.MAX_MARK_LENGTH);\n }\n };\n\n return putRequest;\n }\n catch (IllegalArgumentException e) {\n // The request was not even made. There was an error while trying to write the block list. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IllegalStateException e) {\n // The request was not even made. There was an error while trying to write the block list. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IOException e) {\n // The request was not even made. There was an error while trying to write the block list. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n }\n\n /**\n * Downloads the committed block list from the block blob.\n * <p>\n * The committed block list includes the list of blocks that have been successfully committed to the block blob. The\n * list of committed blocks is returned in the same order that they were committed to the blob. No block may appear\n * more than once in the committed block list.\n * \n * @return An <code>ArrayList</code> object of {@link BlockEntry} objects that represent the committed list\n * block items downloaded from the block blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public ArrayList<BlockEntry> downloadBlockList() throws StorageException {\n return this.downloadBlockList(BlockListingFilter.COMMITTED, null /* accessCondition */, null /* options */,\n null /* opContext */);\n }\n\n /**\n * Downloads the block list from the block blob using the specified block listing filter, request options, and\n * operation context.\n * <p>\n * The committed block list includes the list of blocks that have been successfully committed to the block blob. The\n * list of committed blocks is returned in the same order that they were committed to the blob. No block may appear\n * more than once in the committed block list.\n * \n * @param blockListingFilter\n * A {@link BlockListingFilter} value that specifies whether to download committed blocks, uncommitted\n * blocks, or all blocks.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return An <code>ArrayList</code> object of {@link BlockEntry} objects that represent the list block items\n * downloaded from the block blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public ArrayList<BlockEntry> downloadBlockList(final BlockListingFilter blockListingFilter,\n final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException {\n Utility.assertNotNull(\"blockListingFilter\", blockListingFilter);\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.BLOCK_BLOB, this.blobServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.downloadBlockListImpl(blockListingFilter, accessCondition, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlob, ArrayList<BlockEntry>> downloadBlockListImpl(\n final BlockListingFilter blockListingFilter, final AccessCondition accessCondition,\n final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlob, ArrayList<BlockEntry>> getRequest = new StorageRequest<CloudBlobClient, CloudBlob, ArrayList<BlockEntry>>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlob blob, OperationContext context)\n throws Exception {\n return BlobRequest.getBlockList(blob.getTransformedAddress(context).getUri(this.getCurrentLocation()),\n options, context, accessCondition, blob.snapshotID, blockListingFilter);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public ArrayList<BlockEntry> preProcessResponse(CloudBlob blob, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n\n @Override\n public ArrayList<BlockEntry> postProcessResponse(HttpURLConnection connection, CloudBlob blob,\n CloudBlobClient client, OperationContext context, ArrayList<BlockEntry> storageObject)\n throws Exception {\n blob.updateEtagAndLastModifiedFromResponse(this.getConnection());\n blob.updateLengthFromResponse(this.getConnection());\n\n return BlockListHandler.getBlockList(this.getConnection().getInputStream());\n }\n };\n\n return getRequest;\n }\n\n /**\n * Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it\n * will be overwritten.\n * <p>\n * To avoid overwriting and instead throw an error, please use the \n * {@link #openOutputStream(AccessCondition, BlobRequestOptions, OperationContext)} overload with the appropriate \n * {@link AccessCondition}.\n * \n * @return A {@link BlobOutputStream} object used to write data to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public BlobOutputStream openOutputStream() throws StorageException {\n return this.openOutputStream(null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Creates and opens an output stream to write data to the block blob using the specified request options and\n * operation context. If the blob already exists on the service, it will be overwritten.\n * <p>\n * To avoid overwriting and instead throw an error, please pass in an {@link AccessCondition} generated using \n * {@link AccessCondition#generateIfNotExistsCondition()}.\n * \n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A {@link BlobOutputStream} object used to write data to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public BlobOutputStream openOutputStream(AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n assertNoWriteOperationForSnapshot();\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.BLOCK_BLOB, this.blobServiceClient, \n false /* setStartTime */);\n \n // TODO: Apply any conditional access conditions up front\n\n return new BlobOutputStream(this, accessCondition, options, opContext);\n }\n\n /**\n * Uploads the source stream data to the block blob. If the blob already exists on the service, it will be \n * overwritten.\n * \n * @param sourceStream\n * An {@link InputStream} object that represents the input stream to write to the block blob.\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream data, or -1 if unknown.\n * \n * @throws IOException\n * If an I/O error occurred.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @Override\n @DoesServiceRequest\n public void upload(final InputStream sourceStream, final long length) throws StorageException, IOException {\n this.upload(sourceStream, length, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Uploads the source stream data to the blob, using the specified lease ID, request options, and operation context.\n * If the blob already exists on the service, it will be overwritten.\n * \n * @param sourceStream\n * An {@link InputStream} object that represents the input stream to write to the block blob.\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream data, or -1 if unknown.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws IOException\n * If an I/O error occurred.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @Override\n @DoesServiceRequest\n public void upload(final InputStream sourceStream, final long length, final AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException {\n if (length < -1) {\n throw new IllegalArgumentException(SR.STREAM_LENGTH_NEGATIVE);\n }\n\n assertNoWriteOperationForSnapshot();\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.BLOCK_BLOB, this.blobServiceClient);\n\n StreamMd5AndLength descriptor = new StreamMd5AndLength();\n descriptor.setLength(length);\n\n if (sourceStream.markSupported()) {\n // Mark sourceStream for current position.\n sourceStream.mark(Constants.MAX_MARK_LENGTH);\n }\n\n // If the stream is rewindable and the length is unknown or we need to\n // set md5, then analyze the stream.\n // Note this read will abort at\n // options.getSingleBlobPutThresholdInBytes() bytes and return\n // -1 as length in which case we will revert to using a stream as it is\n // over the single put threshold.\n if (sourceStream.markSupported()\n && (length < 0 || (options.getStoreBlobContentMD5() && length <= options\n .getSingleBlobPutThresholdInBytes()))) {\n // If the stream is of unknown length or we need to calculate\n // the MD5, then we we need to read the stream contents first\n\n descriptor = Utility.analyzeStream(sourceStream, length, options.getSingleBlobPutThresholdInBytes() + 1,\n true /* rewindSourceStream */, options.getStoreBlobContentMD5());\n\n if (descriptor.getMd5() != null && options.getStoreBlobContentMD5()) {\n this.properties.setContentMD5(descriptor.getMd5());\n }\n }\n\n // If the stream is rewindable, and the length is known and less than\n // threshold the upload in a single put, otherwise use a stream.\n if (sourceStream.markSupported() && descriptor.getLength() != -1\n && descriptor.getLength() < options.getSingleBlobPutThresholdInBytes() + 1) {\n this.uploadFullBlob(sourceStream, descriptor.getLength(), accessCondition, options, opContext);\n }\n else {\n final BlobOutputStream writeStream = this.openOutputStream(accessCondition, options, opContext);\n try {\n writeStream.write(sourceStream, length);\n }\n finally {\n writeStream.close();\n }\n }\n }\n\n /**\n * Uploads a blob in a single operation.\n *\n * @param sourceStream\n * A <code>InputStream</code> object that represents the source stream to upload.\n * @param length\n * The length, in bytes, of the stream, or -1 if unknown.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n protected final void uploadFullBlob(final InputStream sourceStream, final long length,\n final AccessCondition accessCondition, final BlobRequestOptions options, final OperationContext opContext)\n throws StorageException {\n assertNoWriteOperationForSnapshot();\n\n // Mark sourceStream for current position.\n sourceStream.mark(Constants.MAX_MARK_LENGTH);\n\n if (length < 0 || length > BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES) {\n throw new IllegalArgumentException(String.format(SR.INVALID_STREAM_LENGTH,\n BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES / Constants.MB));\n }\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n uploadFullBlobImpl(sourceStream, length, accessCondition, options, opContext),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlob, Void> uploadFullBlobImpl(final InputStream sourceStream,\n final long length, final AccessCondition accessCondition, final BlobRequestOptions options,\n final OperationContext opContext) {\n final StorageRequest<CloudBlobClient, CloudBlob, Void> putRequest = new StorageRequest<CloudBlobClient, CloudBlob, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlob blob, OperationContext context)\n throws Exception {\n this.setSendStream(sourceStream);\n this.setLength(length);\n return BlobRequest.putBlob(blob.getTransformedAddress(opContext).getUri(this.getCurrentLocation()),\n options, opContext, accessCondition, blob.properties, blob.properties.getBlobType(),\n this.getLength());\n }\n\n @Override\n public void setHeaders(HttpURLConnection connection, CloudBlob blob, OperationContext context) {\n BlobRequest.addMetadata(connection, blob.metadata, opContext);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, length, context);\n }\n\n @Override\n public Void preProcessResponse(CloudBlob blob, CloudBlobClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n blob.updateEtagAndLastModifiedFromResponse(this.getConnection());\n this.getResult().setRequestServiceEncrypted(BaseResponse.isServerRequestEncrypted(this.getConnection()));\n return null;\n }\n\n @Override\n public void recoveryAction(OperationContext context) throws IOException {\n sourceStream.reset();\n sourceStream.mark(Constants.MAX_MARK_LENGTH);\n }\n\n @Override\n public void validateStreamWrite(StreamMd5AndLength descriptor) throws StorageException {\n if (this.getLength() != null && this.getLength() != -1) {\n if (length != descriptor.getLength()) {\n throw new StorageException(StorageErrorCodeStrings.INVALID_INPUT, SR.INCORRECT_STREAM_LENGTH,\n HttpURLConnection.HTTP_FORBIDDEN, null, null);\n }\n }\n }\n };\n\n return putRequest;\n }\n \n /**\n * Uploads a block to be committed as part of the block blob, using the specified block ID.\n * \n * @param blockId\n * A <code>String</code> that represents the Base-64 encoded block ID. Note for a given blob the length\n * of all Block IDs must be identical.\n * @param sourceStream\n * An {@link InputStream} object that represents the input stream to write to the block blob.\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream data, or -1 if unknown.\n * @throws IOException\n * If an I/O error occurred.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadBlock(final String blockId, final InputStream sourceStream, final long length)\n throws StorageException, IOException {\n this.uploadBlock(blockId, sourceStream, length, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Uploads a block to be committed as part of the block blob, using the specified block ID, the specified lease ID,\n * request options, and operation context.\n * \n * @param blockId\n * A <code>String</code> that represents the Base-64 encoded block ID. Note for a given blob the length\n * of all Block IDs must be identical.\n * @param sourceStream\n * An {@link InputStream} object that represents the input stream to write to the block blob.\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream data, or -1 if unknown.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws IOException\n * If an I/O error occurred.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadBlock(final String blockId, final InputStream sourceStream, final long length,\n final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException, IOException {\n if (length < -1) {\n throw new IllegalArgumentException(SR.STREAM_LENGTH_NEGATIVE);\n }\n\n assertNoWriteOperationForSnapshot();\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.BLOCK_BLOB, this.blobServiceClient);\n\n // Assert block length\n if (Utility.isNullOrEmpty(blockId) || !Base64.validateIsBase64String(blockId)) {\n throw new IllegalArgumentException(SR.INVALID_BLOCK_ID);\n }\n\n if (sourceStream.markSupported()) {\n // Mark sourceStream for current position.\n sourceStream.mark(Constants.MAX_MARK_LENGTH);\n }\n\n InputStream bufferedStreamReference = sourceStream;\n StreamMd5AndLength descriptor = new StreamMd5AndLength();\n descriptor.setLength(length);\n\n if (!sourceStream.markSupported()) {\n // needs buffering\n final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();\n descriptor = Utility.writeToOutputStream(sourceStream, byteStream, length, false /* rewindSourceStream */,\n options.getUseTransactionalContentMD5(), opContext, options);\n\n bufferedStreamReference = new ByteArrayInputStream(byteStream.toByteArray());\n }\n else if (length < 0 || options.getUseTransactionalContentMD5()) {\n // If the stream is of unknown length or we need to calculate the\n // MD5, then we we need to read the stream contents first\n descriptor = Utility.analyzeStream(sourceStream, length, -1L, true /* rewindSourceStream */,\n options.getUseTransactionalContentMD5());\n }\n\n if (descriptor.getLength() > 4 * Constants.MB) {\n throw new IllegalArgumentException(SR.STREAM_LENGTH_GREATER_THAN_4MB);\n }\n\n this.uploadBlockInternal(blockId, descriptor.getMd5(), bufferedStreamReference, descriptor.getLength(),\n accessCondition, options, opContext);\n }\n\n /**\n * Uploads a block of the blob to the server.\n * \n * @param blockId\n * A <code>String</code> which represents the Base64-encoded Block ID.\n * @param md5\n * A <code>String</code> which represents the MD5 to use if it is set.\n * @param sourceStream\n * An {@link InputStream} object to read from.\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream data, or -1 if unknown.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request.\n * @param opContext\n * An {@link OperationContext} object that is used to track the execution of the operation.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n private void uploadBlockInternal(final String blockId, final String md5, final InputStream sourceStream,\n final long length, final AccessCondition accessCondition, final BlobRequestOptions options,\n final OperationContext opContext) throws StorageException {\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n uploadBlockImpl(blockId, md5, sourceStream, length, accessCondition, options, opContext),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlob, Void> uploadBlockImpl(final String blockId, final String md5,\n final InputStream sourceStream, final long length, final AccessCondition accessCondition,\n final BlobRequestOptions options, final OperationContext opContext) {\n\n final StorageRequest<CloudBlobClient, CloudBlob, Void> putRequest = new StorageRequest<CloudBlobClient, CloudBlob, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlob blob, OperationContext context)\n throws Exception {\n this.setSendStream(sourceStream);\n this.setLength(length);\n return BlobRequest.putBlock(blob.getTransformedAddress(opContext).getUri(this.getCurrentLocation()),\n options, opContext, accessCondition, blockId);\n }\n\n @Override\n public void setHeaders(HttpURLConnection connection, CloudBlob blob, OperationContext context) {\n if (options.getUseTransactionalContentMD5()) {\n connection.setRequestProperty(Constants.HeaderConstants.CONTENT_MD5, md5);\n }\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, length, context);\n }\n\n @Override\n public Void preProcessResponse(CloudBlob blob, CloudBlobClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n this.getResult().setRequestServiceEncrypted(BaseResponse.isServerRequestEncrypted(this.getConnection()));\n return null;\n }\n\n @Override\n public void recoveryAction(OperationContext context) throws IOException {\n sourceStream.reset();\n sourceStream.mark(Constants.MAX_MARK_LENGTH);\n }\n };\n\n return putRequest;\n }\n\n /**\n * Uploads a blob from a string using the platform's default encoding. If the blob already exists on the service, it\n * will be overwritten.\n * \n * @param content\n * A <code>String</code> which represents the content that will be uploaded to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws IOException\n */\n public void uploadText(final String content) throws StorageException, IOException {\n this.uploadText(content, null /* charsetName */, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Uploads a blob from a string using the specified encoding. If the blob already exists on the service, it will be \n * overwritten.\n * \n * @param content\n * A <code>String</code> which represents the content that will be uploaded to the blob.\n * @param charsetName\n * A <code>String</code> which represents the name of the charset to use to encode the content.\n * If null, the platform's default encoding is used.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws IOException\n */\n public void uploadText(final String content, final String charsetName, final AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException {\n byte[] bytes = (charsetName == null) ? content.getBytes() : content.getBytes(charsetName);\n this.uploadFromByteArray(bytes, 0, bytes.length, accessCondition, options, opContext);\n }\n\n /**\n * Downloads a blob to a string using the platform's default encoding.\n * \n * @return A <code>String</code> which represents the blob's contents.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws IOException\n */\n public String downloadText() throws StorageException, IOException {\n return this\n .downloadText(null /* charsetName */, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Downloads a blob to a string using the specified encoding.\n * \n * @param charsetName\n * A <code>String</code> which represents the name of the charset to use to encode the content.\n * If null, the platform's default encoding is used.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A <code>String</code> which represents the blob's contents.\n * \n * @throws StorageException\n * If a storage service error occurred.\n * @throws IOException\n */\n public String downloadText(final String charsetName, final AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException {\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n this.download(baos, accessCondition, options, opContext);\n return charsetName == null ? baos.toString() : baos.toString(charsetName);\n }\n\n /**\n * Sets the number of bytes to buffer when writing to a {@link BlobOutputStream}.\n * \n * @param streamWriteSizeInBytes\n * An <code>int</code> which represents the maximum block size, in bytes, for writing to a block blob\n * while using a {@link BlobOutputStream} object, ranging from 16 KB to 4 MB, inclusive.\n * \n * @throws IllegalArgumentException\n * If <code>streamWriteSizeInBytes</code> is less than 16 KB or greater than 4 MB.\n */\n @Override\n public void setStreamWriteSizeInBytes(final int streamWriteSizeInBytes) {\n if (streamWriteSizeInBytes > Constants.MAX_BLOCK_SIZE || streamWriteSizeInBytes < 16 * Constants.KB) {\n throw new IllegalArgumentException(\"StreamWriteSizeInBytes\");\n }\n\n this.streamWriteSizeInBytes = streamWriteSizeInBytes;\n }\n\n /**\n * Sets the blob tier on a block blob on a standard storage account.\n * @param standardBlobTier\n * A {@link StandardBlobTier} object which represents the tier of the blob.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadStandardBlobTier(final StandardBlobTier standardBlobTier) throws StorageException {\n this.uploadStandardBlobTier(standardBlobTier, null /* options */, null /* opContext */);\n }\n\n /**\n * Sets the tier on a block blob on a standard storage account.\n * @param standardBlobTier\n * A {@link StandardBlobTier} object which represents the tier of the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadStandardBlobTier(final StandardBlobTier standardBlobTier, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n assertNoWriteOperationForSnapshot();\n Utility.assertNotNull(\"standardBlobTier\", standardBlobTier);\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.BLOCK_BLOB, this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.uploadBlobTierImpl(standardBlobTier.toString(), options), options.getRetryPolicyFactory(), opContext);\n }\n}", "public final class CloudPageBlob extends CloudBlob {\n /**\n * Creates an instance of the <code>CloudPageBlob</code> class using the specified absolute URI and storage service\n * client.\n * \n * @param blobAbsoluteUri\n * A <code>java.net.URI</code> object which represents the absolute URI to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudPageBlob(final URI blobAbsoluteUri) throws StorageException {\n this(new StorageUri(blobAbsoluteUri));\n }\n\n /**\n * Creates an instance of the <code>CloudPageBlob</code> class using the specified absolute URI and storage service\n * client.\n * \n * @param blobAbsoluteUri\n * A {@link StorageUri} object which represents the absolute URI to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudPageBlob(final StorageUri blobAbsoluteUri) throws StorageException {\n this(blobAbsoluteUri, (StorageCredentials)null);\n }\n\n /**\n * Creates an instance of the <code>CloudPageBlob</code> class by copying values from another page blob.\n * \n * @param otherBlob\n * A <code>CloudPageBlob</code> object which represents the page blob to copy.\n */\n public CloudPageBlob(final CloudPageBlob otherBlob) {\n super(otherBlob);\n }\n \n /**\n * Creates an instance of the <code>CloudPageBlob</code> class using the specified absolute URI and credentials.\n * \n * @param blobAbsoluteUri\n * A <code>java.net.URI</code> object that represents the absolute URI to the blob.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudPageBlob(final URI blobAbsoluteUri, final StorageCredentials credentials) throws StorageException {\n this(new StorageUri(blobAbsoluteUri), credentials);\n }\n\n /**\n * Creates an instance of the <code>CloudPageBlob</code> class using the specified absolute URI, snapshot ID, and\n * credentials.\n * \n * @param blobAbsoluteUri\n * A <code>java.net.URI</code> object that represents the absolute URI to the blob.\n * @param snapshotID\n * A <code>String</code> that represents the snapshot version, if applicable.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudPageBlob(final URI blobAbsoluteUri, final String snapshotID, final StorageCredentials credentials)\n throws StorageException {\n this(new StorageUri(blobAbsoluteUri), snapshotID, credentials);\n }\n \n /**\n * Creates an instance of the <code>CloudPageBlob</code> class using the specified absolute StorageUri and credentials.\n * \n * @param blobAbsoluteUri\n * A {@link StorageUri} object that represents the absolute URI to the blob.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudPageBlob(final StorageUri blobAbsoluteUri, final StorageCredentials credentials) throws StorageException {\n this(blobAbsoluteUri, null /* snapshotID */, credentials);\n }\n\n /**\n * Creates an instance of the <code>CloudPageBlob</code> class using the specified absolute StorageUri, snapshot\n * ID, and credentials.\n * \n * @param blobAbsoluteUri\n * A {@link StorageUri} object that represents the absolute URI to the blob.\n * @param snapshotID\n * A <code>String</code> that represents the snapshot version, if applicable.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudPageBlob(final StorageUri blobAbsoluteUri, final String snapshotID, final StorageCredentials credentials)\n throws StorageException {\n super(BlobType.PAGE_BLOB, blobAbsoluteUri, snapshotID, credentials);\n }\n \n /**\n * Creates an instance of the <code>CloudPageBlob</code> class using the specified type, name, snapshot ID, and\n * container.\n *\n * @param blobName\n * Name of the blob.\n * @param snapshotID\n * A <code>String</code> that represents the snapshot version, if applicable.\n * @param container\n * The reference to the parent container.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n protected CloudPageBlob(String blobName, String snapshotID, CloudBlobContainer container)\n throws URISyntaxException {\n super(BlobType.PAGE_BLOB, blobName, snapshotID, container);\n }\n \n /**\n * Requests the service to start copying a blob's contents, properties, and metadata to a new blob.\n *\n * @param sourceBlob\n * A <code>CloudPageBlob</code> object that represents the source blob to copy.\n *\n * @return A <code>String</code> which represents the copy ID associated with the copy operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n */\n @DoesServiceRequest\n public final String startCopy(final CloudPageBlob sourceBlob) throws StorageException, URISyntaxException {\n return this.startCopy(sourceBlob, null /* sourceAccessCondition */,\n null /* destinationAccessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Requests the service to start copying a blob's contents, properties, and metadata to a new blob, using the\n * specified access conditions, lease ID, request options, and operation context.\n *\n * @param sourceBlob\n * A <code>CloudPageBlob</code> object that represents the source blob to copy.\n * @param sourceAccessCondition\n * An {@link AccessCondition} object that represents the access conditions for the source blob.\n * @param destinationAccessCondition\n * An {@link AccessCondition} object that represents the access conditions for the destination blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @return A <code>String</code> which represents the copy ID associated with the copy operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n *\n */\n @DoesServiceRequest\n public final String startCopy(final CloudPageBlob sourceBlob, final AccessCondition sourceAccessCondition,\n final AccessCondition destinationAccessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException, URISyntaxException {\n return this.startCopy(sourceBlob, null /* premiumBlobTier */, sourceAccessCondition, destinationAccessCondition, options, opContext);\n }\n\n /**\n * Requests the service to start copying a blob's contents, properties, and metadata to a new blob, using the\n * specified blob tier, access conditions, lease ID, request options, and operation context.\n *\n * @param sourceBlob\n * A <code>CloudPageBlob</code> object that represents the source blob to copy.\n * @param premiumBlobTier\n * A {@link PremiumPageBlobTier} object which represents the tier of the blob.\n * @param sourceAccessCondition\n * An {@link AccessCondition} object that represents the access conditions for the source blob.\n * @param destinationAccessCondition\n * An {@link AccessCondition} object that represents the access conditions for the destination blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @return A <code>String</code> which represents the copy ID associated with the copy operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n *\n */\n @DoesServiceRequest\n public final String startCopy(final CloudPageBlob sourceBlob, final PremiumPageBlobTier premiumBlobTier, final AccessCondition sourceAccessCondition,\n final AccessCondition destinationAccessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException, URISyntaxException {\n Utility.assertNotNull(\"sourceBlob\", sourceBlob);\n\n URI source = sourceBlob.getSnapshotQualifiedUri();\n if (sourceBlob.getServiceClient() != null && sourceBlob.getServiceClient().getCredentials() != null)\n {\n source = sourceBlob.getServiceClient().getCredentials().transformUri(sourceBlob.getSnapshotQualifiedUri());\n }\n\n return this.startCopy(source, premiumBlobTier, sourceAccessCondition, destinationAccessCondition, options, opContext);\n }\n\n /**\n * Requests the service to start an incremental copy of another page blob's contents, properties, and metadata\n * to this blob.\n *\n * @param sourceSnapshot\n * A <code>CloudPageBlob</code> object that represents the source blob to copy. Must be a snapshot.\n *\n * @return A <code>String</code> which represents the copy ID associated with the copy operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n */\n @DoesServiceRequest\n public final String startIncrementalCopy(final CloudPageBlob sourceSnapshot) throws StorageException, URISyntaxException {\n final UriQueryBuilder builder = new UriQueryBuilder();\n builder.add(Constants.QueryConstants.SNAPSHOT, sourceSnapshot.snapshotID);\n URI sourceUri = builder.addToURI(sourceSnapshot.getTransformedAddress(null).getPrimaryUri());\n\n return this.startIncrementalCopy(sourceUri, null /* destinationAccessCondition */,\n null /* options */, null /* opContext */);\n }\n\n /**\n * Requests the service to start an incremental copy of another page blob's contents, properties, and metadata\n * to this blob.\n *\n * @param sourceSnapshot\n * A <code>CloudPageBlob</code> object that represents the source blob to copy. Must be a snapshot.\n *\n * @return A <code>String</code> which represents the copy ID associated with the copy operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n */\n @DoesServiceRequest\n public final String startIncrementalCopy(final URI sourceSnapshot) throws StorageException, URISyntaxException {\n return this.startIncrementalCopy(sourceSnapshot, null /* destinationAccessCondition */,\n null /* options */, null /* opContext */);\n }\n\n /**\n * Requests the service to start copying a blob's contents, properties, and metadata to a new blob, using the\n * specified access conditions, lease ID, request options, and operation context.\n *\n * @param sourceSnapshot\n * A <code>CloudPageBlob</code> object that represents the source blob to copy. Must be a snapshot.\n * @param destinationAccessCondition\n * An {@link AccessCondition} object that represents the access conditions for the destination blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @return A <code>String</code> which represents the copy ID associated with the copy operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n *\n */\n @DoesServiceRequest\n public final String startIncrementalCopy(final CloudPageBlob sourceSnapshot, \n final AccessCondition destinationAccessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException, URISyntaxException {\n final UriQueryBuilder builder = new UriQueryBuilder();\n builder.add(Constants.QueryConstants.SNAPSHOT, sourceSnapshot.snapshotID);\n\n URI sourceUri = builder.addToURI(sourceSnapshot.getTransformedAddress(null).getPrimaryUri());\n return this.startIncrementalCopy(sourceUri, destinationAccessCondition, options, opContext);\n }\n\n /**\n * Requests the service to start copying a blob's contents, properties, and metadata to a new blob, using the\n * specified access conditions, lease ID, request options, and operation context.\n *\n * @param sourceSnapshot\n * A <code>CloudPageBlob</code> object that represents the source blob to copy. Must be a snapshot.\n * @param destinationAccessCondition\n * An {@link AccessCondition} object that represents the access conditions for the destination blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @return A <code>String</code> which represents the copy ID associated with the copy operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n *\n */\n @DoesServiceRequest\n public final String startIncrementalCopy(final URI sourceSnapshot,\n final AccessCondition destinationAccessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException, URISyntaxException {\n Utility.assertNotNull(\"sourceSnapshot\", sourceSnapshot);\n this.assertNoWriteOperationForSnapshot();\n \n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, this.properties.getBlobType(), this.blobServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.startCopyImpl(sourceSnapshot, true /* incrementalCopy */, null /* premiumPageBlobTier */, null /* sourceAccesCondition */,\n destinationAccessCondition, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n /**\n * Clears pages from a page blob.\n * <p>\n * Calling <code>clearPages</code> releases the storage space used by the specified pages. Pages that have been\n * cleared are no longer tracked as part of the page blob, and no longer incur a charge against the storage account.\n * \n * @param offset\n * The offset, in bytes, at which to begin clearing pages. This value must be a multiple of 512.\n * @param length\n * The length, in bytes, of the data range to be cleared. This value must be a multiple of 512.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void clearPages(final long offset, final long length) throws StorageException {\n this.clearPages(offset, length, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Clears pages from a page blob using the specified lease ID, request options, and operation context.\n * <p>\n * Calling <code>clearPages</code> releases the storage space used by the specified pages. Pages that have been\n * cleared are no longer tracked as part of the page blob, and no longer incur a charge against the storage account.\n * \n * @param offset\n * A <code>long</code> which represents the offset, in bytes, at which to begin clearing pages. This\n * value must be a multiple of 512.\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the data range to be cleared. This value\n * must be a multiple of 512.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void clearPages(final long offset, final long length, final AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException {\n if (offset % Constants.PAGE_SIZE != 0) {\n throw new IllegalArgumentException(SR.INVALID_PAGE_START_OFFSET);\n }\n\n if (length % Constants.PAGE_SIZE != 0) {\n throw new IllegalArgumentException(SR.INVALID_PAGE_BLOB_LENGTH);\n }\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.PAGE_BLOB, this.blobServiceClient);\n PageRange range = new PageRange(offset, offset + length - 1);\n\n this.putPagesInternal(range, PageOperationType.CLEAR, null, length, null, accessCondition, options, opContext);\n }\n\n /**\n * Creates a page blob. If the blob already exists, this will replace it. To instead throw an error if the blob \n * already exists, use the {@link #create(long, AccessCondition, BlobRequestOptions, OperationContext)}\n * overload with {@link AccessCondition#generateIfNotExistsCondition()}.\n * @param length\n * A <code>long</code> which represents the size, in bytes, of the page blob.\n * \n * @throws IllegalArgumentException\n * If the length is not a multiple of 512.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void create(final long length) throws StorageException {\n this.create(length, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Creates a page blob using the specified request options and operation context. If the blob already exists,\n * this will replace it. To instead throw an error if the blob already exists, use\n * {@link AccessCondition#generateIfNotExistsCondition()}.\n *\n * @param length\n * A <code>long</code> which represents the size, in bytes, of the page blob.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @throws IllegalArgumentException\n * If the length is not a multiple of 512.\n *\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void create(final long length, final AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n this.create(length, null /* premiumBlobTier */, accessCondition, options, opContext);\n }\n\n /**\n * Creates a page blob using the specified request options and operation context. If the blob already exists, \n * this will replace it. To instead throw an error if the blob already exists, use \n * {@link AccessCondition#generateIfNotExistsCondition()}.\n * \n * @param length\n * A <code>long</code> which represents the size, in bytes, of the page blob.\n * @param premiumBlobTier\n * A {@link PremiumPageBlobTier} object which represents the tier of the blob.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws IllegalArgumentException\n * If the length is not a multiple of 512.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void create(final long length, final PremiumPageBlobTier premiumBlobTier, final AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n assertNoWriteOperationForSnapshot();\n\n if (length % Constants.PAGE_SIZE != 0) {\n throw new IllegalArgumentException(SR.INVALID_PAGE_BLOB_LENGTH);\n }\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.PAGE_BLOB, this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.createImpl(length, premiumBlobTier, accessCondition, options), options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlob, Void> createImpl(final long length, final PremiumPageBlobTier premiumBlobTier,\n final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlob, Void> putRequest = new StorageRequest<CloudBlobClient, CloudBlob, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlob blob, OperationContext context)\n throws Exception {\n return BlobRequest.putBlob(blob.getTransformedAddress(context).getUri(this.getCurrentLocation()),\n options, context, accessCondition, blob.properties, BlobType.PAGE_BLOB, length, premiumBlobTier);\n }\n\n @Override\n public void setHeaders(HttpURLConnection connection, CloudBlob blob, OperationContext context) {\n BlobRequest.addMetadata(connection, blob.metadata, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudBlob blob, CloudBlobClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n blob.updateEtagAndLastModifiedFromResponse(this.getConnection());\n this.getResult().setRequestServiceEncrypted(BaseResponse.isServerRequestEncrypted(this.getConnection()));\n blob.getProperties().setLength(length);\n blob.getProperties().setPremiumPageBlobTier(premiumBlobTier);\n if (premiumBlobTier != null) {\n blob.getProperties().setBlobTierInferred(false);\n }\n\n return null;\n }\n\n };\n\n return putRequest;\n }\n\n /**\n * Returns a collection of page ranges and their starting and ending byte offsets.\n * <p>\n * The start and end byte offsets for each page range are inclusive.\n * \n * @return An <code>ArrayList</code> object which represents the set of page ranges and their starting and ending\n * byte offsets.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public ArrayList<PageRange> downloadPageRanges() throws StorageException {\n return this.downloadPageRanges(null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Returns a collection of page ranges and their starting and ending byte offsets using the specified request\n * options and operation context.\n * \n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return An <code>ArrayList</code> object which represents the set of page ranges and their starting and ending\n * byte offsets.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public ArrayList<PageRange> downloadPageRanges(final AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.PAGE_BLOB, this.blobServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.downloadPageRangesImpl(null /* offset */, null /* length */, accessCondition, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n /**\n * Returns a collection of page ranges and their starting and ending byte offsets.\n *\n * @param offset\n * The starting offset of the data range over which to list page ranges, in bytes. Must be a multiple of\n * 512.\n * @param length\n * The length of the data range over which to list page ranges, in bytes. Must be a multiple of 512.\n * @return A <code>List</code> object which represents the set of page ranges and their starting and ending\n * byte offsets.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public List<PageRange> downloadPageRanges(final long offset, final Long length) throws StorageException {\n return this.downloadPageRanges(offset, length, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Returns a collection of page ranges and their starting and ending byte offsets using the specified request\n * options and operation context.\n * \n * @param offset\n * The starting offset of the data range over which to list page ranges, in bytes. Must be a multiple of\n * 512.\n * @param length\n * The length of the data range over which to list page ranges, in bytes. Must be a multiple of 512.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A <code>List</code> object which represents the set of page ranges and their starting and ending\n * byte offsets.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public List<PageRange> downloadPageRanges(final long offset, final Long length,\n final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException {\n if (offset < 0 || (length != null && length <= 0)) {\n throw new IndexOutOfBoundsException();\n }\n \n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.PAGE_BLOB, this.blobServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.downloadPageRangesImpl(offset, length, accessCondition, options), options.getRetryPolicyFactory(), opContext);\n }\n \n private StorageRequest<CloudBlobClient, CloudBlob, ArrayList<PageRange>> downloadPageRangesImpl(final Long offset,\n final Long length, final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlob, ArrayList<PageRange>> getRequest = new StorageRequest<CloudBlobClient, CloudBlob, ArrayList<PageRange>>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlob blob, OperationContext context)\n throws Exception {\n return BlobRequest.getPageRanges(blob.getTransformedAddress(context).getUri(this.getCurrentLocation()),\n options, context, accessCondition, blob.snapshotID, offset, length);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public ArrayList<PageRange> preProcessResponse(CloudBlob parentObject, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n\n @Override\n public ArrayList<PageRange> postProcessResponse(HttpURLConnection connection, CloudBlob blob,\n CloudBlobClient client, OperationContext context, ArrayList<PageRange> storageObject)\n throws Exception {\n blob.updateEtagAndLastModifiedFromResponse(this.getConnection());\n blob.updateLengthFromResponse(this.getConnection());\n\n return PageRangeHandler.getPageRanges(this.getConnection().getInputStream());\n }\n\n };\n\n return getRequest;\n }\n \n /**\n * Gets the collection of page ranges that differ between a specified snapshot and this object.\n * \n * @param previousSnapshot\n * A string representing the snapshot to use as the starting point for the diff. If this\n * CloudPageBlob represents a snapshot, the previousSnapshot parameter must be prior to the current\n * snapshot.\n * @return A <code>List</code> object containing the set of differing page ranges.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public List<PageRangeDiff> downloadPageRangesDiff(final String previousSnapshot) throws StorageException {\n return this.downloadPageRangesDiff(previousSnapshot, null /* offset */, null/* length */,\n null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Gets the collection of page ranges that differ between a specified snapshot and this object.\n * \n * @param previousSnapshot\n * A string representing the snapshot timestamp to use as the starting point for the diff. If this\n * CloudPageBlob represents a snapshot, the previousSnapshot parameter must be prior to the current\n * snapshot.\n * @param offset\n * The starting offset of the data range over which to list page ranges, in bytes. Must be a multiple of\n * 512.\n * @param length\n * The length of the data range over which to list page ranges, in bytes. Must be a multiple of 512.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A <code>List</code> object containing the set of differing page ranges.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public List<PageRangeDiff> downloadPageRangesDiff(final String previousSnapshot, final Long offset,\n final Long length, final AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.PAGE_BLOB, this.blobServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.downloadPageRangesDiffImpl(previousSnapshot, offset, length, accessCondition, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudBlob, List<PageRangeDiff>> downloadPageRangesDiffImpl(\n final String previousSnapshot, final Long offset, final Long length, final AccessCondition accessCondition,\n final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudBlob, List<PageRangeDiff>> getRequest = new StorageRequest<CloudBlobClient, CloudBlob, List<PageRangeDiff>>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlob blob, OperationContext context)\n throws Exception {\n return BlobRequest.getPageRangesDiff(\n blob.getTransformedAddress(context).getUri(this.getCurrentLocation()), options, context,\n accessCondition, blob.snapshotID, previousSnapshot, offset, length);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public List<PageRangeDiff> preProcessResponse(CloudBlob parentObject, CloudBlobClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n\n @Override\n public List<PageRangeDiff> postProcessResponse(HttpURLConnection connection, CloudBlob blob,\n CloudBlobClient client, OperationContext context, List<PageRangeDiff> storageObject)\n throws Exception {\n blob.updateEtagAndLastModifiedFromResponse(this.getConnection());\n blob.updateLengthFromResponse(this.getConnection());\n\n return PageRangeDiffHandler.getPageRangesDiff(this.getConnection().getInputStream());\n }\n };\n\n return getRequest;\n }\n\n /**\n * Opens an output stream object to write data to the page blob. The page blob must already exist and any existing \n * data may be overwritten.\n * \n * @return A {@link BlobOutputStream} object used to write data to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public BlobOutputStream openWriteExisting() throws StorageException {\n return this\n .openOutputStreamInternal(null /* length */, null /* premiumBlobTier */,null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Opens an output stream object to write data to the page blob, using the specified lease ID, request options and\n * operation context. The page blob must already exist and any existing data may be overwritten.\n * \n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A {@link BlobOutputStream} object used to write data to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public BlobOutputStream openWriteExisting(AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n return this.openOutputStreamInternal(null /* length */, null /* premiumBlobTier */, accessCondition, options, opContext);\n }\n\n /**\n * Opens an output stream object to write data to the page blob. The page blob does not need to yet exist and will\n * be created with the length specified. If the blob already exists on the service, it will be overwritten.\n * <p>\n * To avoid overwriting and instead throw an error, please use the \n * {@link #openWriteNew(long, AccessCondition, BlobRequestOptions, OperationContext)} overload with the appropriate \n * {@link AccessCondition}.\n * \n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream to create. This value must be\n * a multiple of 512.\n * \n * @return A {@link BlobOutputStream} object used to write data to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public BlobOutputStream openWriteNew(final long length) throws StorageException {\n return this\n .openOutputStreamInternal(length, null /* premiumBlobTier */, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Opens an output stream object to write data to the page blob, using the specified lease ID, request options and\n * operation context. The page blob does not need to yet exist and will be created with the length specified.If the\n * blob already exists on the service, it will be overwritten.\n * <p>\n * To avoid overwriting and instead throw an error, please pass in an {@link AccessCondition} generated using\n * {@link AccessCondition#generateIfNotExistsCondition()}.\n *\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream to create. This value must be\n * a multiple of 512.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @return A {@link BlobOutputStream} object used to write data to the blob.\n *\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public BlobOutputStream openWriteNew(final long length, AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException {\n return openOutputStreamInternal(length, null /* premiumBlobTier */, accessCondition, options, opContext);\n }\n\n /**\n * Opens an output stream object to write data to the page blob, using the specified lease ID, request options and\n * operation context. The page blob does not need to yet exist and will be created with the length specified.If the \n * blob already exists on the service, it will be overwritten.\n * <p>\n * To avoid overwriting and instead throw an error, please pass in an {@link AccessCondition} generated using \n * {@link AccessCondition#generateIfNotExistsCondition()}.\n * \n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream to create. This value must be\n * a multiple of 512.\n * @param premiumBlobTier\n * A {@link PremiumPageBlobTier} object which represents the tier of the blob.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A {@link BlobOutputStream} object used to write data to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public BlobOutputStream openWriteNew(final long length, final PremiumPageBlobTier premiumBlobTier, AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException {\n return openOutputStreamInternal(length, premiumBlobTier, accessCondition, options, opContext);\n }\n\n /**\n * Opens an output stream object to write data to the page blob, using the specified lease ID, request options and\n * operation context. If the length is specified, a new page blob will be created with the length specified.\n * Otherwise, the page blob must already exist and a stream of its current length will be opened.\n * \n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream to create. This value must be\n * a multiple of 512 or null if the\n * page blob already exists.\n * @param premiumBlobTier\n * A {@link PremiumPageBlobTier} object which represents the tier of the blob.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A {@link BlobOutputStream} object used to write data to the blob.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n private BlobOutputStream openOutputStreamInternal(Long length, PremiumPageBlobTier premiumBlobTier, AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n assertNoWriteOperationForSnapshot();\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.PAGE_BLOB, this.blobServiceClient, \n false /* setStartTime */);\n\n if (options.getStoreBlobContentMD5()) {\n throw new IllegalArgumentException(SR.BLOB_MD5_NOT_SUPPORTED_FOR_PAGE_BLOBS);\n }\n\n if (length != null) {\n if (length % Constants.PAGE_SIZE != 0) {\n throw new IllegalArgumentException(SR.INVALID_PAGE_BLOB_LENGTH);\n }\n\n this.create(length, premiumBlobTier, accessCondition, options, opContext);\n }\n else {\n this.downloadAttributes(accessCondition, options, opContext);\n length = this.getProperties().getLength();\n }\n\n if (accessCondition != null) {\n accessCondition = AccessCondition.generateLeaseCondition(accessCondition.getLeaseID());\n }\n\n return new BlobOutputStream(this, length, accessCondition, options, opContext);\n }\n\n /**\n * Used for both uploadPages and clearPages.\n * \n * @param pageRange\n * A {@link PageRange} object that specifies the page range.\n * @param operationType\n * A {@link PageOperationType} enumeration value that specifies the page operation type.\n * @param data\n * A <code>byte</code> array which represents the data to write.\n * @param length\n * A <code>long</code> which represents the number of bytes to write.\n * @param md5\n * A <code>String</code> which represents the MD5 hash for the data.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n private void putPagesInternal(final PageRange pageRange, final PageOperationType operationType, final byte[] data,\n final long length, final String md5, final AccessCondition accessCondition,\n final BlobRequestOptions options, final OperationContext opContext) throws StorageException {\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n putPagesImpl(pageRange, operationType, data, length, md5, accessCondition, options, opContext),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudPageBlob, Void> putPagesImpl(final PageRange pageRange,\n final PageOperationType operationType, final byte[] data, final long length, final String md5,\n final AccessCondition accessCondition, final BlobRequestOptions options, final OperationContext opContext) {\n final StorageRequest<CloudBlobClient, CloudPageBlob, Void> putRequest = new StorageRequest<CloudBlobClient, CloudPageBlob, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudPageBlob blob, OperationContext context)\n throws Exception {\n if (operationType == PageOperationType.UPDATE) {\n this.setSendStream(new ByteArrayInputStream(data));\n this.setLength(length);\n }\n\n return BlobRequest.putPage(blob.getTransformedAddress(opContext).getUri(this.getCurrentLocation()),\n options, opContext, accessCondition, pageRange, operationType);\n }\n\n @Override\n public void setHeaders(HttpURLConnection connection, CloudPageBlob blob, OperationContext context) {\n if (operationType == PageOperationType.UPDATE) {\n if (options.getUseTransactionalContentMD5()) {\n connection.setRequestProperty(Constants.HeaderConstants.CONTENT_MD5, md5);\n }\n }\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n if (operationType == PageOperationType.UPDATE) {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, length, context);\n }\n else {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n }\n\n @Override\n public Void preProcessResponse(CloudPageBlob blob, CloudBlobClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n blob.updateEtagAndLastModifiedFromResponse(this.getConnection());\n blob.updateSequenceNumberFromResponse(this.getConnection());\n this.getResult().setRequestServiceEncrypted(BaseResponse.isServerRequestEncrypted(this.getConnection()));\n return null;\n }\n };\n\n return putRequest;\n }\n \n protected void updateSequenceNumberFromResponse(HttpURLConnection request) {\n final String sequenceNumber = request.getHeaderField(Constants.HeaderConstants.BLOB_SEQUENCE_NUMBER);\n if (!Utility.isNullOrEmpty(sequenceNumber)) {\n this.getProperties().setPageBlobSequenceNumber(Long.parseLong(sequenceNumber));\n }\n }\n\n /**\n * Resizes the page blob to the specified size.\n * \n * @param size\n * A <code>long</code> which represents the size of the page blob, in bytes.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public void resize(long size) throws StorageException {\n this.resize(size, null /* accessCondition */, null /* options */, null /* operationContext */);\n }\n\n /**\n * Resizes the page blob to the specified size.\n * \n * @param size\n * A <code>long</code> which represents the size of the page blob, in bytes.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public void resize(long size, AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n assertNoWriteOperationForSnapshot();\n\n if (size % Constants.PAGE_SIZE != 0) {\n throw new IllegalArgumentException(SR.INVALID_PAGE_BLOB_LENGTH);\n }\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = BlobRequestOptions.populateAndApplyDefaults(options, this.properties.getBlobType(), this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.resizeImpl(size, accessCondition, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudBlobClient, CloudPageBlob, Void> resizeImpl(final long size,\n final AccessCondition accessCondition, final BlobRequestOptions options) {\n final StorageRequest<CloudBlobClient, CloudPageBlob, Void> putRequest = new StorageRequest<CloudBlobClient, CloudPageBlob, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudBlobClient client, CloudPageBlob blob, OperationContext context)\n throws Exception {\n return BlobRequest.resize(blob.getTransformedAddress(context).getUri(this.getCurrentLocation()),\n options, context, accessCondition, size);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudPageBlob blob, CloudBlobClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n blob.getProperties().setLength(size);\n blob.updateEtagAndLastModifiedFromResponse(this.getConnection());\n blob.updateSequenceNumberFromResponse(this.getConnection());\n return null;\n }\n };\n\n return putRequest;\n }\n\n /**\n * Uploads a blob from data in a byte array. If the blob already exists on the service, it will be overwritten.\n *\n * @param buffer\n * A <code>byte</code> array which represents the data to write to the blob.\n * @param offset\n * A <code>int</code> which represents the offset of the byte array from which to start the data upload.\n * @param length\n * An <code>int</code> which represents the number of bytes to upload from the input buffer.\n * @param premiumBlobTier\n * A {@link PremiumPageBlobTier} object which represents the tier of the blob.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws IOException\n */\n public void uploadFromByteArray(final byte[] buffer, final int offset, final int length, final PremiumPageBlobTier premiumBlobTier,\n final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException, IOException {\n ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer, offset, length);\n this.upload(inputStream, length, premiumBlobTier, accessCondition, options, opContext);\n inputStream.close();\n }\n\n /**\n * Uploads a blob from a file. If the blob already exists on the service, it will be overwritten.\n *\n * @param path\n * A <code>String</code> which represents the path to the file to be uploaded.\n * @param premiumBlobTier\n * A {@link PremiumPageBlobTier} object which represents the tier of the blob.\n * @param accessCondition\n * An {@link AccessCondition} object that represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n * @throws IOException\n */\n public void uploadFromFile(final String path, final PremiumPageBlobTier premiumBlobTier, final AccessCondition accessCondition, BlobRequestOptions options,\n OperationContext opContext) throws StorageException, IOException {\n File file = new File(path);\n long fileLength = file.length();\n InputStream inputStream = new BufferedInputStream(new FileInputStream(file));\n this.upload(inputStream, fileLength, premiumBlobTier, accessCondition, options, opContext);\n inputStream.close();\n }\n\n /**\n * Uploads the source stream data to the page blob. If the blob already exists on the service, it will be \n * overwritten.\n * \n * @param sourceStream\n * An {@link InputStream} object to read from.\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream data, must be non zero and a\n * multiple of 512.\n * \n * @throws IOException\n * If an I/O exception occurred.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @Override\n @DoesServiceRequest\n public void upload(final InputStream sourceStream, final long length) throws StorageException, IOException {\n this.upload(sourceStream, length, null /* premiumBlobTier */, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Uploads the source stream data to the page blob using the specified lease ID, request options, and operation\n * context. If the blob already exists on the service, it will be overwritten.\n *\n * @param sourceStream\n * An {@link InputStream} object to read from.\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream data. This must be great than\n * zero and a multiple of 512.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @throws IOException\n * If an I/O exception occurred.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @Override\n @DoesServiceRequest\n public void upload(final InputStream sourceStream, final long length, final AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException {\n this.upload(sourceStream, length, null /* premiumBlobTier*/, accessCondition, options, opContext);\n }\n\n /**\n * Uploads the source stream data to the page blob using the specified lease ID, request options, and operation\n * context. If the blob already exists on the service, it will be overwritten.\n * \n * @param sourceStream\n * An {@link InputStream} object to read from.\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the stream data. This must be great than\n * zero and a multiple of 512.\n * @param premiumBlobTier\n * A {@link PremiumPageBlobTier} object which represents the tier of the blob.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws IOException\n * If an I/O exception occurred.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void upload(final InputStream sourceStream, final long length, final PremiumPageBlobTier premiumBlobTier, final AccessCondition accessCondition,\n BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException {\n assertNoWriteOperationForSnapshot();\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.PAGE_BLOB, this.blobServiceClient);\n\n if (length <= 0 || length % Constants.PAGE_SIZE != 0) {\n throw new IllegalArgumentException(SR.INVALID_PAGE_BLOB_LENGTH);\n }\n\n if (options.getStoreBlobContentMD5()) {\n throw new IllegalArgumentException(SR.BLOB_MD5_NOT_SUPPORTED_FOR_PAGE_BLOBS);\n }\n\n if (sourceStream.markSupported()) {\n // Mark sourceStream for current position.\n sourceStream.mark(Constants.MAX_MARK_LENGTH);\n }\n\n final BlobOutputStream streamRef = this.openWriteNew(length, premiumBlobTier, accessCondition, options, opContext);\n try {\n streamRef.write(sourceStream, length);\n }\n finally {\n streamRef.close();\n }\n }\n\n /**\n * Uploads a range of contiguous pages, up to 4 MB in size, at the specified offset in the page blob.\n * \n * @param sourceStream\n * An {@link InputStream} object which represents the input stream to write to the page blob.\n * @param offset\n * A <code>long</code> which represents the offset, in number of bytes, at which to begin writing the\n * data. This value must be a multiple of 512.\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the data to write. This value must be a\n * multiple of 512.\n * \n * @throws IllegalArgumentException\n * If the offset or length are not multiples of 512, or if the length is greater than 4 MB.\n * @throws IOException\n * If an I/O exception occurred.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadPages(final InputStream sourceStream, final long offset, final long length)\n throws StorageException, IOException {\n this.uploadPages(sourceStream, offset, length, null /* accessCondition */, null /* options */, null /* opContext */);\n }\n\n /**\n * Uploads a range of contiguous pages, up to 4 MB in size, at the specified offset in the page blob, using the\n * specified lease ID, request options, and operation context.\n * \n * @param sourceStream\n * An {@link InputStream} object which represents the input stream to write to the page blob.\n * @param offset\n * A <code>long</code> which represents the offset, in number of bytes, at which to begin writing the\n * data. This value must be a multiple of\n * 512.\n * @param length\n * A <code>long</code> which represents the length, in bytes, of the data to write. This value must be a\n * multiple of 512.\n * @param accessCondition\n * An {@link AccessCondition} object which represents the access conditions for the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws IllegalArgumentException\n * If the offset or length are not multiples of 512, or if the length is greater than 4 MB.\n * @throws IOException\n * If an I/O exception occurred.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadPages(final InputStream sourceStream, final long offset, final long length,\n final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext)\n throws StorageException, IOException {\n\n if (offset % Constants.PAGE_SIZE != 0) {\n throw new IllegalArgumentException(SR.INVALID_PAGE_START_OFFSET);\n }\n\n if (length == 0 || length % Constants.PAGE_SIZE != 0) {\n throw new IllegalArgumentException(SR.INVALID_PAGE_BLOB_LENGTH);\n }\n\n if (length > 4 * Constants.MB) {\n throw new IllegalArgumentException(SR.INVALID_MAX_WRITE_SIZE);\n }\n\n assertNoWriteOperationForSnapshot();\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.PAGE_BLOB, this.blobServiceClient);\n\n final PageRange pageRange = new PageRange(offset, offset + length - 1);\n final byte[] data = new byte[(int) length];\n String md5 = null;\n\n int count = 0;\n int total = 0;\n while (total < length) {\n count = sourceStream.read(data, total, (int) Math.min(length - total, Integer.MAX_VALUE));\n total += count;\n }\n\n if (options.getUseTransactionalContentMD5()) {\n try {\n final MessageDigest digest = MessageDigest.getInstance(\"MD5\");\n digest.update(data, 0, data.length);\n md5 = Base64.encode(digest.digest());\n }\n catch (final NoSuchAlgorithmException e) {\n // This wont happen, throw fatal.\n throw Utility.generateNewUnexpectedStorageException(e);\n }\n }\n\n this.putPagesInternal(pageRange, PageOperationType.UPDATE, data, length, md5, accessCondition, options,\n opContext);\n }\n\n /**\n * Sets the number of bytes to buffer when writing to a {@link BlobOutputStream}.\n * \n * @param streamWriteSizeInBytes\n * An <code>int</code> which represents the maximum number of bytes to buffer when writing to a page blob\n * stream. This value must be a\n * multiple of 512 and\n * less than or equal to 4 MB.\n * \n * @throws IllegalArgumentException\n * If <code>streamWriteSizeInBytes</code> is less than 512, greater than 4 MB, or not a multiple or 512.\n */\n @Override\n public void setStreamWriteSizeInBytes(final int streamWriteSizeInBytes) {\n if (streamWriteSizeInBytes > Constants.MAX_BLOCK_SIZE || streamWriteSizeInBytes < Constants.PAGE_SIZE\n || streamWriteSizeInBytes % Constants.PAGE_SIZE != 0) {\n throw new IllegalArgumentException(\"StreamWriteSizeInBytes\");\n }\n\n this.streamWriteSizeInBytes = streamWriteSizeInBytes;\n }\n \n /**\n * Sets the blob tier on a page blob on a premium storage account.\n * @param premiumBlobTier\n * A {@link PremiumPageBlobTier} object which represents the tier of the blob.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadPremiumPageBlobTier(final PremiumPageBlobTier premiumBlobTier) throws StorageException {\n this.uploadPremiumPageBlobTier(premiumBlobTier, null /* options */, null /* opContext */);\n }\n\n /**\n * Sets the tier on a page blob on a premium storage account.\n * @param premiumBlobTier\n * A {@link PremiumPageBlobTier} object which represents the tier of the blob.\n * @param options\n * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudBlobClient}).\n * @param opContext\n * An {@link OperationContext} object which represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadPremiumPageBlobTier(final PremiumPageBlobTier premiumBlobTier, BlobRequestOptions options,\n OperationContext opContext) throws StorageException {\n assertNoWriteOperationForSnapshot();\n Utility.assertNotNull(\"premiumBlobTier\", premiumBlobTier);\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.PAGE_BLOB, this.blobServiceClient);\n\n ExecutionEngine.executeWithRetry(this.blobServiceClient, this,\n this.uploadBlobTierImpl(premiumBlobTier.toString(), options), options.getRetryPolicyFactory(), opContext);\n this.properties.setPremiumPageBlobTier(premiumBlobTier);\n this.properties.setBlobTierInferred(false);\n }\n}", "public class SR {\n public static final String ACCOUNT_NAME_NULL_OR_EMPTY = \"The account name is null or empty.\";\n public static final String ACCOUNT_NAME_MISMATCH = \"The account name does not match the existing account name on the credentials.\";\n public static final String APPEND_BLOB_MD5_NOT_POSSIBLE = \"MD5 cannot be calculated for an existing append blob because it would require reading the existing data. Please disable StoreFileContentMD5.\";\n public static final String ARGUMENT_NULL_OR_EMPTY = \"The argument must not be null or an empty string. Argument name: %s.\";\n public static final String ARGUMENT_OUT_OF_RANGE_ERROR = \"The argument is out of range. Argument name: %s, Value passed: %s.\";\n public static final String ATTEMPTED_TO_SERIALIZE_INACCESSIBLE_PROPERTY = \"An attempt was made to access an inaccessible member of the entity during serialization.\";\n public static final String BLOB = \"blob\";\n public static final String BLOB_DATA_CORRUPTED = \"Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s\";\n public static final String BLOB_ENDPOINT_NOT_CONFIGURED = \"No blob endpoint configured.\";\n public static final String BLOB_HASH_MISMATCH = \"Blob hash mismatch (integrity check failed), Expected value is %s, retrieved %s.\";\n public static final String BLOB_MD5_NOT_SUPPORTED_FOR_PAGE_BLOBS = \"Blob level MD5 is not supported for page blobs.\";\n public static final String BLOB_TYPE_NOT_DEFINED = \"The blob type is not defined. Allowed types are BlobType.BLOCK_BLOB and BlobType.Page_BLOB.\";\n public static final String CANNOT_CREATE_SAS_FOR_GIVEN_CREDENTIALS = \"Cannot create Shared Access Signature as the credentials does not have account name information. Please check that the credentials provided support creating Shared Access Signature.\";\n public static final String CANNOT_CREATE_SAS_FOR_SNAPSHOTS = \"Cannot create Shared Access Signature via references to blob snapshots. Please perform the given operation on the root blob instead.\";\n public static final String CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY = \"Cannot create Shared Access Signature unless the Account Key credentials are used by the ServiceClient.\";\n public static final String CANNOT_TRANSFORM_NON_HTTPS_URI_WITH_HTTPS_ONLY_CREDENTIALS = \"Cannot use HTTP with credentials that only support HTTPS.\";\n public static final String CONTAINER = \"container\";\n public static final String CONTENT_LENGTH_MISMATCH = \"An incorrect number of bytes was read from the connection. The connection may have been closed.\";\n public static final String CREATING_NETWORK_STREAM = \"Creating a NetworkInputStream and expecting to read %s bytes.\";\n public static final String CREDENTIALS_CANNOT_SIGN_REQUEST = \"CloudBlobClient, CloudQueueClient and CloudTableClient require credentials that can sign a request.\";\n public static final String CUSTOM_RESOLVER_THREW = \"The custom property resolver delegate threw an exception. Check the inner exception for more details.\";\n public static final String DEFAULT_SERVICE_VERSION_ONLY_SET_FOR_BLOB_SERVICE = \"DefaultServiceVersion can only be set for the Blob service.\";\n public static final String DELETE_SNAPSHOT_NOT_VALID_ERROR = \"The option '%s' must be 'None' to delete a specific snapshot specified by '%s'.\";\n public static final String DIRECTORY = \"directory\";\n public static final String EDMTYPE_WAS_NULL = \"EdmType cannot be null.\";\n public static final String ENUMERATION_ERROR = \"An error occurred while enumerating the result, check the original exception for details.\";\n public static final String EMPTY_BATCH_NOT_ALLOWED = \"Cannot execute an empty batch operation.\";\n public static final String ENDPOINT_INFORMATION_UNAVAILABLE = \"Endpoint information not available for Account using Shared Access Credentials.\";\n public static final String ENTITY_PROPERTY_CANNOT_BE_NULL_FOR_PRIMITIVES = \"EntityProperty cannot be set to null for primitive value types.\";\n public static final String ETAG_INVALID_FOR_DELETE = \"Delete requires a valid ETag (which may be the '*' wildcard).\";\n public static final String ETAG_INVALID_FOR_MERGE = \"Merge requires a valid ETag (which may be the '*' wildcard).\";\n public static final String ETAG_INVALID_FOR_UPDATE = \"Replace requires a valid ETag (which may be the '*' wildcard).\";\n public static final String ENUM_COULD_NOT_BE_PARSED = \"%s could not be parsed from '%s'.\";\n public static final String EXCEPTION_THROWN_DURING_DESERIALIZATION = \"The entity threw an exception during deserialization.\";\n public static final String EXCEPTION_THROWN_DURING_SERIALIZATION = \"The entity threw an exception during serialization.\";\n public static final String EXPECTED_A_FIELD_NAME = \"Expected a field name.\";\n public static final String EXPECTED_END_ARRAY = \"Expected the end of a JSON Array.\";\n public static final String EXPECTED_END_OBJECT = \"Expected the end of a JSON Object.\";\n public static final String EXPECTED_START_ARRAY = \"Expected the start of a JSON Array.\";\n public static final String EXPECTED_START_ELEMENT_TO_EQUAL_ERROR = \"Expected START_ELEMENT to equal error.\";\n public static final String EXPECTED_START_OBJECT = \"Expected the start of a JSON Object.\";\n public static final String FAILED_TO_PARSE_PROPERTY = \"Failed to parse property '%s' with value '%s' as type '%s'\";\n public static final String FILE = \"file\";\n public static final String FILE_ENDPOINT_NOT_CONFIGURED = \"No file endpoint configured.\";\n public static final String FILE_HASH_MISMATCH = \"File hash mismatch (integrity check failed), Expected value is %s, retrieved %s.\";\n public static final String FILE_MD5_NOT_POSSIBLE = \"MD5 cannot be calculated for an existing file because it would require reading the existing data. Please disable StoreFileContentMD5.\";\n public static final String INCORRECT_STREAM_LENGTH = \"An incorrect stream length was specified, resulting in an authentication failure. Please specify correct length, or -1.\";\n public static final String INPUT_STREAM_SHOULD_BE_MARKABLE = \"Input stream must be markable.\";\n public static final String INVALID_ACCOUNT_NAME = \"Invalid account name.\";\n public static final String INVALID_ACL_ACCESS_TYPE = \"Invalid acl public access type returned '%s'. Expected blob or container.\";\n public static final String INVALID_BLOB_TYPE = \"Incorrect Blob type, please use the correct Blob type to access a blob on the server. Expected %s, actual %s.\";\n public static final String INVALID_BLOCK_ID = \"Invalid blockID, blockID must be a valid Base64 String.\";\n public static final String INVALID_BLOCK_SIZE = \"Append block data should not exceed the maximum blob size condition value.\";\n public static final String INVALID_CONDITIONAL_HEADERS = \"The conditionals specified for this operation did not match server.\";\n public static final String INVALID_CONNECTION_STRING = \"Invalid connection string.\";\n public static final String INVALID_CONNECTION_STRING_DEV_STORE_NOT_TRUE = \"Invalid connection string, the UseDevelopmentStorage key must always be paired with 'true'. Remove the flag entirely otherwise.\";\n public static final String INVALID_CONTENT_LENGTH = \"ContentLength must be set to -1 or positive Long value.\";\n public static final String INVALID_CONTENT_TYPE = \"An incorrect Content-Type was returned from the server.\";\n public static final String INVALID_CORS_RULE = \"A CORS rule must contain at least one allowed origin and allowed method, and MaxAgeInSeconds cannot have a value less than zero.\";\n public static final String INVALID_DATE_STRING = \"Invalid Date String: %s.\";\n public static final String INVALID_EDMTYPE_VALUE = \"Invalid value '%s' for EdmType.\";\n public static final String INVALID_FILE_LENGTH = \"File length must be greater than or equal to 0 bytes.\";\n public static final String INVALID_GEO_REPLICATION_STATUS = \"Null or Invalid geo-replication status in response: %s.\";\n public static final String INVALID_IP_ADDRESS = \"Error when parsing IPv4 address: IP address '%s' is invalid.\";\n public static final String INVALID_KEY = \"Storage Key is not a valid base64 encoded string.\";\n public static final String INVALID_LISTING_DETAILS = \"Invalid blob listing details specified.\";\n public static final String INVALID_LOGGING_LEVEL = \"Invalid logging operations specified.\";\n public static final String INVALID_MAX_WRITE_SIZE = \"Max write size is 4MB. Please specify a smaller range.\";\n public static final String INVALID_MESSAGE_LENGTH = \"The message size cannot be larger than %s bytes.\";\n public static final String INVALID_MIME_RESPONSE = \"Invalid MIME response received.\";\n public static final String INVALID_NUMBER_OF_BYTES_IN_THE_BUFFER = \"Page data must be a multiple of 512 bytes. Buffer currently contains %d bytes.\";\n public static final String INVALID_OPERATION_FOR_A_SNAPSHOT = \"Cannot perform this operation on a blob representing a snapshot.\";\n public static final String INVALID_OPERATION_FOR_A_SHARE_SNAPSHOT = \"Cannot perform this operation on a share representing a snapshot.\";\n public static final String INVALID_PAGE_BLOB_LENGTH = \"Page blob length must be multiple of 512.\";\n public static final String INVALID_PAGE_START_OFFSET = \"Page start offset must be multiple of 512.\";\n public static final String INVALID_RANGE_CONTENT_MD5_HEADER = \"Cannot specify x-ms-range-get-content-md5 header on ranges larger than 4 MB. Either use a BlobReadStream via openRead, or disable TransactionalMD5 via the BlobRequestOptions.\";\n public static final String INVALID_RESOURCE_NAME = \"Invalid %s name. Check MSDN for more information about valid naming.\";\n public static final String INVALID_RESOURCE_NAME_LENGTH = \"Invalid %s name length. The name must be between %s and %s characters long.\";\n public static final String INVALID_RESOURCE_RESERVED_NAME = \"Invalid %s name. This name is reserved.\";\n public static final String INVALID_RESPONSE_RECEIVED = \"The response received is invalid or improperly formatted.\";\n public static final String INVALID_STORAGE_PROTOCOL_VERSION = \"Storage protocol version prior to 2009-09-19 do not support shared key authentication.\";\n public static final String INVALID_STORAGE_SERVICE = \"Invalid storage service specified.\";\n public static final String INVALID_STREAM_LENGTH = \"Invalid stream length; stream must be between 0 and %s MB in length.\";\n public static final String ITERATOR_EMPTY = \"There are no more elements in this enumeration.\";\n public static final String LEASE_CONDITION_ON_SOURCE = \"A lease condition cannot be specified on the source of a copy.\";\n public static final String LOG_STREAM_END_ERROR = \"Error parsing log record: unexpected end of stream.\";\n public static final String LOG_STREAM_DELIMITER_ERROR = \"Error parsing log record: unexpected delimiter encountered.\";\n public static final String LOG_STREAM_QUOTE_ERROR = \"Error parsing log record: unexpected quote character encountered.\";\n public static final String LOG_VERSION_UNSUPPORTED = \"A storage log version of %s is unsupported.\";\n public static final String MARK_EXPIRED = \"Stream mark expired.\";\n public static final String MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION = \"The client could not finish the operation within specified maximum execution timeout.\";\n public static final String METADATA_KEY_INVALID = \"The key for one of the metadata key-value pairs is null, empty, or whitespace.\";\n public static final String METADATA_VALUE_INVALID = \"The value for one of the metadata key-value pairs is null, empty, or whitespace.\";\n public static final String MISSING_CREDENTIALS = \"No credentials provided.\";\n public static final String MISSING_MANDATORY_DATE_HEADER = \"Canonicalization did not find a non-empty x-ms-date header in the request. Please use a request with a valid x-ms-date header in RFC 123 format.\";\n public static final String MISSING_MANDATORY_PARAMETER_FOR_SAS = \"Missing mandatory parameters for valid Shared Access Signature.\";\n public static final String MISSING_MD5 = \"ContentMD5 header is missing in the response.\";\n public static final String MISSING_NULLARY_CONSTRUCTOR = \"Class type must contain contain a nullary constructor.\";\n public static final String MULTIPLE_CREDENTIALS_PROVIDED = \"Cannot provide credentials as part of the address and as constructor parameter. Either pass in the address or use a different constructor.\";\n public static final String NETWORK_ON_MAIN_THREAD_EXCEPTION = \"Network operations may not be performed on the main thread.\";\n public static final String OPS_IN_BATCH_MUST_HAVE_SAME_PARTITION_KEY = \"All entities in a given batch must have the same partition key.\";\n public static final String PARAMETER_NOT_IN_RANGE = \"The value of the parameter '%s' should be between %s and %s.\";\n public static final String PARAMETER_SHOULD_BE_GREATER = \"The value of the parameter '%s' should be greater than %s.\";\n public static final String PARAMETER_SHOULD_BE_GREATER_OR_EQUAL = \"The value of the parameter '%s' should be greater than or equal to %s.\";\n public static final String PARTITIONKEY_MISSING_FOR_DELETE = \"Delete requires a partition key.\";\n public static final String PARTITIONKEY_MISSING_FOR_MERGE = \"Merge requires a partition key.\";\n public static final String PARTITIONKEY_MISSING_FOR_UPDATE = \"Replace requires a partition key.\";\n public static final String PARTITIONKEY_MISSING_FOR_INSERT = \"Insert requires a partition key.\";\n public static final String PATH_STYLE_URI_MISSING_ACCOUNT_INFORMATION = \"Missing account name information inside path style URI. Path style URIs should be of the form http://<IPAddress:Port>/<accountName>\";\n public static final String PRIMARY_ONLY_COMMAND = \"This operation can only be executed against the primary storage location.\";\n public static final String PROPERTY_CANNOT_BE_SERIALIZED_AS_GIVEN_EDMTYPE = \"Property %s with Edm Type %s cannot be de-serialized.\";\n public static final String PRECONDITION_FAILURE_IGNORED = \"Pre-condition failure on a retry is being ignored since the request should have succeeded in the first attempt.\";\n public static final String QUERY_PARAMETER_NULL_OR_EMPTY = \"Cannot encode a query parameter with a null or empty key.\";\n public static final String QUERY_REQUIRES_VALID_CLASSTYPE_OR_RESOLVER = \"Query requires a valid class type or resolver.\";\n public static final String QUEUE = \"queue\";\n public static final String QUEUE_ENDPOINT_NOT_CONFIGURED = \"No queue endpoint configured.\";\n public static final String RELATIVE_ADDRESS_NOT_PERMITTED = \"Address %s is a relative address. Only absolute addresses are permitted.\";\n public static final String RESOURCE_NAME_EMPTY = \"Invalid %s name. The name may not be null, empty, or whitespace only.\";\n public static final String RESPONSE_RECEIVED_IS_INVALID = \"The response received is invalid or improperly formatted.\";\n public static final String RETRIEVE_MUST_BE_ONLY_OPERATION_IN_BATCH = \"A batch transaction with a retrieve operation cannot contain any other operations.\";\n public static final String ROWKEY_MISSING_FOR_DELETE = \"Delete requires a row key.\";\n public static final String ROWKEY_MISSING_FOR_MERGE = \"Merge requires a row key.\";\n public static final String ROWKEY_MISSING_FOR_UPDATE = \"Replace requires a row key.\";\n public static final String ROWKEY_MISSING_FOR_INSERT = \"Insert requires a row key.\";\n public static final String SCHEME_NULL_OR_EMPTY = \"The protocol to use is null. Please specify whether to use http or https.\";\n public static final String SECONDARY_ONLY_COMMAND = \"This operation can only be executed against the secondary storage location.\";\n public static final String SHARE = \"share\";\n public static final String SNAPSHOT_LISTING_ERROR = \"Listing snapshots is only supported in flat mode (no delimiter). Consider setting useFlatBlobListing to true.\";\n public static final String SNAPSHOT_QUERY_OPTION_ALREADY_DEFINED = \"Snapshot query parameter is already defined in the blob URI. Either pass in a snapshotTime parameter or use a full URL with a snapshot query parameter.\";\n public static final String STORAGE_CREDENTIALS_NULL_OR_ANONYMOUS = \"StorageCredentials cannot be null or anonymous for this service.\";\n public static final String STORAGE_CLIENT_OR_SAS_REQUIRED = \"Either a SAS token or a service client must be specified.\";\n public static final String STORAGE_URI_MISSING_LOCATION = \"The URI for the target storage location is not specified. Please consider changing the request's location mode.\";\n public static final String STORAGE_URI_MUST_MATCH = \"Primary and secondary location URIs in a StorageUri must point to the same resource.\";\n public static final String STORAGE_URI_NOT_NULL = \"Primary and secondary location URIs in a StorageUri must not both be null.\";\n public static final String STOREAS_DIFFERENT_FOR_GETTER_AND_SETTER = \"StoreAs Annotation found for both getter and setter for property %s with unequal values.\";\n public static final String STOREAS_USED_ON_EMPTY_PROPERTY = \"StoreAs Annotation found for property %s with empty value.\";\n public static final String STREAM_CLOSED = \"Stream is already closed.\";\n public static final String STREAM_LENGTH_GREATER_THAN_4MB = \"Invalid stream length, length must be less than or equal to 4 MB in size.\";\n public static final String STREAM_LENGTH_NEGATIVE = \"Invalid stream length, specify -1 for unknown length stream, or a positive number of bytes.\";\n public static final String STRING_NOT_VALID = \"The String is not a valid Base64-encoded string.\";\n public static final String TABLE = \"table\";\n public static final String TABLE_ENDPOINT_NOT_CONFIGURED = \"No table endpoint configured.\";\n public static final String TABLE_OBJECT_RELATIVE_URIS_NOT_SUPPORTED = \"Table Object relative URIs not supported.\";\n public static final String TAKE_COUNT_ZERO_OR_NEGATIVE = \"Take count must be positive and greater than 0.\";\n public static final String TOO_MANY_PATH_SEGMENTS = \"The count of URL path segments (strings between '/' characters) as part of the blob name cannot exceed 254.\";\n public static final String TOO_MANY_SHARED_ACCESS_POLICY_IDENTIFIERS = \"Too many %d shared access policy identifiers provided. Server does not support setting more than %d on a single container, queue, or table.\";\n public static final String TOO_MANY_SHARED_ACCESS_POLICY_IDS = \"Too many %d shared access policy identifiers provided. Server does not support setting more than %d on a single container.\";\n public static final String TYPE_NOT_SUPPORTED = \"Type %s is not supported.\";\n public static final String UNEXPECTED_CONTINUATION_TYPE = \"The continuation type passed in is unexpected. Please verify that the correct continuation type is passed in. Expected {%s}, found {%s}.\";\n public static final String UNEXPECTED_FIELD_NAME = \"Unexpected field name. Expected: '%s'. Actual: '%s'.\";\n public static final String UNEXPECTED_STATUS_CODE_RECEIVED = \"Unexpected http status code received.\";\n public static final String UNEXPECTED_STREAM_READ_ERROR = \"Unexpected error. Stream returned unexpected number of bytes.\";\n public static final String UNKNOWN_TABLE_OPERATION = \"Unknown table operation.\";\n}", "public final class CloudQueue {\n\n /**\n * Gets the first message from a list of queue messages, if any.\n * \n * @param messages\n * The <code>Iterable</code> collection of {@link CloudQueueMessage} objects to get the first message\n * from.\n * \n * @return The first {@link CloudQueueMessage} from the list of queue messages, or <code>null</code> if the list is\n * empty.\n */\n private static CloudQueueMessage getFirstOrNull(final Iterable<CloudQueueMessage> messages) {\n for (final CloudQueueMessage m : messages) {\n return m;\n }\n\n return null;\n }\n\n /**\n * The name of the queue.\n */\n private String name;\n\n /**\n * A reference to the queue's associated service client.\n */\n private CloudQueueClient queueServiceClient;\n\n /**\n * The queue's Metadata collection.\n */\n private HashMap<String, String> metadata;\n\n /**\n * The queue's approximate message count, as reported by the server.\n */\n private long approximateMessageCount;\n\n /**\n * The <code for the messages of the queue.\n */\n private StorageUri messageRequestAddress;\n\n /**\n * Holds the list of URIs for all locations.\n */\n private StorageUri storageUri;\n\n /**\n * A flag indicating whether or not the message should be encoded in base-64.\n */\n private boolean shouldEncodeMessage;\n\n /**\n * Creates an instance of the <code>CloudQueue</code> class using the specified queue URI. The queue\n * <code>URI</code> must include a SAS token.\n * \n * @param uri\n * A <code>java.net.URI</code> object that represents the absolute URI of the queue.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudQueue(final URI uri) throws StorageException {\n this(new StorageUri(uri, null));\n }\n\n /**\n * Creates an instance of the <code>CloudQueue</code> class using the specified queue <code>StorageUri</code>. The \n * queue <code>StorageUri</code> must include a SAS token.\n * \n * @param uri\n * A <code>StorageUri</code> object that represents the absolute URI of the queue.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudQueue(final StorageUri uri) throws StorageException {\n this(uri, (StorageCredentials)null);\n }\n\n /**\n * Creates an instance of the <code>CloudQueue</code> class using the specified queue <code>URI</code> and\n * credentials. If the <code>URI</code> contains a SAS token, the credentials must be <code>null</code>.\n * \n * @param uri\n * A <code>java.net.URI</code> object that represents the absolute URI of the queue.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudQueue(final URI uri, final StorageCredentials credentials) throws StorageException {\n this(new StorageUri(uri), credentials);\n }\n\n /**\n * Creates an instance of the <code>CloudQueue</code> class using the specified queue <code>StorageUri</code> and\n * credentials. If the <code>StorageUri</code> contains a SAS token, the credentials must be <code>null</code>.\n * \n * @param uri\n * A <code>StorageUri</code> object that represents the absolute URI of the queue.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudQueue(final StorageUri uri, final StorageCredentials credentials) throws StorageException {\n this.shouldEncodeMessage = true;\n this.parseQueryAndVerify(uri, credentials);\n }\n \n /**\n * Creates an instance of the <code>CloudQueue</code> class using the specified name and client.\n * \n * @param queueName\n * The name of the queue, which must adhere to queue naming rules. The queue name should not include any\n * path separator characters (/).\n * Queue names must be lowercase, between 3-63 characters long and must start with a letter or number.\n * Queue names may contain only letters, numbers, and the dash (-) character.\n * @param client\n * A {@link CloudQueueClient} object that represents the associated service client, and that specifies\n * the endpoint for the Queue service.\n * @throws URISyntaxException\n * If the resource URI constructed based on the queueName is invalid.\n * @throws StorageException\n * If a storage service error occurred.\n * @see <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179349.aspx\">Naming Queues and Metadata</a>\n */\n protected CloudQueue(final String queueName, final CloudQueueClient client) throws URISyntaxException,\n StorageException {\n Utility.assertNotNull(\"client\", client);\n Utility.assertNotNull(\"queueName\", queueName);\n\n this.storageUri = PathUtility.appendPathToUri(client.getStorageUri(), queueName);\n this.name = queueName;\n this.queueServiceClient = client;\n this.shouldEncodeMessage = true;\n }\n\n /**\n * Adds a message to the back of the queue.\n * \n * @param message\n * A {@link CloudQueueMessage} object that specifies the message to add.\n * The message object is modified to include the message ID and pop receipt,\n * and can be used in subsequent calls to updateMessage and deleteMessage.\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void addMessage(final CloudQueueMessage message) throws StorageException {\n this.addMessage(message, 0, 0, null /* options */, null /* opContext */);\n }\n\n /**\n * Adds a message to the back of the queue with the specified options.\n * \n * @param message\n * A {@link CloudQueueMessage} object that specifies the message to add.\n * The message object is modified to include the message ID and pop receipt,\n * and can be used in subsequent calls to updateMessage and deleteMessage.\n * \n * @param timeToLiveInSeconds\n * The maximum time to allow the message to be in the queue. A value of zero will set the time-to-live to\n * the service default value of seven days.\n * \n * @param initialVisibilityDelayInSeconds\n * The length of time during which the message will be invisible, starting when it is added to the queue,\n * or 0 to make the message visible immediately. This value must be greater than or equal to zero and\n * less than or equal to the time-to-live value.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * \n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void addMessage(final CloudQueueMessage message, final int timeToLiveInSeconds,\n final int initialVisibilityDelayInSeconds, QueueRequestOptions options, OperationContext opContext)\n throws StorageException {\n Utility.assertNotNull(\"message\", message);\n Utility.assertNotNull(\"messageContent\", message.getMessageContentAsByte());\n Utility.assertInBounds(\"timeToLiveInSeconds\", timeToLiveInSeconds, 0,\n QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS);\n\n final int realTimeToLiveInSeconds = timeToLiveInSeconds == 0 ? QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS\n : timeToLiveInSeconds;\n Utility.assertInBounds(\"initialVisibilityDelayInSeconds\", initialVisibilityDelayInSeconds, 0,\n realTimeToLiveInSeconds - 1);\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n ExecutionEngine.executeWithRetry(this.queueServiceClient, this,\n this.addMessageImpl(message, realTimeToLiveInSeconds, initialVisibilityDelayInSeconds, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, Void> addMessageImpl(final CloudQueueMessage message,\n final int timeToLiveInSeconds, final int initialVisibilityDelayInSeconds, final QueueRequestOptions options)\n throws StorageException {\n final String stringToSend = message.getMessageContentForTransfer(this.shouldEncodeMessage);\n\n try {\n final byte[] messageBytes = QueueMessageSerializer.generateMessageRequestBody(stringToSend);\n\n final StorageRequest<CloudQueueClient, CloudQueue, Void> putRequest =\n new StorageRequest<CloudQueueClient, CloudQueue, Void>(options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue,\n OperationContext context) throws Exception {\n this.setSendStream(new ByteArrayInputStream(messageBytes));\n this.setLength((long) messageBytes.length);\n return QueueRequest.putMessage(\n queue.getMessageRequestAddress(context).getUri(this.getCurrentLocation()), options,\n context, initialVisibilityDelayInSeconds, timeToLiveInSeconds);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, messageBytes.length, context);\n }\n\n @Override\n public Void preProcessResponse(CloudQueue queue, CloudQueueClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n // Parse the returned messages\n CloudQueueMessage returnedMessage = QueueMessageHandler.readMessages(\n this.getConnection().getInputStream(), queue.shouldEncodeMessage).get(0);\n\n message.setInsertionTime(returnedMessage.getInsertionTime());\n message.setExpirationTime(returnedMessage.getExpirationTime());\n message.setNextVisibleTime(returnedMessage.getNextVisibleTime());\n message.setMessageId(returnedMessage.getMessageId());\n message.setPopReceipt(returnedMessage.getPopReceipt());\n\n return null;\n }\n };\n\n return putRequest;\n }\n catch (IllegalArgumentException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IllegalStateException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IOException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n }\n\n /**\n * Clears all messages from the queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void clear() throws StorageException {\n this.clear(null /* options */, null /* opContext */);\n }\n\n /**\n * Clears all messages from the queue, using the specified request options and operation context.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void clear(QueueRequestOptions options, OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.clearImpl(options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, Void> clearImpl(final QueueRequestOptions options) {\n final StorageRequest<CloudQueueClient, CloudQueue, Void> putRequest = new StorageRequest<CloudQueueClient, CloudQueue, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue, OperationContext context)\n throws Exception {\n return QueueRequest.clearMessages(\n queue.getMessageRequestAddress(context).getUri(this.getCurrentLocation()), options, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudQueue parentObject, CloudQueueClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n };\n\n return putRequest;\n }\n\n /**\n * Creates the queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void create() throws StorageException {\n this.create(null /* options */, null /* opContext */);\n }\n\n /**\n * Creates the queue, using the specified request options and operation context.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void create(QueueRequestOptions options, OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.createImpl(options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, Void> createImpl(final QueueRequestOptions options) {\n final StorageRequest<CloudQueueClient, CloudQueue, Void> putRequest = new StorageRequest<CloudQueueClient, CloudQueue, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue, OperationContext context)\n throws Exception {\n return QueueRequest.create(queue.getTransformedAddress(context).getUri(this.getCurrentLocation()),\n options, context);\n }\n\n @Override\n public void setHeaders(HttpURLConnection connection, CloudQueue queue, OperationContext context) {\n QueueRequest.addMetadata(connection, queue.metadata, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudQueue parentObject, CloudQueueClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED\n && this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n\n };\n\n return putRequest;\n }\n\n /**\n * Creates the queue if it does not already exist.\n * \n * @return A value of <code>true</code> if the queue is created in the storage service, otherwise <code>false</code>\n * .\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean createIfNotExists() throws StorageException {\n return this.createIfNotExists(null /* options */, null /* opContext */);\n }\n\n /**\n * Creates the queue if it does not already exist, using the specified request options and operation context.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A value of <code>true</code> if the queue is created in the storage service, otherwise <code>false</code>\n * .\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean createIfNotExists(QueueRequestOptions options, OperationContext opContext) throws StorageException {\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n boolean exists = this.exists(true, options, opContext);\n if (exists) {\n return false;\n }\n else {\n try {\n this.create(options, opContext);\n return true;\n }\n catch (StorageException e) {\n if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT\n && StorageErrorCodeStrings.QUEUE_ALREADY_EXISTS.equals(e.getErrorCode())) {\n return false;\n }\n else {\n throw e;\n }\n }\n }\n }\n\n /**\n * Deletes the queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void delete() throws StorageException {\n this.delete(null /* options */, null /* opContext */);\n }\n\n /**\n * Deletes the queue, using the specified request options and operation context.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void delete(QueueRequestOptions options, OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.deleteImpl(options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, Void> deleteImpl(final QueueRequestOptions options) {\n final StorageRequest<CloudQueueClient, CloudQueue, Void> deleteRequest = new StorageRequest<CloudQueueClient, CloudQueue, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue, OperationContext context)\n throws Exception {\n return QueueRequest.delete(queue.getTransformedAddress(context).getUri(this.getCurrentLocation()),\n options, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudQueue parentObject, CloudQueueClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n };\n\n return deleteRequest;\n }\n\n /**\n * Deletes the queue if it exists.\n * \n * @return A value of <code>true</code> if the queue existed in the storage service and has been deleted, otherwise\n * <code>false</code>.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean deleteIfExists() throws StorageException {\n return this.deleteIfExists(null /* options */, null /* opContext */);\n }\n\n /**\n * Deletes the queue if it exists, using the specified request options and operation context.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A value of <code>true</code> if the queue existed in the storage service and has been deleted, otherwise\n * <code>false</code>.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean deleteIfExists(QueueRequestOptions options, OperationContext opContext) throws StorageException {\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n boolean exists = this.exists(true, options, opContext);\n if (exists) {\n try {\n this.delete(options, opContext);\n return true;\n }\n catch (StorageException e) {\n if (e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND\n && StorageErrorCodeStrings.QUEUE_NOT_FOUND.equals(e.getErrorCode())) {\n return false;\n }\n else {\n throw e;\n }\n }\n\n }\n else {\n return false;\n }\n }\n\n /**\n * Deletes the specified message from the queue.\n * \n * @param message\n * A {@link CloudQueueMessage} object that specifies the message to delete.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void deleteMessage(final CloudQueueMessage message) throws StorageException {\n this.deleteMessage(message, null /* options */, null /* opContext */);\n }\n\n /**\n * Deletes the specified message from the queue, using the specified request options and operation context.\n * \n * @param message\n * A {@link CloudQueueMessage} object that specifies the message to delete.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * \n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void deleteMessage(final CloudQueueMessage message, QueueRequestOptions options, OperationContext opContext)\n throws StorageException {\n Utility.assertNotNull(\"message\", message);\n Utility.assertNotNullOrEmpty(\"messageId\", message.getId());\n Utility.assertNotNullOrEmpty(\"popReceipt\", message.getPopReceipt());\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.deleteMessageImpl(message, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, Void> deleteMessageImpl(final CloudQueueMessage message,\n final QueueRequestOptions options) {\n final String messageId = message.getId();\n final String messagePopReceipt = message.getPopReceipt();\n\n final StorageRequest<CloudQueueClient, CloudQueue, Void> putRequest = new StorageRequest<CloudQueueClient, CloudQueue, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue, OperationContext context)\n throws Exception {\n return QueueRequest.deleteMessage(\n queue.getIndividualMessageAddress(messageId, context).getUri(this.getCurrentLocation()),\n options, context, messagePopReceipt);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudQueue parentObject, CloudQueueClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n };\n\n return putRequest;\n }\n\n /**\n * Downloads the queue's metadata and approximate message count value.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void downloadAttributes() throws StorageException {\n this.downloadAttributes(null /* options */, null /* opContext */);\n }\n\n /**\n * Downloads the queue's metadata and approximate message count value, using the specified request options and\n * operation context.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueue}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void downloadAttributes(QueueRequestOptions options, OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.downloadAttributesImpl(options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, Void> downloadAttributesImpl(final QueueRequestOptions options) {\n final StorageRequest<CloudQueueClient, CloudQueue, Void> getRequest = new StorageRequest<CloudQueueClient, CloudQueue, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue, OperationContext context)\n throws Exception {\n return QueueRequest.downloadAttributes(\n queue.getTransformedAddress(context).getUri(this.getCurrentLocation()), options, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudQueue queue, CloudQueueClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n queue.metadata = BaseResponse.getMetadata(this.getConnection());\n queue.approximateMessageCount = QueueResponse.getApproximateMessageCount(this.getConnection());\n return null;\n }\n };\n\n return getRequest;\n }\n\n /**\n * Returns a value that indicates whether the queue exists.\n * \n * @return <code>true</code> if the queue exists in the storage service, otherwise <code>false</code>.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean exists() throws StorageException {\n return this.exists(null /* options */, null /* opContext */);\n }\n\n /**\n * Returns a value that indicates whether the queue existse, using the specified request options and operation\n * context.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return <code>true</code> if the queue exists in the storage service, otherwise <code>false</code>.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean exists(QueueRequestOptions options, OperationContext opContext) throws StorageException {\n return this.exists(false, options, opContext);\n }\n\n @DoesServiceRequest\n private boolean exists(final boolean primaryOnly, QueueRequestOptions options, OperationContext opContext)\n throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.existsImpl(primaryOnly, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, Boolean> existsImpl(final boolean primaryOnly,\n final QueueRequestOptions options) {\n final StorageRequest<CloudQueueClient, CloudQueue, Boolean> getRequest = new StorageRequest<CloudQueueClient, CloudQueue, Boolean>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(primaryOnly ? RequestLocationMode.PRIMARY_ONLY\n : RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue, OperationContext context)\n throws Exception {\n return QueueRequest.downloadAttributes(\n queue.getTransformedAddress(context).getUri(this.getCurrentLocation()), options, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public Boolean preProcessResponse(CloudQueue parentObject, CloudQueueClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_OK) {\n return Boolean.valueOf(true);\n }\n else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {\n return Boolean.valueOf(false);\n }\n else {\n this.setNonExceptionedRetryableFailure(true);\n // return false instead of null to avoid SCA issues\n return false;\n }\n }\n };\n\n return getRequest;\n }\n\n /**\n * Gets the approximate messages count of the queue. This value is initialized by a request to\n * {@link #downloadAttributes} and represents the approximate message count when that request completed.\n * \n * @return A <code>Long</code> object that represents the approximate messages count of the queue.\n */\n public long getApproximateMessageCount() {\n return this.approximateMessageCount;\n }\n\n /**\n * Get a single message request (Used internally only).\n * \n * @return The <code>URI</code> for a single message request.\n * \n * @throws URISyntaxException\n * If the resource URI is invalid.\n * @throws StorageException\n */\n private StorageUri getIndividualMessageAddress(final String messageId, final OperationContext opContext)\n throws URISyntaxException, StorageException {\n return PathUtility.appendPathToUri(this.getMessageRequestAddress(opContext), messageId);\n }\n\n /**\n * Get the message request base address (Used internally only).\n * \n * @return The message request <code>URI</code>.\n * \n * @throws URISyntaxException\n * If the resource URI is invalid.\n * @throws StorageException\n */\n private StorageUri getMessageRequestAddress(final OperationContext opContext) throws URISyntaxException,\n StorageException {\n if (this.messageRequestAddress == null) {\n this.messageRequestAddress = PathUtility.appendPathToUri(this.getTransformedAddress(opContext),\n QueueConstants.MESSAGES);\n }\n\n return this.messageRequestAddress;\n }\n\n /**\n * Gets the metadata collection for the queue as stored in this <code>CloudQueue</code> object. This value is\n * initialized with the metadata from the queue by a call to {@link #downloadAttributes}, and is set on the queue\n * with a call to {@link #uploadMetadata}.\n * \n * @return A <code>java.util.HashMap</code> object that represents the metadata for the queue.\n */\n public HashMap<String, String> getMetadata() {\n return this.metadata;\n }\n\n /**\n * Gets the name of the queue.\n * \n * @return A <code>String</code> object that represents the name of the queue.\n */\n public String getName() {\n return this.name;\n }\n\n /**\n * Gets the queue service client associated with this queue.\n * \n * @return A {@link CloudQueueClient} object that represents the service client associated with this queue.\n */\n public CloudQueueClient getServiceClient() {\n return this.queueServiceClient;\n }\n\n /**\n * Gets the value indicating whether the message should be base-64 encoded.\n * \n * @return A <code>Boolean</code> that represents whether the message should be base-64 encoded.\n */\n public boolean getShouldEncodeMessage() {\n return this.shouldEncodeMessage;\n }\n\n /**\n * Returns the list of URIs for all locations.\n * \n * @return A <code>StorageUri</code> that represents the list of URIs for all locations..\n */\n public final StorageUri getStorageUri() {\n return this.storageUri;\n }\n\n /**\n * Gets the absolute URI for this queue.\n * \n * @return A <code>java.net.URI</code> object that represents the URI for this queue.\n */\n public URI getUri() {\n return this.storageUri.getPrimaryUri();\n }\n\n /**\n * Peeks a message from the queue. A peek request retrieves a message from the front of the queue without changing\n * its visibility.\n * \n * @return An {@link CloudQueueMessage} object that represents a message in this queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public CloudQueueMessage peekMessage() throws StorageException {\n return this.peekMessage(null /* options */, null /* opContext */);\n }\n\n /**\n * Peeks a message from the queue, using the specified request options and operation context. A peek request\n * retrieves a message from the front of the queue without changing its visibility.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return An {@link CloudQueueMessage} object that represents the requested message from the queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public CloudQueueMessage peekMessage(final QueueRequestOptions options, final OperationContext opContext)\n throws StorageException {\n return getFirstOrNull(this.peekMessages(1, null /* options */, null /* opContext */));\n }\n\n /**\n * Peeks a specified number of messages from the queue. A peek request retrieves messages from the front of the\n * queue without changing their visibility.\n * \n * @param numberOfMessages\n * The number of messages to retrieve.\n * \n * @return An enumerable collection of {@link CloudQueueMessage} objects that represents the requested messages from\n * the queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public Iterable<CloudQueueMessage> peekMessages(final int numberOfMessages) throws StorageException {\n return this.peekMessages(numberOfMessages, null /* options */, null /* opContext */);\n }\n\n /**\n * Peeks a set of messages from the queue, using the specified request options and operation context. A peek request\n * retrieves messages from the front of the queue without changing their visibility.\n * \n * @param numberOfMessages\n * The number of messages to retrieve.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return An enumerable collection of {@link CloudQueueMessage} objects that represents the requested messages from\n * the queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public Iterable<CloudQueueMessage> peekMessages(final int numberOfMessages, QueueRequestOptions options,\n OperationContext opContext) throws StorageException {\n Utility.assertInBounds(\"numberOfMessages\", numberOfMessages, 1, QueueConstants.MAX_NUMBER_OF_MESSAGES_TO_PEEK);\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.queueServiceClient, this,\n this.peekMessagesImpl(numberOfMessages, options), options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, ArrayList<CloudQueueMessage>> peekMessagesImpl(\n final int numberOfMessages, final QueueRequestOptions options) {\n final StorageRequest<CloudQueueClient, CloudQueue, ArrayList<CloudQueueMessage>> getRequest = new StorageRequest<CloudQueueClient, CloudQueue, ArrayList<CloudQueueMessage>>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue, OperationContext context)\n throws Exception {\n return QueueRequest.peekMessages(\n queue.getMessageRequestAddress(context).getUri(this.getCurrentLocation()), options, context,\n numberOfMessages);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public ArrayList<CloudQueueMessage> preProcessResponse(CloudQueue queue, CloudQueueClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n else {\n return QueueMessageHandler.readMessages(this.getConnection().getInputStream(),\n queue.shouldEncodeMessage);\n }\n }\n\n };\n\n return getRequest;\n }\n\n /**\n * Retrieves a message from the front of the queue using the default request options. This operation marks the\n * retrieved message as invisible in the queue for the default visibility timeout period.\n * \n * @return An {@link CloudQueueMessage} object that represents a message in this queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public CloudQueueMessage retrieveMessage() throws StorageException {\n return this.retrieveMessage(QueueConstants.DEFAULT_VISIBILITY_MESSAGE_TIMEOUT_IN_SECONDS, null /* options */,\n null /* opContext */);\n }\n\n /**\n * Retrieves a message from the front of the queue, using the specified request options and operation context. This\n * operation marks the retrieved message as invisible in the queue for the specified visibility timeout period.\n * \n * @param visibilityTimeoutInSeconds\n * Specifies the visibility timeout for the message, in seconds.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return An {@link CloudQueueMessage} object that represents a message in this queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public CloudQueueMessage retrieveMessage(final int visibilityTimeoutInSeconds, final QueueRequestOptions options,\n final OperationContext opContext) throws StorageException {\n return getFirstOrNull(this.retrieveMessages(1, visibilityTimeoutInSeconds, options, opContext));\n }\n\n /**\n * Retrieves the specified number of messages from the front of the queue using the default request options. This\n * operation marks the retrieved messages as invisible in the queue for the default visibility timeout period.\n * \n * @param numberOfMessages\n * The number of messages to retrieve.\n * \n * @return An enumerable collection of {@link CloudQueueMessage} objects that represents the retrieved messages from\n * the queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public Iterable<CloudQueueMessage> retrieveMessages(final int numberOfMessages) throws StorageException {\n return this.retrieveMessages(numberOfMessages, QueueConstants.DEFAULT_VISIBILITY_MESSAGE_TIMEOUT_IN_SECONDS,\n null /* options */, null /* opContext */);\n }\n\n /**\n * Retrieves the specified number of messages from the front of the queue using the specified request options and\n * operation context. This operation marks the retrieved messages as invisible in the queue for the default\n * visibility timeout period.\n * \n * @param numberOfMessages\n * The number of messages to retrieve.\n * \n * @param visibilityTimeoutInSeconds\n * Specifies the visibility timeout for the retrieved messages, in seconds.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return An enumerable collection of {@link CloudQueueMessage} objects that represents the messages retrieved from\n * the queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public Iterable<CloudQueueMessage> retrieveMessages(final int numberOfMessages,\n final int visibilityTimeoutInSeconds, QueueRequestOptions options, OperationContext opContext)\n throws StorageException {\n Utility.assertInBounds(\"numberOfMessages\", numberOfMessages, 1, QueueConstants.MAX_NUMBER_OF_MESSAGES_TO_PEEK);\n Utility.assertInBounds(\"visibilityTimeoutInSeconds\", visibilityTimeoutInSeconds, 0,\n QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS);\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.queueServiceClient, this,\n this.retrieveMessagesImpl(numberOfMessages, visibilityTimeoutInSeconds, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, ArrayList<CloudQueueMessage>> retrieveMessagesImpl(\n final int numberOfMessages, final int visibilityTimeoutInSeconds, final QueueRequestOptions options) {\n final StorageRequest<CloudQueueClient, CloudQueue, ArrayList<CloudQueueMessage>> getRequest = new StorageRequest<CloudQueueClient, CloudQueue, ArrayList<CloudQueueMessage>>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue, OperationContext context)\n throws Exception {\n return QueueRequest.retrieveMessages(\n queue.getMessageRequestAddress(context).getUri(this.getCurrentLocation()), options, context,\n numberOfMessages, visibilityTimeoutInSeconds);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public ArrayList<CloudQueueMessage> preProcessResponse(CloudQueue queue, CloudQueueClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n else {\n return QueueMessageHandler.readMessages(this.getConnection().getInputStream(),\n queue.shouldEncodeMessage);\n }\n }\n };\n\n return getRequest;\n }\n\n /**\n * Sets the metadata collection of name-value pairs to be set on the queue with an {@link #uploadMetadata} call.\n * This collection will overwrite any existing queue metadata. If this is set to an empty collection, the queue\n * metadata will be cleared on an {@link #uploadMetadata} call.\n * \n * @param metadata\n * A <code>java.util.HashMap</code> object that represents the metadata being assigned to the queue.\n */\n public void setMetadata(final HashMap<String, String> metadata) {\n this.metadata = metadata;\n }\n\n /**\n * Sets the flag indicating whether the message should be base-64 encoded.\n * \n * @param shouldEncodeMessage\n * The value indicates whether the message should be base-64 encoded.\n */\n public void setShouldEncodeMessage(final boolean shouldEncodeMessage) {\n this.shouldEncodeMessage = shouldEncodeMessage;\n }\n\n /**\n * Updates the specified message in the queue with a new visibility timeout value in seconds.\n * \n * @param message\n * The {@link CloudQueueMessage} to update in the queue.\n * \n * @param visibilityTimeoutInSeconds\n * Specifies the new visibility timeout for the message, in seconds.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n public void updateMessage(final CloudQueueMessage message, final int visibilityTimeoutInSeconds)\n throws StorageException {\n this.updateMessage(message, visibilityTimeoutInSeconds, EnumSet.of(MessageUpdateFields.VISIBILITY),\n null /* options */, null /* opContext */);\n }\n\n /**\n * Updates a message in the queue, using the specified request options and operation context.\n * \n * @param message\n * The {@link CloudQueueMessage} to update in the queue.\n * \n * @param visibilityTimeoutInSeconds\n * Specifies the new visibility timeout for the message, in seconds.\n * \n * @param messageUpdateFields\n * An <code>EnumSet</code> of {@link MessageUpdateFields} values that specifies which parts of the\n * message are to be updated.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * \n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void updateMessage(final CloudQueueMessage message, final int visibilityTimeoutInSeconds,\n final EnumSet<MessageUpdateFields> messageUpdateFields, QueueRequestOptions options,\n OperationContext opContext) throws StorageException {\n Utility.assertNotNull(\"message\", message);\n Utility.assertNotNullOrEmpty(\"messageId\", message.getId());\n Utility.assertNotNullOrEmpty(\"popReceipt\", message.getPopReceipt());\n\n Utility.assertInBounds(\"visibilityTimeoutInSeconds\", visibilityTimeoutInSeconds, 0,\n QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS);\n\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n ExecutionEngine.executeWithRetry(this.queueServiceClient, this,\n this.updateMessageImpl(message, visibilityTimeoutInSeconds, messageUpdateFields, options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, Void> updateMessageImpl(final CloudQueueMessage message,\n final int visibilityTimeoutInSeconds, final EnumSet<MessageUpdateFields> messageUpdateFields,\n final QueueRequestOptions options) throws StorageException {\n final String stringToSend = message.getMessageContentForTransfer(this.shouldEncodeMessage);\n\n final StorageRequest<CloudQueueClient, CloudQueue, Void> putRequest = new StorageRequest<CloudQueueClient, CloudQueue, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue, OperationContext context)\n throws Exception {\n if (messageUpdateFields.contains(MessageUpdateFields.CONTENT)) {\n try {\n final byte[] messageBytes = QueueMessageSerializer.generateMessageRequestBody(stringToSend);\n this.setSendStream(new ByteArrayInputStream(messageBytes));\n this.setLength((long) messageBytes.length);\n }\n catch (IllegalArgumentException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IllegalStateException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IOException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n }\n\n return QueueRequest.updateMessage(\n queue.getIndividualMessageAddress(message.getId(), context).getUri(this.getCurrentLocation()),\n options, context, message.getPopReceipt(), visibilityTimeoutInSeconds);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n if (messageUpdateFields.contains(MessageUpdateFields.CONTENT)) {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, this.getLength(), context);\n }\n else {\n connection.setFixedLengthStreamingMode(0);\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n }\n\n @Override\n public Void preProcessResponse(CloudQueue queue, CloudQueueClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n message.setPopReceipt(this.getConnection().getHeaderField(Constants.HeaderConstants.POP_RECEIPT_HEADER));\n message.setNextVisibleTime(Utility.parseRFC1123DateFromStringInGMT(this.getConnection().getHeaderField(\n Constants.HeaderConstants.TIME_NEXT_VISIBLE_HEADER)));\n\n return null;\n }\n };\n\n return putRequest;\n }\n\n /**\n * Uploads the metadata in the <code>CloudQueue</code> object to the queue.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void uploadMetadata() throws StorageException {\n this.uploadMetadata(null /* options */, null /* opContext */);\n }\n\n /**\n * Uploads the metadata in the <code>CloudQueue</code> object to the queue, using the specified request options and\n * operation context.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * \n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void uploadMetadata(QueueRequestOptions options, OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.uploadMetadataImpl(options),\n options.getRetryPolicyFactory(), opContext);\n\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, Void> uploadMetadataImpl(final QueueRequestOptions options) {\n\n final StorageRequest<CloudQueueClient, CloudQueue, Void> putRequest = new StorageRequest<CloudQueueClient, CloudQueue, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue, OperationContext context)\n throws Exception {\n return QueueRequest.setMetadata(queue.getTransformedAddress(context).getUri(this.getCurrentLocation()),\n options, context);\n }\n\n @Override\n public void setHeaders(HttpURLConnection connection, CloudQueue queue, OperationContext context) {\n QueueRequest.addMetadata(connection, queue.metadata, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, 0L, context);\n }\n\n @Override\n public Void preProcessResponse(CloudQueue parentObject, CloudQueueClient client, OperationContext context)\n throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n\n };\n\n return putRequest;\n }\n\n /**\n * Uploads the queue's permissions.\n * \n * @param permissions\n * A {@link QueuePermissions} object that represents the permissions to upload.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadPermissions(final QueuePermissions permissions) throws StorageException {\n this.uploadPermissions(permissions, null /* options */, null /* opContext */);\n }\n\n /**\n * Uploads the queue's permissions using the specified request options and operation context.\n * \n * @param permissions\n * A {@link QueuePermissions} object that represents the permissions to upload.\n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadPermissions(final QueuePermissions permissions, QueueRequestOptions options,\n OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n ExecutionEngine.executeWithRetry(this.queueServiceClient, this,\n this.uploadPermissionsImpl(permissions, options), options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, Void> uploadPermissionsImpl(\n final QueuePermissions permissions, final QueueRequestOptions options) throws StorageException {\n\n final StringWriter outBuffer = new StringWriter();\n\n try {\n SharedAccessPolicySerializer.writeSharedAccessIdentifiersToStream(permissions.getSharedAccessPolicies(),\n outBuffer);\n\n final byte[] aclBytes = outBuffer.toString().getBytes(Constants.UTF8_CHARSET);\n\n final StorageRequest<CloudQueueClient, CloudQueue, Void> putRequest = new StorageRequest<CloudQueueClient, CloudQueue, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue,\n OperationContext context) throws Exception {\n this.setSendStream(new ByteArrayInputStream(aclBytes));\n this.setLength((long) aclBytes.length);\n return QueueRequest.setAcl(queue.getTransformedAddress(context).getUri(this.getCurrentLocation()),\n options, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, aclBytes.length, context);\n }\n\n @Override\n public Void preProcessResponse(CloudQueue parentObject, CloudQueueClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n };\n\n return putRequest;\n }\n catch (IllegalArgumentException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IllegalStateException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IOException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n }\n\n /**\n * Downloads the permission settings for the queue.\n * \n * @return A {@link QueuePermissions} object that represents the queue's permissions.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public QueuePermissions downloadPermissions() throws StorageException {\n return this.downloadPermissions(null /* options */, null /* opContext */);\n }\n\n /**\n * Downloads the permissions settings for the queue using the specified request options and operation context.\n * \n * @param options\n * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudQueueClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A {@link QueuePermissions} object that represents the container's permissions.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public QueuePermissions downloadPermissions(QueueRequestOptions options, OperationContext opContext)\n throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.downloadPermissionsImpl(options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudQueueClient, CloudQueue, QueuePermissions> downloadPermissionsImpl(\n final QueueRequestOptions options) {\n\n final StorageRequest<CloudQueueClient, CloudQueue, QueuePermissions> getRequest = new StorageRequest<CloudQueueClient, CloudQueue, QueuePermissions>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudQueueClient client, CloudQueue queue, OperationContext context)\n throws Exception {\n return QueueRequest.getAcl(queue.getTransformedAddress(context).getUri(this.getCurrentLocation()),\n options, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudQueueClient client, OperationContext context)\n throws Exception {\n StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context);\n }\n\n @Override\n public QueuePermissions preProcessResponse(CloudQueue parentObject, CloudQueueClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n return null;\n }\n\n return new QueuePermissions();\n }\n\n @Override\n public QueuePermissions postProcessResponse(HttpURLConnection connection, CloudQueue queue,\n CloudQueueClient client, OperationContext context, QueuePermissions queuePermissions)\n throws Exception {\n HashMap<String, SharedAccessQueuePolicy> accessIds = SharedAccessPolicyHandler.getAccessIdentifiers(\n this.getConnection().getInputStream(), SharedAccessQueuePolicy.class);\n\n for (final String key : accessIds.keySet()) {\n queuePermissions.getSharedAccessPolicies().put(key, accessIds.get(key));\n }\n\n return queuePermissions;\n }\n };\n\n return getRequest;\n }\n\n /**\n * Returns a shared access signature for the queue.\n * \n * @param policy\n * The access policy for the shared access signature.\n * @param groupPolicyIdentifier\n * A queue-level access policy.\n * \n * @return A shared access signature for the queue.\n * \n * @throws InvalidKeyException\n * If an invalid key was passed.\n * @throws StorageException\n * If a storage service error occurred.\n * @throws IllegalArgumentException\n * If an unexpected value is passed.\n */\n public String generateSharedAccessSignature(final SharedAccessQueuePolicy policy, final String groupPolicyIdentifier)\n throws InvalidKeyException, StorageException {\n\n return this.generateSharedAccessSignature(policy, groupPolicyIdentifier, null /* IP range */, null /* protocols */);\n }\n\n /**\n * Returns a shared access signature for the queue.\n * \n * @param policy\n * The access policy for the shared access signature.\n * @param groupPolicyIdentifier\n * A queue-level access policy.\n * @param ipRange\n * A {@link IPRange} object containing the range of allowed IP addresses.\n * @param protocols\n * A {@link SharedAccessProtocols} representing the allowed Internet protocols.\n * \n * @return A shared access signature for the queue.\n * \n * @throws InvalidKeyException\n * If an invalid key was passed.\n * @throws StorageException\n * If a storage service error occurred.\n * @throws IllegalArgumentException\n * If an unexpected value is passed.\n */\n public String generateSharedAccessSignature(\n final SharedAccessQueuePolicy policy, final String groupPolicyIdentifier, final IPRange ipRange,\n final SharedAccessProtocols protocols)\n throws InvalidKeyException, StorageException {\n\n if (!StorageCredentialsHelper.canCredentialsSignRequest(this.queueServiceClient.getCredentials())) {\n final String errorMessage = SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY;\n throw new IllegalArgumentException(errorMessage);\n }\n\n final String resourceName = this.getSharedAccessCanonicalName();\n\n final String signature = SharedAccessSignatureHelper.generateSharedAccessSignatureHashForQueue(\n policy, groupPolicyIdentifier, resourceName, ipRange, protocols, this.queueServiceClient);\n\n final UriQueryBuilder builder = SharedAccessSignatureHelper.generateSharedAccessSignatureForQueue(\n policy, groupPolicyIdentifier, ipRange, protocols, signature);\n\n return builder.toString();\n }\n\n /**\n * Returns the canonical name for shared access.\n * \n * @return the canonical name for shared access.\n */\n private String getSharedAccessCanonicalName() {\n String accountName = this.getServiceClient().getCredentials().getAccountName();\n String queueName = this.getName();\n\n return String.format(\"/%s/%s/%s\", SR.QUEUE, accountName, queueName);\n }\n\n /**\n * Returns the transformed URI for the resource if the given credentials require transformation.\n * \n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @return A <code>java.net.URI</code> object that represents the transformed URI.\n * \n * @throws IllegalArgumentException\n * If the URI is not absolute.\n * @throws StorageException\n * If a storage service error occurred.\n * @throws URISyntaxException\n * If the resource URI is invalid.\n */\n private final StorageUri getTransformedAddress(final OperationContext opContext) throws URISyntaxException,\n StorageException {\n return this.queueServiceClient.getCredentials().transformUri(this.getStorageUri(), opContext);\n }\n \n /**\n * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.\n * \n * @param completeUri\n * A {@link StorageUri} object which represents the complete URI.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * @throws StorageException\n * If a storage service error occurred.\n */\n private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials) \n throws StorageException {\n Utility.assertNotNull(\"completeUri\", completeUri);\n\n if (!completeUri.isAbsolute()) {\n throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));\n }\n\n this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);\n \n final StorageCredentialsSharedAccessSignature parsedCredentials = \n SharedAccessSignatureHelper.parseQuery(completeUri);\n\n if (credentials != null && parsedCredentials != null) {\n throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);\n }\n\n try {\n final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());\n this.queueServiceClient = new CloudQueueClient(PathUtility.getServiceClientBaseAddress(\n this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);\n this.name = PathUtility.getContainerNameFromUri(storageUri.getPrimaryUri(), usePathStyleUris);\n }\n catch (final URISyntaxException e) {\n throw Utility.generateNewUnexpectedStorageException(e);\n }\n }\n}", "public final class CloudTable {\n /**\n * The name of the table.\n */\n private String name;\n\n /**\n * Holds the list of URIs for all locations.\n */\n private StorageUri storageUri;\n\n /**\n * A reference to the associated service client.\n */\n private CloudTableClient tableServiceClient;\n\n /**\n * Gets the name of the table.\n *\n * @return A <code>String</code> object that represents the name of the table.\n */\n public String getName() {\n return this.name;\n }\n\n /**\n * Gets the table service client associated with this queue.\n *\n * @return A {@link CloudTableClient} object that represents the service client associated with this table.\n */\n public CloudTableClient getServiceClient() {\n return this.tableServiceClient;\n }\n\n /**\n * Returns the list of URIs for all locations.\n *\n * @return A {@link StorageUri} that represents the list of URIs for all locations..\n */\n public final StorageUri getStorageUri() {\n return this.storageUri;\n }\n\n /**\n * Gets the absolute URI for this table.\n *\n * @return A <code>java.net.URI</code> object that represents the URI for this table.\n */\n public URI getUri() {\n return this.storageUri.getPrimaryUri();\n }\n\n /**\n * Creates an instance of the <code>CloudTable</code> class using the specified table URI. The table URI must\n * include a SAS token.\n *\n * @param uri\n * A <code>java.net.URI</code> object that represents the absolute URI of the table.\n *\n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudTable(final URI uri) throws StorageException {\n this(new StorageUri(uri, null));\n }\n\n /**\n * Creates an instance of the <code>CloudTable</code> class using the specified table URI. The table URI must\n * include a SAS token.\n *\n * @param uri\n * A {@link StorageUri} object that represents the absolute URI of the table.\n *\n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudTable(final StorageUri uri) throws StorageException {\n this(uri, (StorageCredentials)null);\n }\n \n /**\n * Creates an instance of the <code>CloudTable</code> class using the specified table URI and credentials.\n *\n * @param uri\n * A <code>java.net.URI</code> object that represents the absolute URI of the table.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n *\n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudTable(final URI uri, final StorageCredentials credentials) throws StorageException {\n this(new StorageUri(uri, null), credentials);\n }\n\n /**\n * Creates an instance of the <code>CloudTable</code> class using the specified table StorageUri and credentials.\n *\n * @param uri\n * A {@link StorageUri} object that represents the absolute StorageUri of the table.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n *\n * @throws StorageException\n * If a storage service error occurred.\n */\n public CloudTable(final StorageUri uri, final StorageCredentials credentials) throws StorageException {\n this.parseQueryAndVerify(uri, credentials);\n }\n\n /**\n * Creates an instance of the <code>CloudTable</code> class using the specified name and client.\n *\n * @param tableName\n * A <code>String</code> which represents the name of the table, which must adhere to table naming rules.\n * The table name should not include any path separator characters (/).\n * Table names are case insensitive, must be unique within an account and must be between 3-63 characters\n * long. Table names must start with an cannot begin with a numeric character and may only contain\n * alphanumeric characters. Some table names are reserved, including \"table\".\n * @param client\n * A {@link CloudTableClient} object that represents the associated service client, and that specifies\n * the endpoint for the Table service.\n *\n * @throws URISyntaxException\n * If the resource URI constructed based on the tableName is invalid.\n * @throws StorageException\n * If a storage service error occurred.\n * @see <a href=\"http://msdn.microsoft.com/library/azure/dd179338.aspx\">Understanding the Table Service Data\n * Model</a>\n */\n protected CloudTable(final String tableName, final CloudTableClient client) throws URISyntaxException,\n StorageException {\n Utility.assertNotNull(\"client\", client);\n Utility.assertNotNull(\"tableName\", tableName);\n\n this.storageUri = PathUtility.appendPathToUri(client.getStorageUri(), tableName);\n this.name = tableName;\n this.tableServiceClient = client;\n }\n\n /**\n * Creates the table in the storage service with default request options.\n * <p>\n * This method invokes the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd135729.aspx\">Create Table</a>\n * REST API to create the specified table, using the Table service endpoint and storage account credentials of this\n * instance.\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void create() throws StorageException {\n this.create(null /* options */, null /* opContext */);\n }\n\n /**\n * Creates the table in the storage service, using the specified {@link TableRequestOptions} and\n * {@link OperationContext}.\n * <p>\n * This method invokes the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd135729.aspx\">Create Table</a>\n * REST API to create the specified table, using the Table service endpoint and storage account credentials of this\n * instance.\n *\n * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the\n * operation.\n *\n * @param options\n * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout\n * settings for the operation. Specify <code>null</code> to use the request options specified on the\n * {@link CloudTableClient}.\n * @param opContext\n * An {@link OperationContext} object for tracking the current operation. Specify <code>null</code> to\n * safely ignore operation context.\n *\n * @throws StorageException\n * If an error occurs accessing the storage service, or because the table cannot be\n * created, or already exists.\n */\n @DoesServiceRequest\n public void create(TableRequestOptions options, OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient);\n\n Utility.assertNotNullOrEmpty(\"tableName\", this.name);\n\n final DynamicTableEntity tableEntry = new DynamicTableEntity();\n tableEntry.getProperties().put(TableConstants.TABLE_NAME, new EntityProperty(this.name));\n\n TableOperation.insert(tableEntry).execute(this.tableServiceClient, TableConstants.TABLES_SERVICE_TABLES_NAME,\n options, opContext);\n }\n\n /**\n * Creates the table in the storage service using default request options if it does not already exist.\n *\n * @return <code>true</code> if the table is created in the storage service; otherwise <code>false</code>.\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean createIfNotExists() throws StorageException {\n return this.createIfNotExists(null /* options */, null /* opContext */);\n }\n\n /**\n * Creates the table in the storage service with the specified request options and operation context, if it does not\n * already exist.\n *\n * @param options\n * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudTableClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @return <code>true</code> if the table did not already exist and was created; otherwise <code>false</code> .\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean createIfNotExists(TableRequestOptions options, OperationContext opContext) throws StorageException {\n options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient);\n\n boolean exists = this.exists(true, options, opContext);\n if (exists) {\n return false;\n }\n else {\n try {\n this.create(options, opContext);\n return true;\n }\n catch (StorageException e) {\n if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT\n && StorageErrorCodeStrings.TABLE_ALREADY_EXISTS.equals(e.getErrorCode())) {\n return false;\n }\n else {\n throw e;\n }\n }\n }\n }\n\n /**\n * Deletes the table from the storage service.\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void delete() throws StorageException {\n this.delete(null /* options */, null /* opContext */);\n }\n\n /**\n * Deletes the table from the storage service, using the specified request options and operation context.\n *\n * @param options\n * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudTableClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public void delete(TableRequestOptions options, OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient);\n\n Utility.assertNotNullOrEmpty(\"tableName\", this.name);\n final DynamicTableEntity tableEntry = new DynamicTableEntity();\n tableEntry.getProperties().put(TableConstants.TABLE_NAME, new EntityProperty(this.name));\n\n TableOperation deleteOp = new TableOperation(tableEntry, TableOperationType.DELETE);\n deleteOp.execute(this.tableServiceClient, TableConstants.TABLES_SERVICE_TABLES_NAME, options, opContext);\n }\n\n /**\n * Deletes the table from the storage service, if it exists.\n *\n * @return <code>true</code> if the table existed in the storage service and has been deleted; otherwise\n * <code>false</code>.\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean deleteIfExists() throws StorageException {\n return this.deleteIfExists(null /* options */, null /* opContext */);\n }\n\n /**\n * Deletes the table from the storage service using the specified request options and operation context, if it\n * exists.\n *\n * @param options\n * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudTableClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @return A value of <code>true</code> if the table existed in the storage service and has been deleted, otherwise\n * <code>false</code>.\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean deleteIfExists(TableRequestOptions options, OperationContext opContext) throws StorageException {\n options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient);\n\n if (this.exists(true, options, opContext)) {\n try {\n this.delete(options, opContext);\n }\n catch (StorageException ex) {\n if (ex.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND\n && StorageErrorCodeStrings.RESOURCE_NOT_FOUND.equals(ex.getErrorCode())) {\n return false;\n }\n else {\n throw ex;\n }\n }\n return true;\n }\n else {\n return false;\n }\n }\n\n /**\n * Executes the specified batch operation on a table as an atomic operation. A batch operation may contain up to 100\n * individual table operations, with the requirement that each operation entity must have same partition key. Only\n * one retrieve operation is allowed per batch. Note that the total payload of a batch operation is limited to 4MB.\n * <p>\n * This method invokes an <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd894038.aspx\">Entity Group\n * Transaction</a> on the REST API to execute the specified batch operation on the table as an atomic unit, using\n * the Table service endpoint and storage account credentials of this instance.\n *\n * @param batch\n * The {@link TableBatchOperation} object representing the operations to execute on the table.\n *\n * @return\n * A <code>java.util.ArrayList</code> of {@link TableResult} that contains the results, in order, of\n * each {@link TableOperation} in the {@link TableBatchOperation} on the named table.\n *\n * @throws StorageException\n * if an error occurs accessing the storage service, or the operation fails.\n */\n @DoesServiceRequest\n public ArrayList<TableResult> execute(final TableBatchOperation batch) throws StorageException {\n return this.execute(batch, null /* options */, null /* opContext */);\n }\n\n /**\n * Executes the specified batch operation on a table as an atomic operation, using the specified\n * {@link TableRequestOptions} and {@link OperationContext}. A batch operation may contain up to 100 individual\n * table operations, with the requirement that each operation entity must have same partition key. Only one retrieve\n * operation is allowed per batch. Note that the total payload of a batch operation is limited to 4MB.\n * <p>\n * This method invokes an <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd894038.aspx\">Entity Group\n * Transaction</a> on the REST API to execute the specified batch operation on the table as an atomic unit, using\n * the Table service endpoint and storage account credentials of this instance.\n *\n * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the\n * operation.\n *\n * @param batch\n * The {@link TableBatchOperation} object representing the operations to execute on the table.\n * @param options\n * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout\n * settings for the operation. Specify <code>null</code> to use the request options specified on the\n * {@link CloudTableClient}.\n * @param opContext\n * An {@link OperationContext} object for tracking the current operation. Specify <code>null</code> to\n * safely ignore operation context.\n *\n * @return\n * A <code>java.util.ArrayList</code> of {@link TableResult} that contains the results, in order, of\n * each {@link TableOperation} in the {@link TableBatchOperation} on the named table.\n *\n * @throws StorageException\n * if an error occurs accessing the storage service, or the operation fails.\n */\n @DoesServiceRequest\n public ArrayList<TableResult> execute(final TableBatchOperation batch, TableRequestOptions options,\n OperationContext opContext) throws StorageException {\n Utility.assertNotNull(\"batch\", batch);\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = TableRequestOptions.populateAndApplyDefaults(options, this.getServiceClient());\n return batch.execute(this.getServiceClient(), this.getName(), options, opContext);\n }\n\n /**\n * Executes the operation on a table.\n * <p>\n * This method will invoke the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179423.aspx\">Table Service\n * REST API</a> to execute the specified operation on the table, using the Table service endpoint and storage\n * account credentials of this instance.\n *\n * @param operation\n * The {@link TableOperation} object representing the operation to execute on the table.\n *\n * @return\n * A {@link TableResult} containing the result of executing the {@link TableOperation} on the table.\n *\n * @throws StorageException\n * if an error occurs accessing the storage service, or the operation fails.\n */\n @DoesServiceRequest\n public TableResult execute(final TableOperation operation) throws StorageException {\n return this.execute(operation, null /* options */, null /* opContext */);\n }\n\n /**\n * Executes the operation on a table, using the specified {@link TableRequestOptions} and {@link OperationContext}.\n * <p>\n * This method will invoke the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179423.aspx\">Table Service\n * REST API</a> to execute the specified operation on the table, using the Table service endpoint and storage\n * account credentials of this instance.\n *\n * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the\n * operation.\n *\n * @param operation\n * The {@link TableOperation} object representing the operation to execute on the table.\n * @param options\n * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout\n * settings for the operation. Specify <code>null</code> to use the request options specified on the\n * {@link CloudTableClient}.\n * @param opContext\n * An {@link OperationContext} object for tracking the current operation. Specify <code>null</code> to\n * safely ignore operation context.\n *\n * @return\n * A {@link TableResult} containing the result of executing the {@link TableOperation} on the table.\n *\n * @throws StorageException\n * if an error occurs accessing the storage service, or the operation fails.\n */\n @DoesServiceRequest\n public TableResult execute(final TableOperation operation, final TableRequestOptions options,\n final OperationContext opContext) throws StorageException {\n Utility.assertNotNull(\"operation\", operation);\n return operation.execute(this.getServiceClient(), this.getName(), options, opContext);\n }\n\n /**\n * Executes a query, applying the specified {@link EntityResolver} to the result.\n * <p>\n * This method will invoke a <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179421.aspx\">Query\n * Entities</a> operation on the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179423.aspx\">Table Service\n * REST API</a> to query the table, using the Table service endpoint and storage account credentials of this\n * instance.\n *\n * @param query\n * A {@link TableQuery} instance specifying the table to query and the query parameters to use.\n * @param resolver\n * An {@link EntityResolver} instance which creates a projection of the table query result entities into\n * the specified type <code>R</code>.\n *\n * @return\n * A collection implementing the <code>Iterable</code> interface containing the projection into type\n * <code>R</code> of the results of executing the query.\n */\n @DoesServiceRequest\n public <R> Iterable<R> execute(final TableQuery<?> query, final EntityResolver<R> resolver) {\n return this.execute(query, resolver, null /* options */, null /* opContext */);\n }\n\n /**\n * Executes a query, applying the specified {@link EntityResolver} to the result, using the\n * specified {@link TableRequestOptions} and {@link OperationContext}.\n * <p>\n * This method will invoke a <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179421.aspx\">Query\n * Entities</a> operation on the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179423.aspx\">Table Service\n * REST API</a> to query the table, using the Table service endpoint and storage account credentials of this\n * instance.\n *\n * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the\n * operation.\n *\n * @param query\n * A {@link TableQuery} instance specifying the table to query and the query parameters to use.\n * @param resolver\n * An {@link EntityResolver} instance which creates a projection of the table query result entities into\n * the specified type <code>R</code>.\n * @param options\n * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout\n * settings for the operation. Specify <code>null</code> to use the request options specified on the\n * {@link CloudTableClient}.\n * @param opContext\n * An {@link OperationContext} object for tracking the current operation. Specify <code>null</code> to\n * safely ignore operation context.\n *\n * @return\n * A collection implementing the <code>Iterable</code> interface containing the projection into type\n * <code>R</code> of the results of executing the query.\n */\n @DoesServiceRequest\n @SuppressWarnings({ \"unchecked\" })\n public <R> Iterable<R> execute(final TableQuery<?> query, final EntityResolver<R> resolver,\n final TableRequestOptions options, final OperationContext opContext) {\n Utility.assertNotNull(\"query\", query);\n Utility.assertNotNull(SR.QUERY_REQUIRES_VALID_CLASSTYPE_OR_RESOLVER, resolver);\n query.setSourceTableName(this.getName());\n return (Iterable<R>) this.getServiceClient().generateIteratorForQuery(query, resolver, options, opContext);\n }\n\n /**\n * Executes a query.\n * <p>\n * This method will invoke a <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179421.aspx\">Query\n * Entities</a> operation on the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179423.aspx\">Table Service\n * REST API</a> to query the table, using the Table service endpoint and storage account credentials of this\n * instance.\n *\n * @param query\n * A {@link TableQuery} instance specifying the table to query and the query parameters to use,\n * specialized for a type T implementing {@link TableEntity}.\n *\n * @return\n * A collection implementing the <code>Iterable</code> interface specialized for type T of the results of\n * executing the query.\n */\n @DoesServiceRequest\n public <T extends TableEntity> Iterable<T> execute(final TableQuery<T> query) {\n return this.execute(query, null /* options */, null /* opContext */);\n }\n\n /**\n * Executes a query, using the specified {@link TableRequestOptions} and {@link OperationContext}.\n * <p>\n * This method will invoke a <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179421.aspx\">Query\n * Entities</a> operation on the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179423.aspx\">Table Service\n * REST API</a> to query the table, using the Table service endpoint and storage account credentials of this\n * instance.\n *\n * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the\n * operation.\n *\n * @param query\n * A {@link TableQuery} instance specifying the table to query and the query parameters to use,\n * specialized for a type T implementing {@link TableEntity}.\n * @param options\n * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout\n * settings for the operation. Specify <code>null</code> to use the request options specified on the\n * {@link CloudTableClient}.\n * @param opContext\n * An {@link OperationContext} object for tracking the current operation. Specify <code>null</code> to\n * safely ignore operation context.\n *\n * @return\n * A collection implementing the <code>Iterable</code> interface specialized for type T of the results of\n * executing the query.\n */\n @SuppressWarnings({ \"unchecked\" })\n @DoesServiceRequest\n public <T extends TableEntity> Iterable<T> execute(final TableQuery<T> query, final TableRequestOptions options,\n final OperationContext opContext) {\n Utility.assertNotNull(\"query\", query);\n Utility.assertNotNull(SR.QUERY_REQUIRES_VALID_CLASSTYPE_OR_RESOLVER, query.getClazzType());\n query.setSourceTableName(this.getName());\n return (Iterable<T>) this.getServiceClient().generateIteratorForQuery(query, null, options, opContext);\n }\n\n /**\n * Executes a query in segmented mode with the specified {@link ResultContinuation} continuation token,\n * applying the {@link EntityResolver} to the result.\n * Executing a query with <code>executeSegmented</code> allows the query to be resumed after returning partial\n * results, using information returned by the server in the {@link ResultSegment} object.\n * <p>\n * This method will invoke a <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179421.aspx\">Query\n * Entities</a> operation on the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179423.aspx\">Table Service\n * REST API</a> to query the table, using the Table service endpoint and storage account credentials of this\n * instance.\n *\n * @param query\n * A {@link TableQuery} instance specifying the table to query and the query parameters to use.\n * @param resolver\n * An {@link EntityResolver} instance which creates a projection of the table query result entities into\n * the specified type <code>R</code>.\n * @param continuationToken\n * A {@link ResultContinuation} object representing a continuation token from the server when the\n * operation returns a partial result. Specify <code>null</code> on the initial call. Call the\n * {@link ResultSegment#getContinuationToken()} method on the result to obtain the\n * {@link ResultContinuation} object to use in the next call to resume the query.\n *\n * @return\n * A {@link ResultSegment} containing the projection into type <code>R</code> of the results of executing\n * the query.\n *\n * @throws StorageException\n * if a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public <R> ResultSegment<R> executeSegmented(final TableQuery<?> query, final EntityResolver<R> resolver,\n final ResultContinuation continuationToken) throws StorageException {\n return this.executeSegmented(query, resolver, continuationToken, null /* options */, null /* opContext */);\n }\n\n /**\n * Executes a query in segmented mode with the specified {@link ResultContinuation} continuation token,\n * using the specified {@link TableRequestOptions} and {@link OperationContext}, applying the {@link EntityResolver}\n * to the result.\n * Executing a query with <code>executeSegmented</code> allows the query to be resumed after returning partial\n * results, using information returned by the server in the {@link ResultSegment} object.\n * <p>\n * This method will invoke a <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179421.aspx\">Query\n * Entities</a> operation on the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179423.aspx\">Table Service\n * REST API</a> to query the table, using the Table service endpoint and storage account credentials of this\n * instance.\n *\n * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the\n * operation.\n *\n * @param query\n * A {@link TableQuery} instance specifying the table to query and the query parameters to use.\n * @param resolver\n * An {@link EntityResolver} instance which creates a projection of the table query result entities into\n * the specified type <code>R</code>.\n * @param continuationToken\n * A {@link ResultContinuation} object representing a continuation token from the server when the\n * operation returns a partial result. Specify <code>null</code> on the initial call. Call the\n * {@link ResultSegment#getContinuationToken()} method on the result to obtain the\n * {@link ResultContinuation} object to use in the next call to resume the query.\n * @param options\n * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout\n * settings for the operation. Specify <code>null</code> to use the request options specified on the\n * {@link CloudTableClient}.\n * @param opContext\n * An {@link OperationContext} object for tracking the current operation. Specify <code>null</code> to\n * safely ignore operation context.\n *\n * @return\n * A {@link ResultSegment} containing the projection into type <code>R</code> of the results of executing\n * the query.\n *\n * @throws StorageException\n * if a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n @SuppressWarnings({ \"unchecked\" })\n public <R> ResultSegment<R> executeSegmented(final TableQuery<?> query, final EntityResolver<R> resolver,\n final ResultContinuation continuationToken, final TableRequestOptions options,\n final OperationContext opContext) throws StorageException {\n Utility.assertNotNull(SR.QUERY_REQUIRES_VALID_CLASSTYPE_OR_RESOLVER, resolver);\n query.setSourceTableName(this.getName());\n return (ResultSegment<R>) this.getServiceClient().executeQuerySegmentedImpl(query, resolver, continuationToken,\n options, opContext);\n }\n\n /**\n * Executes a query in segmented mode with a {@link ResultContinuation} continuation token.\n * Executing a query with <code>executeSegmented</code> allows the query to be resumed after returning partial\n * results, using information returned by the server in the {@link ResultSegment} object.\n * <p>\n * This method will invoke a <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179421.aspx\">Query\n * Entities</a> operation on the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179423.aspx\">Table Service\n * REST API</a> to query the table, using the Table service endpoint and storage account credentials of this\n * instance.\n *\n * @param query\n * A {@link TableQuery} instance specifying the table to query and the query parameters to use,\n * specialized for a type T implementing {@link TableEntity}.\n * @param continuationToken\n * A {@link ResultContinuation} object representing a continuation token from the server when the\n * operation returns a partial result. Specify <code>null</code> on the initial call. Call the\n * {@link ResultSegment#getContinuationToken()} method on the result to obtain the\n * {@link ResultContinuation} object to use in the next call to resume the query.\n *\n * @return\n * A {@link ResultSegment} specialized for type T of the results of executing the query.\n *\n * @throws StorageException\n * if a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public <T extends TableEntity> ResultSegment<T> executeSegmented(final TableQuery<T> query,\n final ResultContinuation continuationToken) throws StorageException {\n return this.executeSegmented(query, continuationToken, null /* options */, null /* opContext */);\n }\n\n /**\n * Executes a query in segmented mode with a {@link ResultContinuation} continuation token,\n * using the specified {@link TableRequestOptions} and {@link OperationContext}.\n * Executing a query with <code>executeSegmented</code> allows the query to be resumed after returning partial\n * results, using information returned by the server in the {@link ResultSegment} object.\n * <p>\n * This method will invoke a <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179421.aspx\">Query\n * Entities</a> operation on the <a href=\"http://msdn.microsoft.com/en-us/library/azure/dd179423.aspx\">Table Service\n * REST API</a> to query the table, using the Table service endpoint and storage account credentials of this\n * instance.\n *\n * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the\n * operation.\n *\n * @param query\n * A {@link TableQuery} instance specifying the table to query and the query parameters to use,\n * specialized for a type T implementing {@link TableEntity}.\n * @param continuationToken\n * A {@link ResultContinuation} object representing a continuation token from the server when the\n * operation returns a partial result. Specify <code>null</code> on the initial call. Call the\n * {@link ResultSegment#getContinuationToken()} method on the result to obtain the\n * {@link ResultContinuation} object to use in the next call to resume the query.\n * @param options\n * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout\n * settings for the operation. Specify <code>null</code> to use the request options specified on the\n * {@link CloudTableClient}.\n * @param opContext\n * An {@link OperationContext} object for tracking the current operation. Specify <code>null</code> to\n * safely ignore operation context.\n *\n * @return\n * A {@link ResultSegment} specialized for type T of the results of executing the query.\n *\n * @throws StorageException\n * if a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n @SuppressWarnings({ \"unchecked\" })\n public <T extends TableEntity> ResultSegment<T> executeSegmented(final TableQuery<T> query,\n final ResultContinuation continuationToken, final TableRequestOptions options,\n final OperationContext opContext) throws StorageException {\n Utility.assertNotNull(\"query\", query);\n query.setSourceTableName(this.getName());\n return (ResultSegment<T>) this.getServiceClient().executeQuerySegmentedImpl(query, null, continuationToken,\n options, opContext);\n }\n\n /**\n * Returns a value that indicates whether the table exists in the storage service.\n *\n * @return <code>true</code> if the table exists in the storage service; otherwise <code>false</code>.\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean exists() throws StorageException {\n return this.exists(null /* options */, null /* opContext */);\n }\n\n /**\n * Returns a value that indicates whether the table exists in the storage service, using the specified request\n * options and operation context.\n *\n * @param options\n * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudTableClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @return <code>true</code> if the table exists in the storage service, otherwise <code>false</code>.\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n public boolean exists(TableRequestOptions options, OperationContext opContext) throws StorageException {\n return this.exists(false, options, opContext);\n }\n\n /**\n * Returns a value that indicates whether the table exists in the storage service, using the specified request\n * options and operation context.\n *\n * @param options\n * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudTableClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @return <code>true</code> if the table exists in the storage service, otherwise <code>false</code>.\n *\n * @throws StorageException\n * If a storage service error occurred during the operation.\n */\n @DoesServiceRequest\n private boolean exists(final boolean primaryOnly, TableRequestOptions options, OperationContext opContext)\n throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient);\n\n Utility.assertNotNullOrEmpty(\"tableName\", this.name);\n\n QueryTableOperation operation = (QueryTableOperation) TableOperation.retrieve(this.name /* Used As PK */,\n null/* Row Key */, DynamicTableEntity.class);\n operation.setPrimaryOnlyRetrieve(primaryOnly);\n\n final TableResult result = operation.execute(this.tableServiceClient,\n TableConstants.TABLES_SERVICE_TABLES_NAME, options, opContext);\n\n if (result.getHttpStatusCode() == HttpURLConnection.HTTP_OK) {\n return true;\n }\n else if (result.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {\n return false;\n }\n else {\n throw new StorageException(StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, SR.UNEXPECTED_STATUS_CODE_RECEIVED,\n result.getHttpStatusCode(), null /* extendedErrorInfo */, null /* innerException */);\n }\n }\n\n /**\n * Uploads the table's permissions.\n *\n * @param permissions\n * A {@link TablePermissions} object that represents the permissions to upload.\n *\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadPermissions(final TablePermissions permissions) throws StorageException {\n this.uploadPermissions(permissions, null /* options */, null /* opContext */);\n }\n\n /**\n * Uploads the table's permissions using the specified request options and operation context.\n *\n * @param permissions\n * A {@link TablePermissions} object that represents the permissions to upload.\n * @param options\n * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudTableClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public void uploadPermissions(final TablePermissions permissions, TableRequestOptions options,\n OperationContext opContext) throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient);\n\n ExecutionEngine.executeWithRetry(this.tableServiceClient, this,\n this.uploadPermissionsImpl(permissions, options), options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudTableClient, CloudTable, Void> uploadPermissionsImpl(\n final TablePermissions permissions, final TableRequestOptions options) throws StorageException {\n final StringWriter outBuffer = new StringWriter();\n\n try {\n SharedAccessPolicySerializer.writeSharedAccessIdentifiersToStream(permissions.getSharedAccessPolicies(),\n outBuffer);\n final byte[] aclBytes = outBuffer.toString().getBytes(Constants.UTF8_CHARSET);\n\n final StorageRequest<CloudTableClient, CloudTable, Void> putRequest = new StorageRequest<CloudTableClient, CloudTable, Void>(\n options, this.getStorageUri()) {\n\n @Override\n public HttpURLConnection buildRequest(CloudTableClient client, CloudTable table,\n OperationContext context) throws Exception {\n this.setSendStream(new ByteArrayInputStream(aclBytes));\n this.setLength((long) aclBytes.length);\n return TableRequest.setAcl(table.getStorageUri().getUri(this.getCurrentLocation()), options,\n context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudTableClient client, OperationContext context)\n throws Exception {\n StorageRequest.signTableRequest(connection, client, aclBytes.length, context);\n }\n\n @Override\n public Void preProcessResponse(CloudTable parentObject, CloudTableClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return null;\n }\n \n @Override\n public StorageExtendedErrorInformation parseErrorDetails() {\n return TableStorageErrorDeserializer.parseErrorDetails(this);\n }\n };\n\n return putRequest;\n }\n catch (IllegalArgumentException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IllegalStateException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n catch (IOException e) {\n // The request was not even made. There was an error while trying to write the message. Just throw.\n StorageException translatedException = StorageException.translateClientException(e);\n throw translatedException;\n }\n }\n\n /**\n * Downloads the permission settings for the table.\n *\n * @return A {@link TablePermissions} object that represents the container's permissions.\n *\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public TablePermissions downloadPermissions() throws StorageException {\n return this.downloadPermissions(null /* options */, null /* opContext */);\n }\n\n /**\n * Downloads the permissions settings for the table using the specified request options and operation context.\n *\n * @param options\n * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying\n * <code>null</code> will use the default request options from the associated service client (\n * {@link CloudTableClient}).\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n *\n * @return A {@link TablePermissions} object that represents the table's permissions.\n *\n * @throws StorageException\n * If a storage service error occurred.\n */\n @DoesServiceRequest\n public TablePermissions downloadPermissions(TableRequestOptions options, OperationContext opContext)\n throws StorageException {\n if (opContext == null) {\n opContext = new OperationContext();\n }\n\n opContext.initialize();\n options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient);\n\n return ExecutionEngine.executeWithRetry(this.tableServiceClient, this, this.downloadPermissionsImpl(options),\n options.getRetryPolicyFactory(), opContext);\n }\n\n private StorageRequest<CloudTableClient, CloudTable, TablePermissions> downloadPermissionsImpl(\n final TableRequestOptions options) {\n final StorageRequest<CloudTableClient, CloudTable, TablePermissions> getRequest = new StorageRequest<CloudTableClient, CloudTable, TablePermissions>(\n options, this.getStorageUri()) {\n\n @Override\n public void setRequestLocationMode() {\n this.setRequestLocationMode(RequestLocationMode.PRIMARY_OR_SECONDARY);\n }\n\n @Override\n public HttpURLConnection buildRequest(CloudTableClient client, CloudTable table, OperationContext context)\n throws Exception {\n return TableRequest.getAcl(table.getStorageUri().getUri(this.getCurrentLocation()), options, context);\n }\n\n @Override\n public void signRequest(HttpURLConnection connection, CloudTableClient client, OperationContext context)\n throws Exception {\n StorageRequest.signTableRequest(connection, client, -1L, context);\n }\n\n @Override\n public TablePermissions preProcessResponse(CloudTable parentObject, CloudTableClient client,\n OperationContext context) throws Exception {\n if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) {\n this.setNonExceptionedRetryableFailure(true);\n }\n\n return new TablePermissions();\n }\n\n @Override\n public TablePermissions postProcessResponse(HttpURLConnection connection, CloudTable table,\n CloudTableClient client, OperationContext context, TablePermissions permissions) throws Exception {\n HashMap<String, SharedAccessTablePolicy> accessIds = SharedAccessPolicyHandler.getAccessIdentifiers(\n this.getConnection().getInputStream(), SharedAccessTablePolicy.class);\n for (final String key : accessIds.keySet()) {\n permissions.getSharedAccessPolicies().put(key, accessIds.get(key));\n }\n\n return permissions;\n }\n \n @Override\n public StorageExtendedErrorInformation parseErrorDetails() {\n return TableStorageErrorDeserializer.parseErrorDetails(this);\n }\n };\n\n return getRequest;\n }\n\n /**\n * Creates a shared access signature for the table.\n *\n * @param policy\n * A {@link SharedAccessTablePolicy} object which represents the access policy for the shared access\n * signature.\n * @param accessPolicyIdentifier\n * A <code>String</code> which represents a table-level access policy.\n * @param startPartitionKey\n * A <code>String</code> which represents the starting partition key.\n * @param startRowKey\n * A <code>String</code> which represents the starting row key.\n * @param endPartitionKey\n * A <code>String</code> which represents the ending partition key.\n * @param endRowKey\n * A <code>String</code> which represents the ending end key.\n *\n * @return A <code>String</code> containing the shared access signature for the table.\n *\n * @throws InvalidKeyException\n * If an invalid key was passed.\n * @throws StorageException\n * If a storage service error occurred.\n * @throws IllegalArgumentException\n * If an unexpected value is passed.\n */\n public String generateSharedAccessSignature(final SharedAccessTablePolicy policy,\n final String accessPolicyIdentifier, final String startPartitionKey, final String startRowKey,\n final String endPartitionKey, final String endRowKey) throws InvalidKeyException, StorageException {\n \n return generateSharedAccessSignature(policy, accessPolicyIdentifier,\n startPartitionKey, startRowKey, endPartitionKey, endRowKey, null /* IP Range */, null /* Protocols */);\n }\n\n /**\n * Creates a shared access signature for the table.\n *\n * @param policy\n * A {@link SharedAccessTablePolicy} object which represents the access policy for the shared access\n * signature.\n * @param accessPolicyIdentifier\n * A <code>String</code> which represents a table-level access policy.\n * @param startPartitionKey\n * A <code>String</code> which represents the starting partition key.\n * @param startRowKey\n * A <code>String</code> which represents the starting row key.\n * @param endPartitionKey\n * A <code>String</code> which represents the ending partition key.\n * @param endRowKey\n * A <code>String</code> which represents the ending end key.\n * @param ipRange\n * A {@link IPRange} object containing the range of allowed IP addresses.\n * @param protocols\n * A {@link SharedAccessProtocols} representing the allowed Internet protocols.\n *\n * @return A <code>String</code> containing the shared access signature for the table.\n *\n * @throws InvalidKeyException\n * If an invalid key was passed.\n * @throws StorageException\n * If a storage service error occurred.\n * @throws IllegalArgumentException\n * If an unexpected value is passed.\n */\n public String generateSharedAccessSignature(\n final SharedAccessTablePolicy policy, final String accessPolicyIdentifier, final String startPartitionKey,\n final String startRowKey, final String endPartitionKey, final String endRowKey, final IPRange ipRange,\n final SharedAccessProtocols protocols)\n throws InvalidKeyException, StorageException {\n\n if (!StorageCredentialsHelper.canCredentialsSignRequest(this.tableServiceClient.getCredentials())) {\n throw new IllegalArgumentException(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY);\n }\n\n final String resourceName = this.getSharedAccessCanonicalName();\n\n final String signature = SharedAccessSignatureHelper.generateSharedAccessSignatureHashForTable(\n policy, accessPolicyIdentifier, resourceName, ipRange, protocols,\n startPartitionKey, startRowKey, endPartitionKey, endRowKey, this.tableServiceClient);\n\n final UriQueryBuilder builder = SharedAccessSignatureHelper.generateSharedAccessSignatureForTable(\n policy, startPartitionKey, startRowKey, endPartitionKey, endRowKey, accessPolicyIdentifier,\n ipRange, protocols, this.name, signature);\n\n return builder.toString();\n }\n\n /**\n * Returns the canonical name for shared access.\n *\n * @return A <code>String</code> containing the canonical name for shared access.\n */\n private String getSharedAccessCanonicalName() {\n String accountName = this.getServiceClient().getCredentials().getAccountName();\n String tableNameLowerCase = this.getName().toLowerCase(Locale.ENGLISH);\n\n return String.format(\"/%s/%s/%s\", SR.TABLE, accountName, tableNameLowerCase);\n }\n\n /**\n * Verifies the passed in URI. Then parses it and uses its components to populate this resource's properties.\n * \n * @param completeUri\n * A {@link StorageUri} object which represents the complete URI.\n * @param credentials\n * A {@link StorageCredentials} object used to authenticate access.\n * @throws StorageException\n * If a storage service error occurred.\n */ \n private void parseQueryAndVerify(final StorageUri completeUri, final StorageCredentials credentials) \n throws StorageException {\n Utility.assertNotNull(\"completeUri\", completeUri);\n\n if (!completeUri.isAbsolute()) {\n throw new IllegalArgumentException(String.format(SR.RELATIVE_ADDRESS_NOT_PERMITTED, completeUri.toString()));\n }\n\n this.storageUri = PathUtility.stripURIQueryAndFragment(completeUri);\n \n final StorageCredentialsSharedAccessSignature parsedCredentials = \n SharedAccessSignatureHelper.parseQuery(completeUri);\n\n if (credentials != null && parsedCredentials != null) {\n throw new IllegalArgumentException(SR.MULTIPLE_CREDENTIALS_PROVIDED);\n }\n\n try {\n final boolean usePathStyleUris = Utility.determinePathStyleFromUri(this.storageUri.getPrimaryUri());\n this.tableServiceClient = new CloudTableClient(PathUtility.getServiceClientBaseAddress(\n this.getStorageUri(), usePathStyleUris), credentials != null ? credentials : parsedCredentials);\n this.name = PathUtility.getTableNameFromUri(storageUri.getPrimaryUri(), usePathStyleUris);\n }\n catch (final URISyntaxException e) {\n throw Utility.generateNewUnexpectedStorageException(e);\n }\n }\n}" ]
import com.microsoft.azure.storage.TestRunners.CloudTests; import com.microsoft.azure.storage.TestRunners.DevFabricTests; import com.microsoft.azure.storage.TestRunners.DevStoreTests; import com.microsoft.azure.storage.blob.CloudBlobClient; import com.microsoft.azure.storage.blob.CloudBlobContainer; import com.microsoft.azure.storage.blob.CloudBlobDirectory; import com.microsoft.azure.storage.blob.CloudBlockBlob; import com.microsoft.azure.storage.blob.CloudPageBlob; import com.microsoft.azure.storage.core.SR; import com.microsoft.azure.storage.queue.CloudQueue; import com.microsoft.azure.storage.queue.CloudQueueClient; import com.microsoft.azure.storage.table.CloudTable; import com.microsoft.azure.storage.table.CloudTableClient; import org.junit.Test; import org.junit.experimental.categories.Category; import java.net.URI; import java.net.URISyntaxException; import java.security.InvalidKeyException; import static org.junit.Assert.*;
/** * Copyright Microsoft Corporation * * 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.microsoft.azure.storage; @Category({ DevFabricTests.class, DevStoreTests.class, CloudTests.class }) public class StorageUriTests { private static final String ACCOUNT_NAME = "account"; private static final String SECONDARY_SUFFIX = "-secondary"; private static final String ENDPOINT_SUFFIX = ".core.windows.net"; private static final String BLOB_SERVICE = ".blob"; private static final String QUEUE_SERVICE = ".queue"; private static final String TABLE_SERVICE = ".table"; @Test public void testStorageUriWithTwoUris() throws URISyntaxException { URI primaryClientUri = new URI("http://" + ACCOUNT_NAME + BLOB_SERVICE + ENDPOINT_SUFFIX); URI primaryContainerUri = new URI(primaryClientUri + "/container"); URI secondaryClientUri = new URI("http://" + ACCOUNT_NAME + SECONDARY_SUFFIX + BLOB_SERVICE + ENDPOINT_SUFFIX); URI dummyClientUri = new URI("http://" + ACCOUNT_NAME + "-dummy" + BLOB_SERVICE + ENDPOINT_SUFFIX); // no uri try { new StorageUri(null, null); fail(SR.STORAGE_URI_NOT_NULL); } catch (IllegalArgumentException ex) { assertEquals(SR.STORAGE_URI_NOT_NULL, ex.getMessage()); } // primary uri only StorageUri singleUri = new StorageUri(primaryClientUri); assertEquals(primaryClientUri, singleUri.getPrimaryUri()); assertNull(singleUri.getSecondaryUri()); StorageUri singleUri2 = new StorageUri(primaryClientUri); assertEquals(singleUri, singleUri2); StorageUri singleUri3 = new StorageUri(secondaryClientUri); assertFalse(singleUri.equals(singleUri3)); // secondary uri only StorageUri singleSecondaryUri = new StorageUri(null, secondaryClientUri); assertEquals(secondaryClientUri, singleSecondaryUri.getSecondaryUri()); assertNull(singleSecondaryUri.getPrimaryUri()); StorageUri singleSecondarUri2 = new StorageUri(null, secondaryClientUri); assertEquals(singleSecondaryUri, singleSecondarUri2); StorageUri singleSecondarUri3 = new StorageUri(null, primaryClientUri); assertFalse(singleSecondaryUri.equals(singleSecondarUri3)); // primary and secondary uri StorageUri multiUri = new StorageUri(primaryClientUri, secondaryClientUri); assertEquals(primaryClientUri, multiUri.getPrimaryUri()); assertEquals(secondaryClientUri, multiUri.getSecondaryUri()); assertFalse(multiUri.equals(singleUri)); StorageUri multiUri2 = new StorageUri(primaryClientUri, secondaryClientUri); assertEquals(multiUri, multiUri2); try { new StorageUri(primaryClientUri, primaryContainerUri); fail(SR.STORAGE_URI_MUST_MATCH); } catch (IllegalArgumentException ex) { assertEquals(SR.STORAGE_URI_MUST_MATCH, ex.getMessage()); } StorageUri multiUri3 = new StorageUri(primaryClientUri, dummyClientUri); assertFalse(multiUri.equals(multiUri3)); StorageUri multiUri4 = new StorageUri(dummyClientUri, secondaryClientUri); assertFalse(multiUri.equals(multiUri4)); StorageUri multiUri5 = new StorageUri(secondaryClientUri, primaryClientUri); assertFalse(multiUri.equals(multiUri5)); } @Test public void testDevelopmentStorageWithTwoUris() throws URISyntaxException { CloudStorageAccount account = CloudStorageAccount.getDevelopmentStorageAccount(); URI primaryClientURI = account.getBlobStorageUri().getPrimaryUri(); URI primaryContainerURI = new URI(primaryClientURI.toString() + "/container"); URI secondaryClientURI = account.getBlobStorageUri().getSecondaryUri(); StorageUri singleURI = new StorageUri(primaryClientURI); assertTrue(primaryClientURI.equals(singleURI.getPrimaryUri())); assertNull(singleURI.getSecondaryUri()); StorageUri singleURI2 = new StorageUri(primaryClientURI); assertTrue(singleURI.equals(singleURI2)); StorageUri singleURI3 = new StorageUri(secondaryClientURI); assertFalse(singleURI.equals(singleURI3)); StorageUri multiURI = new StorageUri(primaryClientURI, secondaryClientURI); assertTrue(primaryClientURI.equals(multiURI.getPrimaryUri())); assertTrue(secondaryClientURI.equals(multiURI.getSecondaryUri())); assertFalse(multiURI.equals(singleURI)); StorageUri multiURI2 = new StorageUri(primaryClientURI, secondaryClientURI); assertTrue(multiURI.equals(multiURI2)); try { new StorageUri(primaryClientURI, primaryContainerURI); fail("StorageUri constructor should fail if both URIs do not point to the same resource"); } catch (IllegalArgumentException e) { assertEquals(SR.STORAGE_URI_MUST_MATCH, e.getMessage()); } StorageUri multiURI3 = new StorageUri(secondaryClientURI, primaryClientURI); assertFalse(multiURI.equals(multiURI3)); } @Test public void testCloudStorageAccountWithStorageUri() throws URISyntaxException, InvalidKeyException { StorageUri blobEndpoint = new StorageUri(new URI("http://" + ACCOUNT_NAME + BLOB_SERVICE + ENDPOINT_SUFFIX), new URI("http://" + ACCOUNT_NAME + SECONDARY_SUFFIX + BLOB_SERVICE + ENDPOINT_SUFFIX)); StorageUri queueEndpoint = new StorageUri(new URI("http://" + ACCOUNT_NAME + QUEUE_SERVICE + ENDPOINT_SUFFIX), new URI("http://" + ACCOUNT_NAME + SECONDARY_SUFFIX + QUEUE_SERVICE + ENDPOINT_SUFFIX)); StorageUri tableEndpoint = new StorageUri(new URI("http://" + ACCOUNT_NAME + TABLE_SERVICE + ENDPOINT_SUFFIX), new URI("http://" + ACCOUNT_NAME + SECONDARY_SUFFIX + TABLE_SERVICE + ENDPOINT_SUFFIX)); CloudStorageAccount account = CloudStorageAccount.parse(String.format( "DefaultEndpointsProtocol=http;AccountName=%s;AccountKey=dummyKey", ACCOUNT_NAME)); assertEquals(blobEndpoint, account.getBlobStorageUri()); assertEquals(queueEndpoint, account.getQueueStorageUri()); assertEquals(tableEndpoint, account.getTableStorageUri()); assertEquals(blobEndpoint, account.createCloudBlobClient().getStorageUri()); assertEquals(queueEndpoint, account.createCloudQueueClient().getStorageUri()); assertEquals(tableEndpoint, account.createCloudTableClient().getStorageUri()); assertEquals(blobEndpoint.getPrimaryUri(), account.getBlobEndpoint()); assertEquals(queueEndpoint.getPrimaryUri(), account.getQueueEndpoint()); assertEquals(tableEndpoint.getPrimaryUri(), account.getTableEndpoint()); } @Test public void testBlobTypesWithStorageUri() throws StorageException, URISyntaxException { CloudBlobClient blobClient = TestHelper.createCloudBlobClient(); StorageUri endpoint = new StorageUri(new URI("http://" + ACCOUNT_NAME + BLOB_SERVICE + ENDPOINT_SUFFIX), new URI("http://" + ACCOUNT_NAME + SECONDARY_SUFFIX + BLOB_SERVICE + ENDPOINT_SUFFIX)); CloudBlobClient client = new CloudBlobClient(endpoint, blobClient.getCredentials()); assertEquals(endpoint, client.getStorageUri()); assertEquals(endpoint.getPrimaryUri(), client.getEndpoint()); StorageUri containerUri = new StorageUri(new URI(endpoint.getPrimaryUri() + "/container"), new URI( endpoint.getSecondaryUri() + "/container"));
CloudBlobContainer container = client.getContainerReference("container");
3
JavaMoney/javamoney-shelter
retired/format/src/main/java/org/javamoney/format/internal/DefaultTokenizeableFormatsSingletonSpi.java
[ "public interface ItemFormat<T> {\n\n\t/**\n\t * Return the target type this {@link ItemFormat} is expecting and capable\n\t * to format.\n\t * \n\t * @return the target type, never {@code null}.\n\t */\n\tpublic Class<T> getTargetClass();\n\n\t/**\n\t * Access the {@link LocalizationContext} configuring this {@link ItemFormat}.\n\t * \n\t * @return Returns the {@link LocalizationContext} attached to this\n\t * {@link ItemFormat}, never {@code null}.\n\t */\n\tpublic LocalizationContext getStyle();\n\n\t/**\n\t * Formats a value of {@code T} to a {@code String}. The {@link Locale}\n\t * passed defines the overall target {@link Locale}, whereas the\n\t * {@link LocalizationContext} attached with the instances configures, how the\n\t * {@link ItemFormat} should generally behave. The {@link LocalizationContext}\n\t * allows to configure the formatting and parsing in arbitrary details. The\n\t * attributes that are supported are determined by the according\n\t * {@link ItemFormat} implementation:\n\t * <ul>\n\t * <li>When the {@link ItemFormat} was created using the\n\t * {@link ItemFormatBuilder}, all the {@link StyleableItemFormatToken}, that model the\n\t * overall format, and the {@link ParseResultFactory}, that is responsible for\n\t * extracting the final parsing result, returned from a parsing call, are\n\t * all possible recipients for attributes of the configuring\n\t * {@link LocalizationContext}.\n\t * <li>When the {@link ItemFormat} was provided by an instance of\n\t * {@link ItemFormatFactorySpi} the {@link ItemFormat} returned determines\n\t * the capabilities that can be configured.\n\t * </ul>\n\t * \n\t * So, regardless if an {@link ItemFormat} is created using the fluent style\n\t * {@link ItemFormatBuilder} pattern, or provided as preconfigured\n\t * implementation, {@link LocalizationContext}s allow to configure them both\n\t * effectively.\n\t * \n\t * @param item\n\t * the item to print, not {@code null}\n\t * @return the string printed using the settings of this formatter\n\t * @throws UnsupportedOperationException\n\t * if the formatter is unable to print\n\t * @throws ItemFormatException\n\t * if there is a problem while printing\n\t */\n\tpublic String format(T item, Locale locale);\n\n\t/**\n\t * Prints a item value to an {@code Appendable}.\n\t * <p>\n\t * Example implementations of {@code Appendable} are {@code StringBuilder},\n\t * {@code StringBuffer} or {@code Writer}. Note that {@code StringBuilder}\n\t * and {@code StringBuffer} never throw an {@code IOException}.\n\t * \n\t * @param appendable\n\t * the appendable to add to, not null\n\t * @param item\n\t * the item to print, not null\n\t * @param locale\n\t * the main target {@link Locale} to be used, not {@code null}\n\t * @throws UnsupportedOperationException\n\t * if the formatter is unable to print\n\t * @throws ItemFormatException\n\t * if there is a problem while printing\n\t * @throws IOException\n\t * if an IO error occurs\n\t */\n\tpublic void print(Appendable appendable, T item, Locale locale)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Fully parses the text into an instance of {@code T}.\n\t * <p>\n\t * The parse must complete normally and parse the entire text. If the parse\n\t * completes without reading the entire length of the text, an exception is\n\t * thrown. If any other problem occurs during parsing, an exception is\n\t * thrown.\n\t * <p>\n\t * This method uses a {@link Locale} as an input parameter. Additionally the\n\t * {@link ItemFormatException} instance is configured by a\n\t * {@link LocalizationContext}. {@link LocalizationContext}s allows to configure\n\t * formatting input in detail. This allows to implement complex formatting\n\t * requirements using this interface.\n\t * \n\t * @param text\n\t * the text to parse, not null\n\t * @param locale\n\t * the main target {@link Locale} to be used, not {@code null}\n\t * @return the parsed value, never {@code null}\n\t * @throws UnsupportedOperationException\n\t * if the formatter is unable to parse\n\t * @throws ItemParseException\n\t * if there is a problem while parsing\n\t */\n\tpublic T parse(CharSequence text, Locale locale) throws ItemParseException;\n\n}", "public class ItemFormatException extends MonetaryException {\n\n /**\n\t * serialVersionUID.\n\t */\n\tprivate static final long serialVersionUID = -2966663514205132233L;\n\n\t/**\n * Constructor taking a message.\n * \n * @param message the message\n */\n public ItemFormatException(String message) {\n \tsuper(message);\n }\n\n /**\n * Constructor taking a message and cause.\n * \n * @param message the message\n * @param cause the exception cause\n */\n public ItemFormatException(String message, Throwable cause) {\n \tsuper(message, cause);\n }\n\n //-----------------------------------------------------------------------\n /**\n * Checks if the cause of this exception was an IOException, and if so re-throws it\n * <p>\n * This method is useful if you call a printer with an open stream or\n * writer and want to ensure that IOExceptions are not lost.\n * <pre>\n * try {\n * printer.print(writer, money);\n * } catch (CalendricalFormatException ex) {\n * ex.rethrowIOException();\n * // if code reaches here exception was caused by issues other than IO\n * }\n * </pre>\n * Note that calling this method will re-throw the original IOException,\n * causing this MoneyFormatException to be lost.\n *\n * @throws IOException if the cause of this exception is an IOException\n */\n public void rethrowIOException() throws IOException {\n \t// TODO Not Implemented yet\n }\n\n}", "public final class LocalizationContext extends AbstractContext implements Serializable{\n\n /**\n * serialVersionUID.\n */\n private static final long serialVersionUID = 8612440355369457473L;\n\n private static final Logger LOG = LoggerFactory.getLogger(LocalizationContext.class);\n\n /**\n * the default id.\n */\n public static final String DEFAULT_ID = \"default\";\n\n /**\n * The style's name, by default ({@link #DEFAULT_ID}.\n */\n private String id = DEFAULT_ID;\n\n /**\n * The style's target type.\n */\n private Class<?> targetType;\n\n\n /**\n * The shared map of LocalizationStyle instances.\n */\n private static final Map<String,LocalizationContext> STYLE_MAP =\n new ConcurrentHashMap<String,LocalizationContext>();\n\n /**\n * Access a cached <i>default</i> style for a type. This equals to\n * {@link #of(Class, String)}, hereby passing\n * {@link LocalizationContext#DEFAULT_ID} as {@code styleId}.\n *\n * @param targetType The target type, not {@code null}.\n * @param styleId The style's id, not {@code null}.\n * @return the according style, if a corresponding style is cached, or\n * {@code null].\n */\n public static final LocalizationContext of(Class<?> targetType, String styleId){\n return STYLE_MAP.get(getKey(targetType, styleId));\n }\n\n /**\n * Access a cached <i>default</i> style for a type. This equals to\n * {@link #of(Class, String)}, hereby passing\n * {@link LocalizationContext#DEFAULT_ID} as {@code styleId}.\n *\n * @param targetType The target type, not {@code null}.\n * @return the according style, if a corresponding style is cached, or\n * {@code null].\n */\n public static final LocalizationContext of(Class<?> targetType){\n return of(targetType, LocalizationContext.DEFAULT_ID);\n }\n\n /**\n * Collects all styles currently registered within the style cache for the\n * given type.\n *\n * @param targetType the target type, not {@code null}.\n * @return a set of style identifiers for the given type, never null.\n */\n public static Collection<String> getSupportedStyleIds(Class<?> targetType){\n Set<String> result = new HashSet<String>();\n String className = targetType.getName();\n for(String key : STYLE_MAP.keySet()){\n int index = key.indexOf('_');\n if(className.equals(key.substring(0, index))){\n result.add(key.substring(index + 1));\n }\n }\n return result;\n }\n\n /**\n * Access a cached style for a type.\n *\n * @param targetType The target type, not {@code null}.\n * @param styleId The style's id, not {@code null}.\n * @return the according style, if a corresponding style is cached, or\n * {@code null].\n */\n private static String getKey(Class<?> targetType, String styleId){\n return targetType.getName() + \"_\" + (styleId != null ? styleId : \"default\");\n }\n\n /**\n * Creates a new instance of a style.\n *\n * @param builder The style's builder (not null).\n */\n private LocalizationContext(Builder builder){\n super(builder);\n this.id = builder.id;\n this.targetType = builder.targetType;\n }\n\n /**\n * Get the style's identifier, not null.\n *\n * @return the style's id.\n */\n public String getId(){\n return id;\n }\n\n /**\n * Get the style's target type used.\n *\n * @return the translation (default) locale\n */\n public final Class<?> getTargetType(){\n return this.targetType;\n }\n\n /**\n * Access the ItemFormat class that should be instantiated by default for formatting this style.\n *\n * @return the default item format class, or null.\n */\n public final Class<? extends ItemFormat<?>> getDefaultItemFormatClass(){\n String defaultItemFormatClassName = getText(\"defaultItemFormatClassName\");\n if(defaultItemFormatClassName != null){\n try{\n return (Class<? extends ItemFormat<?>>) Class.forName(defaultItemFormatClassName);\n }\n catch(Exception e){\n LOG.error(\"Failed to load ItemFormat class: \" + defaultItemFormatClassName, e);\n }\n }\n return getAny(\"defaultItemFormatClass\", Class.class);\n }\n\n\n /**\n * Method allows to check, if a given style is a default style, which is\n * equivalent to a style id equal to {@link #DEFAULT_ID}.\n *\n * @return true, if the instance is a default style.\n */\n public boolean isDefaultStyle(){\n return DEFAULT_ID.equals(getId());\n }\n\n /**\n * Builder to of new instances of {@link LocalizationContext}.\n * <p>\n * This class is not thread-safe and should not be used in multiple threads.\n * However {@link LocalizationContext} instances created can securely shared\n * among threads.\n *\n * @author Anatole Tresch\n */\n public static final class Builder extends AbstractContextBuilder<Builder,LocalizationContext>{\n /**\n * The style's id.\n */\n private String id = DEFAULT_ID;\n\n /**\n * The formated type.\n */\n private Class<?> targetType;\n\n /**\n * The default class of ItemFormat to be used.\n */\n private Class<? extends ItemFormat<?>> defaultItemFormatClass;\n\n /**\n * Constructor.\n *\n * @param targetType the target type, not null.\n */\n public Builder(Class<?> targetType){\n this.targetType = targetType;\n setId(DEFAULT_ID);\n }\n\n /**\n * Constructor.\n *\n * @param styleId The style's id.\n * @param targetType The target TYPE\n * @return the {@link LocalizationContext} created.\n */\n public Builder(Class<?> targetType, String styleId){\n setId(styleId);\n this.targetType = targetType;\n }\n\n /**\n * Creates a new instance of a style. This method will copy all\n * attributes and properties from the given style. The style created\n * will not be read-only, even when the base style is read-only.\n *\n * @param baseContext The style to be used as a base style.\n */\n public Builder(LocalizationContext baseContext){\n importContext(baseContext);\n this.id = baseContext.getId();\n this.targetType = baseContext.getTargetType();\n }\n\n /**\n * Creates a new instance of {@link LocalizationContext}.\n *\n * @return a new instance of {@link LocalizationContext}, never\n * {@code null}\n * @throws IllegalStateException if this builder can not of a new instance.\n */\n public LocalizationContext build(){\n return build(false);\n }\n\n /**\n * Creates a new instance of {@link LocalizationContext}.\n *\n * @param register flag for registering the style into the global cache.\n * @return a new instance of {@link LocalizationContext}, never\n * {@code null}\n * @throws IllegalStateException if this builder can not of a new instance.\n */\n public LocalizationContext build(boolean register){\n LocalizationContext style = new LocalizationContext(this);\n if(register){\n STYLE_MAP.put(getKey(this.targetType, this.id), style);\n }\n return style;\n }\n\n /**\n * Constructor for a <i>default</i> style.\n */\n public Builder(){\n }\n\n /**\n * Method allows to check, if a given style is a default style, which is\n * equivalent to a style {@code id} equal to {@link #DEFAULT_ID}.\n *\n * @return {@code true}, if the instance is a <i>default</i> style.\n */\n public boolean isDefaultStyle(){\n return DEFAULT_ID.equals(getId());\n }\n\n /**\n * Sets the style's id.\n *\n * @param id the style's id, not {@code null}.\n * @return this instance, for chaining.\n */\n public Builder setId(String id){\n Objects.requireNonNull(id, \"style id required.\");\n this.id = id;\n return this;\n }\n\n\n /**\n * Sets the given targetType.\n *\n * @param targetType The instance's targetType, not {@code null}.\n * @return The Builder instance for chaining.\n */\n public <T> Builder setTargetType(Class<?> targetType){\n Objects.requireNonNull(targetType, \"targetType required.\");\n this.targetType = targetType;\n return this;\n }\n\n /**\n * Sets the default formatter to be used by this style.\n *\n * @param itemFormatClass the default formatter class, not null.\n * @param <T> the target type\n * @return The Builder instance for chaining.\n */\n public <T> Builder setDefaultItemFormat(Class<? extends ItemFormat<?>> itemFormatClass){\n Objects.requireNonNull(itemFormatClass);\n this.defaultItemFormatClass = itemFormatClass;\n return this;\n }\n\n /**\n * Get the style's identifier, not {@code null}.\n *\n * @return the style's id.\n */\n public String getId(){\n return id;\n }\n\n }\n\n}", "public interface ItemFormatFactorySpi<T>{\n\n /**\n * Return the target type the owning artifact can be applied to.\n *\n * @return the target type, never {@code null}.\n */\n public Class<T> getTargetClass();\n\n /**\n * Return the style id's supported by this {@link ItemFormatFactorySpi}\n * instance.\n *\n * @return the supported style identifiers, never {@code null}.\n * @see org.javamoney.format.LocalizationContext#getId()\n */\n public Collection<String> getSupportedStyleIds();\n\n /**\n * Access a configured default {@link org.javamoney.format.LocalizationContext} instance. If the\n * required styleId is part of the supported styles returned by this spi\n * implementation, then this method should return the according\n * {@link org.javamoney.format.LocalizationContext} instance.\n *\n * @param targetType The target type, not {@code null}.\n * @param styleId The style identifier, may be {@code null}, acquiring a\n * <i>default</i> style.\n * @return the style instance, or {@code null}.\n */\n public LocalizationContext getLocalizationStyle(Class<?> targetType, String styleId);\n\n /**\n * Method to check, if a style is available for the type this factory is\n * producing {@link ItemFormat}s.\n *\n * @param styleId the target style identifier.\n * @return {@code true}, if the style is available for the current target\n * type.\n * @see #getTargetClass()\n */\n public boolean isSupportedStyle(String styleId);\n\n /**\n * Creates a new instance of {@link ItemFormat} configured by the given\n * {@link org.javamoney.format.LocalizationContext} instance, if the style (style identifier, one\n * of the style's attributes) required are not supported by this factory,\n * {@code null} should be returned (different to the API, where an\n * {@link ItemFormatException} must be thrown.\n *\n * @param style the {@link org.javamoney.format.LocalizationContext} that configures this\n * {@link ItemFormat}, which also contains the {@link ItemFormat}\n * 's configuration attributes.\n * @return a {@link ItemFormat} instance configured with the given style, or\n * {@code null}.\n * @see #getTargetClass()\n */\n public ItemFormat<T> getItemFormat(LocalizationContext style) throws ItemFormatException;\n\n}", "public interface TokenizeableFormatsSingletonSpi{\n\n\t/**\n\t * Return the style id's supported by this {@link ItemFormatFactorySpi}\n\t * instance.\n\t * \n\t * @see org.javamoney.format.LocalizationContext#getId()\n\t * @param targetType\n\t * the target type, never {@code null}.\n\t * @return the supported style ids, never {@code null}.\n\t */\n\tpublic Collection<String> getSupportedStyleIds(Class<?> targetType);\n\n\t/**\n\t * Return a style given iots type and id.\n\t * \n\t * @param targetType\n\t * the target type, never {@code null}.\n\t * @param styleId\n\t * the required style id.\n\t * @return the supported style ids, never {@code null}.\n\t */\n\tpublic LocalizationContext getLocalizationStyle(Class<?> targetType,\n\t\t\tString styleId);\n\n\t/**\n\t * Method allows to check if a named style is supported.\n\t * \n\t * @param targetType\n\t * the target type, never {@code null}.\n\t * @param styleId\n\t * The style id.\n\t * @return true, if a spi implementation is able to provide an\n\t * {@link ItemFormat} for the given style.\n\t */\n\tpublic boolean isSupportedStyle(Class<?> targetType, String styleId);\n\n\t/**\n\t * This method returns an instance of an {@link ItemFormat} .\n\t * \n\t * @param targetType\n\t * the target type, never {@code null}.\n\t * @param style\n\t * the {@link org.javamoney.format.LocalizationContext} to be attached to this\n\t * {@link ItemFormat}, which also contains the target\n\t * {@link Locale} instances to be used, as well as other\n\t * attributes configuring this instance.\n\t * @return the formatter required, if available.\n\t * @throws ItemFormatException\n\t * if the {@link org.javamoney.format.LocalizationContext} passed can not be used for\n\t * configuring the {@link ItemFormat} and no matching\n\t * {@link ItemFormat} could be provided by any of the registered\n\t * {@link ItemFormatFactorySpi} instances.\n\t */\n\tpublic <T> ItemFormat<T> getItemFormat(Class<T> targetType,\n\t\t\tLocalizationContext style) throws ItemFormatException;\n}" ]
import org.javamoney.format.ItemFormat; import org.javamoney.format.ItemFormatException; import org.javamoney.format.LocalizationContext; import org.javamoney.format.spi.ItemFormatFactorySpi; import org.javamoney.format.spi.TokenizeableFormatsSingletonSpi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Singleton; import javax.money.spi.Bootstrap; import java.util.*; import java.util.concurrent.ConcurrentHashMap;
/* * Copyright (c) 2012, 2013, Credit Suisse (Anatole Tresch), Werner Keil. * * 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.javamoney.format.internal; /** * This is the base class for implementing the * {@link org.javamoney.format.spi.TokenizeableFormatsSingletonSpi}. * * @author Anatole Tresch */ @Singleton public class DefaultTokenizeableFormatsSingletonSpi implements TokenizeableFormatsSingletonSpi{ @SuppressWarnings("rawtypes")
private Map<Class,Set<ItemFormatFactorySpi>> formatMap = new ConcurrentHashMap<Class,Set<ItemFormatFactorySpi>>();
3
agorava/agorava-twitter
agorava-twitter-cdi/src/main/java/org/agorava/twitter/impl/TwitterGeoServiceImpl.java
[ "public abstract class TwitterBaseService extends ProviderApiService {\n\n protected static final char MULTI_VALUE_SEPARATOR = ',';\n\n public static final String API_ROOT = \"https://api.twitter.com/1.1/\";\n\n public Map<String, String> buildPagingParametersWithCount(int page, int pageSize, long sinceId, long maxId) {\n Map<String, String> parameters = new HashMap<String, String>();\n parameters.put(\"page\", String.valueOf(page));\n parameters.put(\"count\", String.valueOf(pageSize));\n if (sinceId > 0) {\n parameters.put(\"since_id\", String.valueOf(sinceId));\n }\n if (maxId > 0) {\n parameters.put(\"max_id\", String.valueOf(maxId));\n }\n return parameters;\n }\n\n public Map<String, String> buildPagingParametersWithPerPage(int page, int pageSize, long sinceId, long maxId) {\n Map<String, String> parameters = new HashMap<String, String>();\n parameters.put(\"page\", String.valueOf(page));\n parameters.put(\"per_page\", String.valueOf(pageSize));\n if (sinceId > 0) {\n parameters.put(\"since_id\", String.valueOf(sinceId));\n }\n if (maxId > 0) {\n parameters.put(\"max_id\", String.valueOf(maxId));\n }\n return parameters;\n }\n\n @Inject\n @Twitter\n private OAuthService service;\n\n @Override\n public String buildAbsoluteUri(String uri) {\n return API_ROOT + uri;\n }\n\n @Override\n public OAuthService getService() {\n return service;\n }\n}", "public interface TwitterGeoService {\n\n /**\n * Retrieves information about a place\n *\n * @param id the place ID\n * @return a {@link Place}\n * @throws ApiException if there is an error while communicating with Twitter.\n */\n Place getPlace(String id);\n\n /**\n * Retrieves up to 20 places matching the given location.\n *\n * @param latitude the latitude\n * @param longitude the longitude\n * @return a list of {@link Place}s that the point is within\n * @throws ApiException if there is an error while communicating with Twitter.\n */\n List<Place> reverseGeoCode(double latitude, double longitude);\n\n /**\n * Retrieves up to 20 places matching the given location and criteria\n *\n * @param latitude the latitude\n * @param longitude the longitude\n * @param granularity the minimal granularity of the places to return. If null, the default granularity (neighborhood) is\n * assumed.\n * @param accuracy a radius of accuracy around the given point. If given a number,\n * the value is assumed to be in meters. The\n * number may be qualified with \"ft\" to indicate feet. If null, the default accuracy (0m) is assumed.\n * @return a list of {@link Place}s that the point is within\n * @throws ApiException if there is an error while communicating with Twitter.\n */\n List<Place> reverseGeoCode(double latitude, double longitude, PlaceType granularity, String accuracy);\n\n /**\n * Searches for up to 20 places matching the given location.\n *\n * @param latitude the latitude\n * @param longitude the longitude\n * @return a list of {@link Place}s that the point is within\n * @throws ApiException if there is an error while communicating with Twitter.\n */\n List<Place> search(double latitude, double longitude);\n\n /**\n * Searches for up to 20 places matching the given location and criteria\n *\n * @param latitude the latitude\n * @param longitude the longitude\n * @param granularity the minimal granularity of the places to return. If null, the default granularity (neighborhood) is\n * assumed.\n * @param accuracy a radius of accuracy around the given point. If given a number,\n * the value is assumed to be in meters. The\n * number may be qualified with \"ft\" to indicate feet. If null, the default accuracy (0m) is assumed.\n * @param query a free form text value to help find places by name. If null, no query will be applied to the search.\n * @return a list of {@link Place}s that the point is within\n * @throws ApiException if there is an error while communicating with Twitter.\n */\n List<Place> search(double latitude, double longitude, PlaceType granularity, String accuracy, String query);\n\n /**\n * Finds places similar to a place described in the parameters. Returns a list of places along with a token that is required\n * for creating a new place. This method must be called before calling createPlace().\n *\n * @param latitude the latitude\n * @param longitude the longitude\n * @param name the name that the place is known as\n * @return a {@link SimilarPlaces} collection, including a token that can be used to create a new place.\n * @throws ApiException if there is an error while communicating with Twitter.\n */\n SimilarPlaces findSimilarPlaces(double latitude, double longitude, String name);\n\n /**\n * Finds places similar to a place described in the parameters. Returns a list of places along with a token that is required\n * for creating a new place. This method must be called before calling createPlace().\n *\n * @param latitude the latitude\n * @param longitude the longitude\n * @param name the name that the place is known as\n * @param streetAddress the place's street address. May be null.\n * @param containedWithin the ID of the place that the place is contained within\n * @return a {@link SimilarPlaces} collection, including a token that can be used to create a new place.\n * @throws ApiException if there is an error while communicating with Twitter.\n */\n SimilarPlaces findSimilarPlaces(double latitude, double longitude, String name, String streetAddress,\n String containedWithin);\n\n /**\n * Creates a new place.\n *\n * @param placePrototype the place prototype returned in a {@link SimilarPlaces} from a call to findSimilarPlaces()\n * @return a {@link Place} object with the newly created place data\n * @throws ApiException if there is an error while communicating with Twitter.\n */\n Place createPlace(PlacePrototype placePrototype);\n}", "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class PlacesList {\n\n private final List<Place> list;\n\n @JsonCreator\n public PlacesList(@JsonProperty(\"result\") @JsonDeserialize(using = PlacesDeserializer.class) List<Place> list) {\n this.list = list;\n }\n\n public List<Place> getList() {\n return list;\n }\n\n private static class PlacesDeserializer extends JsonDeserializer<List<Place>> {\n @SuppressWarnings(\"unchecked\")\n @Override\n public List<Place> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {\n ObjectMapper mapper = BeanResolver.getInstance().resolve(ObjectMapper.class);\n jp.setCodec(mapper);\n JsonNode treeNode = (JsonNode) jp.readValueAs(JsonNode.class).get(\"places\");\n return (List<Place>) mapper.reader(new TypeReference<List<Place>>() {\n }).readValue(treeNode);\n }\n }\n}", "public class Place {\n\n private final String id;\n\n private final String name;\n\n private final String fullName;\n\n private final String streetAddress;\n\n private final String country;\n\n private final String countryCode;\n\n private final PlaceType placeType;\n\n public Place(String id, String name, String fullName, String streetAddress, String country, String countryCode,\n PlaceType placeType) {\n this.id = id;\n this.name = name;\n this.fullName = fullName;\n this.country = country;\n this.streetAddress = streetAddress;\n this.countryCode = countryCode;\n this.placeType = placeType;\n }\n\n public String getId() {\n return id;\n }\n\n public String getName() {\n return name;\n }\n\n public String getFullName() {\n return fullName;\n }\n\n public String getStreetAddress() {\n return streetAddress;\n }\n\n public String getCountry() {\n return country;\n }\n\n public String getCountryCode() {\n return countryCode;\n }\n\n public PlaceType getPlaceType() {\n return placeType;\n }\n\n}", "public class PlacePrototype {\n\n private final double latitude;\n\n private final double longitude;\n\n private final String name;\n\n private final String containedWithin;\n\n private final String createToken;\n\n private final String streetAddress;\n\n public PlacePrototype(String createToken, double latitude, double longitude, String name, String streetAddress,\n String containedWithin) {\n this.createToken = createToken;\n this.latitude = latitude;\n this.longitude = longitude;\n this.name = name;\n this.streetAddress = streetAddress;\n this.containedWithin = containedWithin;\n }\n\n public double getLatitude() {\n return latitude;\n }\n\n public double getLongitude() {\n return longitude;\n }\n\n public String getName() {\n return name;\n }\n\n public String getStreetAddress() {\n return streetAddress;\n }\n\n public String getContainedWithin() {\n return containedWithin;\n }\n\n public String getCreateToken() {\n return createToken;\n }\n}", "public enum PlaceType {\n\n POINT_OF_INTEREST, NEIGHBORHOOD, CITY, ADMIN, COUNTRY\n\n}", "@SuppressWarnings(\"serial\")\npublic class SimilarPlaces extends ArrayList<Place> {\n\n private final PlacePrototype placePrototype;\n\n public SimilarPlaces(List<Place> places, PlacePrototype placePrototype) {\n super(places);\n this.placePrototype = placePrototype;\n }\n\n /**\n * A prototype place that matches the criteria for the call to\n * {@link TwitterGeoService#findSimilarPlaces(double, double, String)}, including a create token that can be used to create\n * the place.\n */\n public PlacePrototype getPlacePrototype() {\n return placePrototype;\n }\n\n}", "public class SimilarPlacesResponse {\n\n private final String token;\n\n private final List<Place> places;\n\n public SimilarPlacesResponse(List<Place> places, String token) {\n this.places = places;\n this.token = token;\n }\n\n /**\n * The list of places found in a similar places search.\n *\n * @return\n */\n public List<Place> getPlaces() {\n return places;\n }\n\n /**\n * A token that may be used to create a new place.\n */\n public String getToken() {\n return token;\n }\n}" ]
import java.util.HashMap; import java.util.List; import java.util.Map; import org.agorava.TwitterBaseService; import org.agorava.twitter.Twitter; import org.agorava.twitter.TwitterGeoService; import org.agorava.twitter.jackson.PlacesList; import org.agorava.twitter.model.Place; import org.agorava.twitter.model.PlacePrototype; import org.agorava.twitter.model.PlaceType; import org.agorava.twitter.model.SimilarPlaces; import org.agorava.twitter.model.SimilarPlacesResponse; import javax.inject.Named;
/* * Copyright 2013 Agorava * * 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.agorava.twitter.impl; /** * @author Antoine Sabot-Durand * @author Craig Walls */ @Twitter @Named public class TwitterGeoServiceImpl extends TwitterBaseService implements TwitterGeoService { @Override public Place getPlace(String placeId) { return getService().get(buildAbsoluteUri("geo/id/" + placeId + ".json"), Place.class); } @Override public List<Place> reverseGeoCode(double latitude, double longitude) { return reverseGeoCode(latitude, longitude, null, null); } @Override public List<Place> reverseGeoCode(double latitude, double longitude, PlaceType granularity, String accuracy) { Map<String, String> parameters = buildGeoParameters(latitude, longitude, granularity, accuracy, null); return getService().get(buildUri("geo/reverse_geocode.json", parameters), PlacesList.class).getList(); } @Override public List<Place> search(double latitude, double longitude) { return search(latitude, longitude, null, null, null); } @Override public List<Place> search(double latitude, double longitude, PlaceType granularity, String accuracy, String query) { Map<String, String> parameters = buildGeoParameters(latitude, longitude, granularity, accuracy, query); return getService().get(buildUri("geo/search.json", parameters), PlacesList.class).getList(); } @Override public SimilarPlaces findSimilarPlaces(double latitude, double longitude, String name) { return findSimilarPlaces(latitude, longitude, name, null, null); } @Override public SimilarPlaces findSimilarPlaces(double latitude, double longitude, String name, String streetAddress, String containedWithin) { Map<String, String> parameters = buildPlaceParameters(latitude, longitude, name, streetAddress, containedWithin); SimilarPlacesResponse response = getService().get(buildUri("geo/similar_places.json", parameters), SimilarPlacesResponse.class);
PlacePrototype placePrototype = new PlacePrototype(response.getToken(), latitude, longitude, name, streetAddress,
4
SecUSo/privacy-friendly-memo-game
app/src/main/java/org/secuso/privacyfriendlymemory/ui/navigation/StatisticsActivity.java
[ "public final class Constants {\n\n private Constants(){} // this class should not be initialized\n\n // Preferences Constants\n public final static String FIRST_APP_START = \"FIRST_APP_START\";\n public final static String SELECTED_CARD_DESIGN = \"SELECTED_CARD_DESIGN\";\n public final static String CUSTOM_CARDS_URIS = \"CUSTOM_CARDS_URIS\";\n\n // Preferences Constants Highscore\n public final static String HIGHSCORE_EASY = \"HIGHSCORE_EASY\";\n public final static String HIGHSCORE_EASY_TRIES = \"HIGHSCORE_EASY_TRIES\";\n public final static String HIGHSCORE_EASY_TIME = \"HIGHSCORE_EASY_TIME\";\n\n public final static String HIGHSCORE_MODERATE = \"HIGHSCORE_MODERATE\";\n public final static String HIGHSCORE_MODERATE_TRIES = \"HIGHSCORE_MODERATE_TRIES\";\n public final static String HIGHSCORE_MODERATE_TIME = \"HIGHSCORE_MODERATE_TIME\";\n\n public final static String HIGHSCORE_HARD = \"HIGHSCORE_HARD\";\n public final static String HIGHSCORE_HARD_TRIES = \"HIGHSCORE_HARD_TRIES\";\n public final static String HIGHSCORE_HARD_TIME = \"HIGHSCORE_HARD_TIME\";\n\n\n // Preferences Constants Statistics\n public final static String STATISTICS_DECK_ONE = \"STATISTICS_DECK_ONE\";\n public final static String STATISTICS_DECK_TWO = \"STATISTICS_DECK_TWO\";\n\n // Intent Extra Constants\n public final static String GAME_DIFFICULTY = \"GAME_DIFFICULTY\";\n public final static String GAME_MODE = \"GAME_MODE\";\n public final static String CARD_DESIGN = \"CARD_DESIGN\";\n\n\n}", "public class MemoGameStatistics {\n\n private Map<String, Integer> nameCountMapping = new HashMap<>();\n\n public MemoGameStatistics(Set<String> statisticsSet){\n createNameCountMapping(statisticsSet);\n }\n\n public void incrementCount(List<String> resourceNames){\n for(String resourceName : resourceNames){\n Integer count = nameCountMapping.get(resourceName);\n count++;\n nameCountMapping.put(resourceName, count);\n }\n }\n\n public Set<String> getStatisticsSet(){\n Set<String> statisticsSet = new HashSet<>();\n for(Map.Entry<String, Integer> statisticsEntry : nameCountMapping.entrySet()){\n String nameWithCounter = statisticsEntry.getKey() + \"_\" + statisticsEntry.getValue();\n statisticsSet.add(nameWithCounter);\n }\n return statisticsSet;\n }\n\n private void createNameCountMapping(Set<String> statisticsSet){\n for(String statisticsEntry : statisticsSet){\n String resourceName = statisticsEntry.substring(0, statisticsEntry.lastIndexOf(\"_\"));\n Integer count = Integer.parseInt(statisticsEntry.substring(statisticsEntry.lastIndexOf(\"_\")+1, statisticsEntry.length()));\n nameCountMapping.put(resourceName, count);\n }\n }\n\n public static Set<String> createInitStatistics(List<String> resourceNames){\n Set<String> initialStatistics = new HashSet<>();\n for(String resourceName : resourceNames){\n String initialStatsEntry = resourceName + \"_\" + 0;\n initialStatistics.add(initialStatsEntry);\n }\n return initialStatistics;\n }\n\n public Integer[] getFalseSelectedCounts(){\n return nameCountMapping.values().toArray(new Integer[nameCountMapping.values().size()]);\n }\n\n public String[] getResourceNames(){\n return nameCountMapping.keySet().toArray(new String[nameCountMapping.keySet().size()]);\n }\n}", "public class ResIdAdapter {\n\n public static List<String> getResourceName(List<Integer> resIds, Context context){\n List<String> resIdResourceNames = new LinkedList<>();\n for(Integer resId : resIds){\n resIdResourceNames.add(context.getResources().getResourceEntryName(resId));\n }\n return resIdResourceNames;\n }\n}", "public enum CardDesign {\n\n FIRST(1, R.string.carddesign_displayname_first),\n SECOND(2, R.string.carddesign_displayname_second),\n CUSTOM(3, R.string.carddesign_displayname_custom);\n\n private final int value;\n private final int displayNameResId;\n\n CardDesign(int value, int displayNameResId){\n this.value = value;\n this.displayNameResId = displayNameResId;\n }\n\n public int getDisplayNameResId(){ return displayNameResId; }\n public int getValue(){\n return value;\n }\n\n public boolean isCustom(){\n if(value == 3) {\n return true;\n }else{\n return false;\n }\n }\n\n public static CardDesign get(int value){\n switch(value){\n case 1:\n return FIRST;\n case 2:\n return SECOND;\n case 3:\n return CUSTOM;\n default:\n return FIRST;\n }\n }\n\n}", "public class MemoGameDefaultImages {\n\n private static final int NOT_FOUND_IMAGE_RES_ID = R.drawable.secuso_not_found;\n\n private static List<Integer> images1 = new LinkedList<>();\n private static List<Integer> images2 = new LinkedList<>();\n\n static{\n // fill first deck with images\n images1.add(R.drawable.set1card1);\n images1.add(R.drawable.set1card2);\n images1.add(R.drawable.set1card3);\n images1.add(R.drawable.set1card4);\n images1.add(R.drawable.set1card5);\n images1.add(R.drawable.set1card6);\n images1.add(R.drawable.set1card7);\n images1.add(R.drawable.set1card8);\n images1.add(R.drawable.set1card9);\n images1.add(R.drawable.set1card10);\n images1.add(R.drawable.set1card11);\n images1.add(R.drawable.set1card12);\n images1.add(R.drawable.set1card13);\n images1.add(R.drawable.set1card14);\n images1.add(R.drawable.set1card15);\n images1.add(R.drawable.set1card16);\n images1.add(R.drawable.set1card17);\n images1.add(R.drawable.set1card18);\n images1.add(R.drawable.set1card19);\n images1.add(R.drawable.set1card20);\n images1.add(R.drawable.set1card21);\n images1.add(R.drawable.set1card22);\n images1.add(R.drawable.set1card23);\n images1.add(R.drawable.set1card24);\n images1.add(R.drawable.set1card25);\n images1.add(R.drawable.set1card26);\n images1.add(R.drawable.set1card27);\n images1.add(R.drawable.set1card28);\n images1.add(R.drawable.set1card29);\n images1.add(R.drawable.set1card30);\n images1.add(R.drawable.set1card31);\n images1.add(R.drawable.set1card32);\n }\n \n static{\n // fill second deck with images\n images2.add(R.drawable.set2card1);\n images2.add(R.drawable.set2card2);\n images2.add(R.drawable.set2card3);\n images2.add(R.drawable.set2card4);\n images2.add(R.drawable.set2card5);\n images2.add(R.drawable.set2card6);\n images2.add(R.drawable.set2card7);\n images2.add(R.drawable.set2card8);\n images2.add(R.drawable.set2card9);\n images2.add(R.drawable.set2card10);\n images2.add(R.drawable.set2card11);\n images2.add(R.drawable.set2card12);\n images2.add(R.drawable.set2card13);\n images2.add(R.drawable.set2card14);\n images2.add(R.drawable.set2card15);\n images2.add(R.drawable.set2card16);\n images2.add(R.drawable.set2card17);\n images2.add(R.drawable.set2card18);\n images2.add(R.drawable.set2card19);\n images2.add(R.drawable.set2card20);\n images2.add(R.drawable.set2card21);\n images2.add(R.drawable.set2card22);\n images2.add(R.drawable.set2card23);\n images2.add(R.drawable.set2card24);\n images2.add(R.drawable.set2card25);\n images2.add(R.drawable.set2card26);\n images2.add(R.drawable.set2card27);\n images2.add(R.drawable.set2card28);\n images2.add(R.drawable.set2card29);\n images2.add(R.drawable.set2card30);\n images2.add(R.drawable.set2card31);\n images2.add(R.drawable.set2card32);\n }\n\n public static int getNotFoundImageResID(){\n return NOT_FOUND_IMAGE_RES_ID;\n }\n\n public static List<Integer> getResIDs(CardDesign cardDesign, MemoGameDifficulty memoryDifficulty, boolean shuffled){\n List<Integer> imagesForCardDesign = new LinkedList<>();\n switch(cardDesign){\n case FIRST:\n imagesForCardDesign = images1;\n break;\n case SECOND:\n imagesForCardDesign = images2;\n break;\n }\n\n if(shuffled){\n Collections.shuffle(imagesForCardDesign);\n }\n return reduce(memoryDifficulty, imagesForCardDesign);\n }\n\n private static List<Integer> reduce(MemoGameDifficulty memoryDifficulty, List<Integer> images){\n // get images based on the deck size defined in the game difficulty\n int differentImages = memoryDifficulty.getDeckSize()/2;\n if(differentImages > images.size()) {\n throw new IllegalStateException(\"Requested deck contains not enough images for the specific game difficulty\");\n }\n return images.subList(0, differentImages);\n }\n\n}", "public enum MemoGameDifficulty {\n\n\n Easy(R.string.difficulty_easy, 16),\n Moderate(R.string.difficulty_moderate, 36),\n Hard(R.string.difficulty_hard, 64);\n\n private final int resID;\n private final int deckSize;\n\n private static List<MemoGameDifficulty> validDifficulties = new LinkedList<>();\n\n static{\n validDifficulties.add(Easy);\n validDifficulties.add(Moderate);\n validDifficulties.add(Hard);\n }\n\n\n MemoGameDifficulty(@StringRes int resID, int deckSize) {\n this.resID = resID;\n this.deckSize = deckSize;\n }\n\n public int getStringResID() {\n return resID;\n }\n\n public int getDeckSize() {\n return deckSize;\n }\n\n public static List<MemoGameDifficulty> getValidDifficulties(){\n return validDifficulties;\n }\n\n}" ]
import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import org.secuso.privacyfriendlymemory.Constants; import org.secuso.privacyfriendlymemory.common.MemoGameStatistics; import org.secuso.privacyfriendlymemory.common.ResIdAdapter; import org.secuso.privacyfriendlymemory.model.CardDesign; import org.secuso.privacyfriendlymemory.model.MemoGameDefaultImages; import org.secuso.privacyfriendlymemory.model.MemoGameDifficulty; import org.secuso.privacyfriendlymemory.ui.R; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set;
package org.secuso.privacyfriendlymemory.ui.navigation; public class StatisticsActivity extends AppCompatActivity { private static StatisticsActivity statisticsActivity; private SectionsPagerAdapter mSectionsPagerAdapter; private ViewPager mViewPager; private SharedPreferences preferences = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_statistcs_content); preferences = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()); setupActionBar(); this.statisticsActivity = this; // setup up fragments in sectionspager mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); // setup tab layout TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); } @Override protected void onDestroy() { super.onDestroy(); statisticsActivity = null; } private void setupActionBar() { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(R.string.menu_statistics); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#024265"))); actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_statistics, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: finish(); return true; case R.id.menu_statistics_reset: List<Integer> resIdsDeckOne = MemoGameDefaultImages.getResIDs(CardDesign.FIRST, MemoGameDifficulty.Hard, false); List<Integer> resIdsDeckTwo = MemoGameDefaultImages.getResIDs(CardDesign.SECOND, MemoGameDifficulty.Hard, false);
List<String> resourceNamesDeckOne = ResIdAdapter.getResourceName(resIdsDeckOne, this);
2
ApplETS/applets-java-api
src/test/java/applets/etsmtl/ca/news/EventsResourcesTest.java
[ "@Path(\"events\")\npublic class EventsResources {\n\n private final EventDAO eventDAO;\n private final SourceDAO sourceDAO;\n\n @Inject\n public EventsResources(EventDAO eventDAO, SourceDAO sourceDAO) {\n this.eventDAO = eventDAO;\n this.sourceDAO = sourceDAO;\n }\n\n @GET\n @Path(\"list/{id}\")\n @Produces({MediaType.APPLICATION_JSON})\n public List<Event> getEvents(@PathParam(\"id\") String id) {\n List<Event> events = new ArrayList<Event>();\n\n Source source = sourceDAO.find(id);\n\n events.addAll(eventDAO.findFollowingEvents(id));\n\n return events;\n }\n\n @GET\n @Path(\"sources\")\n @Produces({MediaType.APPLICATION_JSON})\n public List<Source> getSources() {\n\n List<Source> sources = sourceDAO.findByType(\"facebook\");\n return sources;\n }\n}", "public class EventDAO extends DAO<Event> {\n\n @Override\n public Event find(String id) {\n try {\n String findById=\"SELECT * FROM evenements WHERE id = ?\";\n PreparedStatement st = this.connection.prepareStatement(findById,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);\n st.setString(1, id);\n ResultSet result = st.executeQuery();\n // TODO add DATE param to query\n if(result.first()) {\n Event event = getDataFromResult(result);\n result.close();\n st.close();\n return event;\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n @Override\n public boolean isExisting(String id) {\n try {\n String findById=\"SELECT id FROM evenements WHERE id = ?\";\n PreparedStatement st = this.connection.prepareStatement(findById,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);\n st.setString(1, id);\n ResultSet result = st.executeQuery();\n if(result.first()) {\n result.close();\n st.close();\n return true;\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n return false;\n }\n\n @Override\n public List<Event> findAll() {\n // TODO review limit\n // TODO check if date must be checked on find() to filter passed events\n List<Event> events = new ArrayList<Event>();\n try {\n String findAll = \"SELECT * FROM evenements ORDER BY debut DESC LIMIT \"+ FIND_ALL_EVENEMENTS_MAX_SIZE;\n ResultSet result = this.connection\n .createStatement(\n ResultSet.TYPE_SCROLL_INSENSITIVE,\n ResultSet.CONCUR_READ_ONLY\n ).executeQuery(\n findAll\n );\n while(result.next()) {\n events.add(getDataFromResult(result));\n }\n result.close();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n Collections.sort(events);\n return events;\n }\n\n /**\n * Cherche les événements pour une source donnée.\n * @param sourceID le ID de la source.\n * @return La liste des événements pour cette source\n */\n public List<Event> findAllForSource(String sourceID) {\n // TODO review limit\n // TODO check if date must be checked on find() to filter passed events\n List<Event> events = new ArrayList<Event>();\n try {\n String findAllforSource = \"SELECT * FROM evenements WHERE id_source = ? ORDER BY debut DESC LIMIT \" + FIND_ALL_EVENEMENTS_MAX_SIZE;\n PreparedStatement st = this.connection.prepareStatement(findAllforSource,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);\n st.setString(1, sourceID);\n ResultSet result = st.executeQuery();\n while(result.next()) {\n events.add(getDataFromResult(result));\n }\n result.close();\n st.close();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n Collections.sort(events);\n return events;\n }\n\n /**\n * Cherche les prochains événements pour une source donnée.\n * @param sourceID le ID de la source.\n * @return La liste des événements pour cette source\n */\n public List<Event> findFollowingEvents(String sourceID) {\n // TODO review limit\n // TODO check if date must be checked on find() to filter passed events\n List<Event> events = new ArrayList<Event>();\n try {\n String findAllforSource = \"SELECT * FROM evenements WHERE id_source = ? AND fin >= ? ORDER BY debut\";\n PreparedStatement st = this.connection.prepareStatement(findAllforSource,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);\n st.setString(1, sourceID);\n st.setDate(2, new Date(new java.util.Date().getTime())); // Now\n ResultSet result = st.executeQuery();\n while(result.next()) {\n events.add(getDataFromResult(result));\n }\n result.close();\n st.close();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n Collections.sort(events);\n return events;\n }\n\n public void add(Event event) {\n try {\n\n String req_insert_event = \"INSERT INTO evenements (id, nom, debut, fin, nom_lieu, ville, etat, pays, adresse, code_postal, longitude, latitude, description, image, id_source) \" +\n \"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\";\n PreparedStatement preparedStatement = ConnectionSingleton.getInstance().prepareStatement(req_insert_event);\n\n preparedStatement.setString(1, event.getId());\n preparedStatement.setString(2, event.getNom());\n\n if(event.getDebut() != null)\n preparedStatement.setTimestamp(3, new java.sql.Timestamp(event.getDebut().getTime()));\n else\n preparedStatement.setTimestamp(3, null);\n\n if(event.getFin() != null)\n preparedStatement.setTimestamp(4, new java.sql.Timestamp(event.getFin().getTime()));\n else\n preparedStatement.setTimestamp(4, null);\n\n preparedStatement.setString(5, event.getNom_lieu());\n preparedStatement.setString(6, event.getVille());\n preparedStatement.setString(7, event.getEtat());\n preparedStatement.setString(8, event.getPays());\n preparedStatement.setString(9, event.getAdresse());\n preparedStatement.setString(10, event.getCode_postal());\n preparedStatement.setFloat(11, event.getLongitude());\n preparedStatement.setFloat(12, event.getLatitude());\n preparedStatement.setString(13, event.getDescription());\n preparedStatement.setString(14, event.getImage());\n preparedStatement.setString(15, event.getId_source());\n\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (NullPointerException e) {\n e.printStackTrace();\n }\n }\n\n public void update(Event event) {\n try {\n\n String req_insert_event = \"\" +\n \"UPDATE evenements \" +\n \"SET nom = ?, debut = ?, fin = ?, nom_lieu = ?, ville = ?, etat = ?, pays = ?, \" +\n \"adresse = ?, code_postal = ?, longitude = ?, latitude = ?, description = ?, \" +\n \"image = ?, id_source = ? \" +\n \"WHERE id = ?\";\n PreparedStatement preparedStatement = ConnectionSingleton.getInstance().prepareStatement(req_insert_event);\n\n preparedStatement.setString(15, event.getId());\n preparedStatement.setString(1, event.getNom());\n\n if(event.getDebut() != null)\n preparedStatement.setTimestamp(2, new java.sql.Timestamp(event.getDebut().getTime()));\n else\n preparedStatement.setTimestamp(2, null);\n\n if(event.getFin() != null)\n preparedStatement.setTimestamp(3, new java.sql.Timestamp(event.getFin().getTime()));\n else\n preparedStatement.setTimestamp(3, null);\n\n preparedStatement.setString(4, event.getNom_lieu());\n preparedStatement.setString(5, event.getVille());\n preparedStatement.setString(6, event.getEtat());\n preparedStatement.setString(7, event.getPays());\n preparedStatement.setString(8, event.getAdresse());\n preparedStatement.setString(9, event.getCode_postal());\n preparedStatement.setFloat(10, event.getLongitude());\n preparedStatement.setFloat(11, event.getLatitude());\n preparedStatement.setString(12, event.getDescription());\n preparedStatement.setString(13, event.getImage());\n preparedStatement.setString(14, event.getId_source());\n\n preparedStatement.executeUpdate();\n } catch (SQLException | NullPointerException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n protected Event getDataFromResult(ResultSet result) throws SQLException {\n Event event = new Event();\n event.setId(result.getString(\"id\"));\n event.setNom(result.getString(\"nom\"));\n event.setDebut(result.getDate(\"debut\"));\n event.setFin(result.getDate(\"fin\"));\n event.setNom_lieu(result.getString(\"nom_lieu\"));\n event.setVille(result.getString(\"ville\"));\n event.setEtat(result.getString(\"etat\"));\n event.setPays(result.getString(\"pays\"));\n event.setAdresse(result.getString(\"adresse\"));\n event.setCode_postal(result.getString(\"code_postal\"));\n event.setLongitude(result.getFloat(\"longitude\"));\n event.setLatitude(result.getFloat(\"latitude\"));\n event.setDescription(result.getString(\"description\"));\n event.setImage(result.getString(\"image\"));\n event.setId_source(result.getString(\"id_source\"));\n return event;\n }\n\n}", "public class SourceDAO extends DAO<Source> {\n\n @Override\n public Source find(String key) {\n Source source = new Source();\n try {\n String findByKey = \"SELECT * FROM sources WHERE key = ?\";\n PreparedStatement st = this.connection.prepareStatement(findByKey,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);\n st.setString( 1, key );\n ResultSet result = st.executeQuery();\n if(result.first()) {\n source = getDataFromResult(result);\n }\n result.close();\n st.close();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return source;\n }\n\n @Override\n public boolean isExisting(String key) {\n try {\n String findByKey = \"SELECT key FROM sources WHERE key = ?\";\n PreparedStatement st = this.connection.prepareStatement(findByKey,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);\n st.setString(1, key);\n ResultSet result = st.executeQuery();\n if(result.first())\n return true;\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n return false;\n }\n\n @Override\n public List<Source> findAll() {\n List<Source> sources = new ArrayList<Source>();\n try {\n String findAll = \"SELECT * FROM sources\";\n ResultSet result = this.connection\n .createStatement(\n ResultSet.TYPE_SCROLL_INSENSITIVE,\n ResultSet.CONCUR_READ_ONLY\n ).executeQuery(\n findAll\n );\n while(result.next()) {\n sources.add(getDataFromResult(result));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n return sources;\n }\n\n public void add(Source source) {\n try {\n\n String req_insert_source = \"INSERT INTO sources (key, name, type, url_image, value) VALUES (?,?,?::type_source,?,?)\";\n PreparedStatement preparedStatement = ConnectionSingleton.getInstance().prepareStatement(req_insert_source);\n\n preparedStatement.setString(1, source.getKey());\n preparedStatement.setString(2, source.getName());\n preparedStatement.setString(3, source.getType());\n preparedStatement.setString(4, source.getUrlImage());\n preparedStatement.setString(5, source.getValue());\n\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n\n public void update(Source source) {\n try {\n\n String req_insert_source = \"\" +\n \"UPDATE sources \" +\n \"SET name = ?, type = ?::type_source, url_image = ?, value = ? \" +\n \"WHERE key = ?\";\n PreparedStatement preparedStatement = ConnectionSingleton.getInstance().prepareStatement(req_insert_source);\n\n preparedStatement.setString(5, source.getKey());\n preparedStatement.setString(1, source.getName());\n preparedStatement.setString(2, source.getType());\n preparedStatement.setString(3, source.getUrlImage());\n preparedStatement.setString(4, source.getValue());\n\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n\n public List<Source> findByType(String type){\n List<Source> sources = new ArrayList<Source>();\n try {\n String findByType = \"SELECT * FROM sources WHERE type = ?::type_source\";\n PreparedStatement st = this.connection.prepareStatement(findByType,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);\n st.setString(1, type);\n ResultSet result = st.executeQuery();\n while(result.next()) {\n sources.add(getDataFromResult(result));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n return sources;\n }\n\n\n @Override\n protected Source getDataFromResult(ResultSet result) throws SQLException {\n Source source = new Source();\n source.setUrlImage(result.getString(\"url_image\"));\n source.setType(result.getString(\"type\"));\n source.setName(result.getString(\"name\"));\n source.setKey(result.getString(\"key\"));\n source.setValue(result.getString(\"value\"));\n return source;\n }\n\n\n\n}", "@XmlRootElement\npublic class Event implements Comparable{\n private String id;\n private String nom;\n private Date debut; // TODO test for better class\n private Date fin; // TODO test for better class\n private String nom_lieu;\n private String ville;\n private String etat;\n private String pays;\n private String adresse;\n private String code_postal;\n private float longitude;\n private float latitude;\n private String description;\n private String image;\n private String id_source;\n\n public Event() {\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 getNom() {\n return nom;\n }\n\n public void setNom(String nom) {\n this.nom = nom;\n }\n\n public Date getDebut() {\n return debut;\n }\n\n public void setDebut(Date debut) {\n this.debut = debut;\n }\n\n public Date getFin() {\n return fin;\n }\n\n public void setFin(Date fin) {\n this.fin = fin;\n }\n\n public String getNom_lieu() {\n return nom_lieu;\n }\n\n public void setNom_lieu(String nom_lieu) {\n this.nom_lieu = nom_lieu;\n }\n\n public String getVille() {\n return ville;\n }\n\n public void setVille(String ville) {\n this.ville = ville;\n }\n\n public String getEtat() {\n return etat;\n }\n\n public void setEtat(String etat) {\n this.etat = etat;\n }\n\n public String getPays() {\n return pays;\n }\n\n public void setPays(String pays) {\n this.pays = pays;\n }\n\n public String getAdresse() {\n return adresse;\n }\n\n public void setAdresse(String adresse) {\n this.adresse = adresse;\n }\n\n public String getCode_postal() {\n return code_postal;\n }\n\n public void setCode_postal(String code_postal) {\n this.code_postal = code_postal;\n }\n\n public float getLongitude() {\n return longitude;\n }\n\n public void setLongitude(float longitude) {\n this.longitude = longitude;\n }\n\n public float getLatitude() {\n return latitude;\n }\n\n public void setLatitude(float latitude) {\n this.latitude = latitude;\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 getImage() {\n return image;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n\n public String getId_source() {\n return id_source;\n }\n\n public void setId_source(String id_source) {\n this.id_source = id_source;\n }\n\n @Override\n public int compareTo(Object o) {\n return this.debut.compareTo(((Event)o).getDebut());\n }\n}", "@XmlRootElement\npublic class Source {\n\n private String name;\n private String type;\n private String urlImage;\n private String key;\n\n private String value;\n\n public Source() {\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 getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getUrlImage() {\n return urlImage;\n }\n\n public void setUrlImage(String urlImage) {\n this.urlImage = urlImage;\n }\n\n public String getKey() {\n return key;\n }\n\n public void setKey(String key) {\n this.key = key;\n }\n\n public String getValue() { return value; }\n\n public void setValue(String value) { this.value = value; }\n}" ]
import applets.etsmtl.ca.news.EventsResources; import applets.etsmtl.ca.news.db.EventDAO; import applets.etsmtl.ca.news.db.SourceDAO; import applets.etsmtl.ca.news.model.Event; import applets.etsmtl.ca.news.model.Source; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Assert; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.ws.rs.core.Application; import javax.ws.rs.core.GenericType; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.when;
package news; public class EventsResourcesTest extends JerseyTest { @Mock private EventDAO eventDAO; @Mock private SourceDAO sourceDAO; @Override protected Application configure() { MockitoAnnotations.initMocks(this);
EventsResources resource = new EventsResources(eventDAO, sourceDAO);
0
wwfdoink/jolokia-web
src/main/java/prj/jolokiaweb/controller/ApiController.java
[ "public class JolokiaApp {\n private static final int DEFAULT_PORT = 8080;\n private static final String DEFAULT_CONTEXT_PATH = \"\";\n private static Tomcat tomcat;\n private static String baseUrl;\n private static String contextPath;\n\n /**\n * @param tomcatPort Web server listening port\n * @param contextPath Tomcat context path\n * @param agentInfo Jolokia AgentInfo\n */\n public JolokiaApp(final Integer tomcatPort, final String contextPath, final AgentInfo agentInfo) throws ServletException, URISyntaxException {\n int port = (tomcatPort == null) ? DEFAULT_PORT : tomcatPort;\n tomcat = new Tomcat();\n tomcat.setPort(port);\n tomcat.setBaseDir(new File(System.getProperty(\"java.io.tmpdir\")).getAbsolutePath());\n tomcat.getHost().setAppBase(\".\");\n Service service = tomcat.getService();\n Connector connector;\n if (agentInfo.getSSLConfig().isUseSSL()) {\n connector = getSslConnector(port, agentInfo);\n service.addConnector(connector);\n } else {\n connector = getHttpConnector(port);\n service.addConnector(connector);\n }\n\n Context ctx = tomcat.addWebapp(contextPath, new File(System.getProperty(\"java.io.tmpdir\")).getAbsolutePath());\n ctx.addServletContainerInitializer(new WsSci(), null);\n\n StringBuilder urlBuilder = new StringBuilder();\n urlBuilder.append(connector.getScheme() + \"://\");\n urlBuilder.append(tomcat.getServer().getAddress());\n urlBuilder.append(\":\");\n urlBuilder.append(port);\n\n this.baseUrl = urlBuilder.toString();\n this.contextPath = contextPath;\n if (agentInfo.getUrl() == null) {\n agentInfo.setLocalAgent(true);\n agentInfo.setUrl(getContextUrl() + \"/jolokia/\");\n } else {\n agentInfo.setLocalAgent(false);\n }\n JolokiaClient.init(agentInfo);\n }\n\n private static Connector getHttpConnector(int port) throws URISyntaxException {\n Connector connector = new Connector();\n connector.setPort(port);\n connector.setSecure(true);\n connector.setScheme(\"http\");\n connector.setURIEncoding(\"UTF-8\");\n return connector;\n }\n\n private static Connector getSslConnector(int port, AgentInfo agentInfo) throws URISyntaxException {\n SSLConfig sslConfig = agentInfo.getSSLConfig();\n Connector connector = new Connector();\n connector.setPort(port);\n connector.setSecure(true);\n connector.setScheme(\"https\");\n connector.setURIEncoding(\"UTF-8\");\n connector.setAttribute(\"clientAuth\", \"false\");\n connector.setAttribute(\"protocol\", \"HTTP/1.1\");\n connector.setAttribute(\"sslProtocol\", \"TLS\");\n connector.setAttribute(\"maxThreads\", \"10\");\n connector.setAttribute(\"protocol\", \"org.apache.coyote.http11.Http11AprProtocol\");\n connector.setAttribute(\"SSLEnabled\", true);\n\n if (sslConfig.isCustomCert()) {\n if (sslConfig.getKeystoreAlias() != null) {\n connector.setAttribute(\"keyAlias\", sslConfig.getKeystoreAlias());\n }\n connector.setAttribute(\"keystorePass\", sslConfig.getKeystorePassword());\n connector.setAttribute(\"keystoreFile\", sslConfig.getKeystorePath());\n } else {\n // using the bundled self-signed cert\n connector.setAttribute(\"keyAlias\", \"tomcat\");\n connector.setAttribute(\"keystorePass\", \"localhost\");\n //connector.setAttribute(\"keystoreType\", \"JKS\");\n connector.setAttribute(\"keystoreFile\",\n JolokiaApp.class.getProtectionDomain()\n .getCodeSource()\n .getLocation()\n .toURI()\n .getPath()\n .replace(\"/classes/\", \"\") + \"/resources/cert/keystore.jks\"\n );\n }\n\n return connector;\n }\n\n public static void main(String[] args) throws Exception {\n Options options = new Options();\n\n options.addOption(Option.builder()\n .argName(\"1-65534\")\n .longOpt(\"port\")\n .optionalArg(true)\n .hasArg()\n .desc(\"Tomcat listening port, default: \" + DEFAULT_PORT)\n .build());\n options.addOption(Option.builder()\n .argName(\"rwxd\")\n .longOpt(\"permissions\")\n .optionalArg(true)\n .hasArg()\n .desc(\"r:read, w:write, x:execute, n:none, default is: rwx\")\n .build());\n options.addOption(Option.builder()\n .argName(\"\")\n .longOpt(\"contextPath\")\n .optionalArg(true)\n .hasArg()\n .desc(\"Context Path, default is the root\")\n .build());\n options.addOption(Option.builder()\n .argName(\"\")\n .longOpt(\"remoteAgentUrl\")\n .optionalArg(true)\n .hasArg()\n .desc(\"Remote jolokia-jvm-agent url\")\n .build());\n options.addOption(Option.builder()\n .argName(\"\")\n .longOpt(\"remoteAgentUsername\")\n .optionalArg(true)\n .hasArg()\n .desc(\"Remote jolokia-jvm-agent username\")\n .build());\n options.addOption(Option.builder()\n .argName(\"\")\n .longOpt(\"remoteAgentPassword\")\n .optionalArg(true)\n .hasArg()\n .desc(\"Remote jolokia-jvm-agent password\")\n .build());\n options.addOption(Option.builder()\n .argName(\"\")\n .longOpt(\"ssl\")\n .optionalArg(true)\n .hasArg(false)\n .desc(\"Use ssl with the bundled self-signed cert\")\n .build());\n options.addOption(Option.builder()\n .argName(\"\")\n .longOpt(\"sslKeyStoreAlias\")\n .optionalArg(true)\n .hasArg()\n .desc(\"keystore alias\")\n .build());\n options.addOption(Option.builder()\n .argName(\"\")\n .longOpt(\"sslKeyStorePath\")\n .optionalArg(true)\n .hasArg()\n .desc(\"keystore path\")\n .build());\n options.addOption(Option.builder()\n .argName(\"\")\n .longOpt(\"sslKeyStorePassword\")\n .optionalArg(true)\n .hasArg()\n .desc(\"keystore password\")\n .build());\n options.addOption(Option.builder()\n .argName(\"\")\n .longOpt(\"allowSelfSignedCert\")\n .optionalArg(true)\n .hasArg(false)\n .desc(\"Allow self signed certs, default: false\")\n .build());\n options.addOption(Option.builder()\n .argName(\"<username> <password>\")\n .longOpt(\"requireAuth\")\n .optionalArg(true)\n .valueSeparator(',')\n .hasArgs()\n .desc(\"Enable Basic auth\")\n .build());\n\n CommandLineParser parser = new DefaultParser();\n\n int port = DEFAULT_PORT;\n String contextPath = DEFAULT_CONTEXT_PATH;\n AgentInfo agentInfo = new AgentInfo();\n\n try {\n CommandLine line = parser.parse(options, args);\n\n if (line.hasOption(\"port\") ) {\n port = Integer.parseInt(line.getOptionValue(\"port\"));\n if (port < 1 || port > 65534) {\n throw new RuntimeException(\"Invalid port number\");\n }\n } else {\n System.out.println(\"Using default port: \" + port);\n }\n\n if (line.hasOption(\"permissions\") ) {\n String permStr = line.getOptionValue(\"permissions\");\n if (permStr.contains(\"r\")) {\n agentInfo.addPermission(AgentInfo.JolokiaPermission.READ);\n }\n if (permStr.contains(\"w\")) {\n agentInfo.addPermission(AgentInfo.JolokiaPermission.WRITE);\n }\n if (permStr.contains(\"x\")) {\n agentInfo.addPermission(AgentInfo.JolokiaPermission.EXECUTE);\n }\n } else {\n //default behavior\n agentInfo.addPermission(\n AgentInfo.JolokiaPermission.READ,\n AgentInfo.JolokiaPermission.WRITE,\n AgentInfo.JolokiaPermission.EXECUTE\n );\n }\n\n if (line.hasOption(\"contextPath\") ) {\n contextPath = line.getOptionValue(\"contextPath\");\n if (!contextPath.startsWith(\"/\")) {\n contextPath = \"/\" + contextPath;\n }\n }\n if (line.hasOption(\"remoteAgentUrl\") ) {\n String url = line.getOptionValue(\"remoteAgentUrl\");\n if (!url.endsWith(\"/\")) {\n url += \"/\";\n }\n URL urlCheck = new URL(url); // check url\n agentInfo.setUrl(url);\n }\n if (line.hasOption(\"remoteAgentUsername\") ) {\n agentInfo.setAgentUsername(line.getOptionValue(\"remoteAgentUsername\"));\n }\n if (line.hasOption(\"remoteAgentPassword\") ) {\n agentInfo.setAgentPassword(line.getOptionValue(\"remoteAgentPassword\"));\n }\n\n /* SSL specific */\n SSLConfig sslConfig = agentInfo.getSSLConfig();\n if (line.hasOption(\"ssl\") ) {\n sslConfig.setUseSSL(true);;\n }\n if (line.hasOption(\"sslKeyStorePath\") ) {\n sslConfig.setUseSSL(true);\n sslConfig.setKeystorePath(line.getOptionValue(\"sslKeyStorePath\"));\n }\n if (line.hasOption(\"sslKeyStorePassword\") ) {\n sslConfig.setKeystorePassword(line.getOptionValue(\"sslKeyStorePassword\"));\n }\n if (line.hasOption(\"sslKeyStoreAlias\") ) {\n sslConfig.setKeystoreAlias(line.getOptionValue(\"sslKeyStoreAlias\"));\n }\n if (line.hasOption(\"allowSelfSignedCert\") ) {\n sslConfig.setAllowSelfSignedCert(true);\n }\n if (line.hasOption(\"requireAuth\") ) {\n String[] values = line.getOptionValues(\"requireAuth\");\n if (values.length != 2) {\n throw new RuntimeException(\"requireAuth requires 2 parameters: <username>,<password>\");\n }\n agentInfo.setWebUsername(values[0]);\n agentInfo.setWebPassword(values[1]);\n agentInfo.setLocalAgent(true);\n }\n\n JolokiaApp app = new JolokiaApp(port, contextPath, agentInfo);\n app.startAndWait();\n } catch(Exception e) {\n System.out.println(\"Invalid input:\" + e.getMessage());\n HelpFormatter formatter = new HelpFormatter();\n formatter.printHelp( \"java -jar jolokiaweb-all.jar\", options);\n }\n }\n\n /**\n * Start tomcat server and return when server has started.\n */\n public void start() throws LifecycleException {\n tomcat.start();\n }\n\n /**\n * Start tomcat server then block\n * @throws LifecycleException\n */\n public void startAndWait() throws LifecycleException {\n start();\n tomcat.getServer().await();\n }\n\n public void stop() throws LifecycleException {\n try {\n tomcat.stop();\n } finally {\n tomcat.destroy();\n }\n }\n\n public static String getBaseUrl() {\n return baseUrl;\n }\n\n public static String getContextPath() {\n return contextPath;\n }\n\n public static String getContextUrl() {\n if (contextPath.length() > 0) {\n if (getBaseUrl().endsWith(\"/\")) {\n return getBaseUrl() + getContextPath();\n } else {\n return getBaseUrl() + \"/\" + getContextPath();\n }\n }\n return baseUrl;\n }\n\n /**\n * Builder class for JolokiaApp\n */\n public static class Builder {\n private Integer port = DEFAULT_PORT;\n private String contextPath = \"\";\n private AgentInfo agentInfo = new AgentInfo();\n\n public Builder() {\n agentInfo.addPermission(AgentInfo.JolokiaPermission.READ);\n agentInfo.addPermission(AgentInfo.JolokiaPermission.WRITE);\n agentInfo.addPermission(AgentInfo.JolokiaPermission.EXECUTE);\n }\n\n /**\n * @param port Web server listening port\n * @return this Builder\n */\n public Builder port(final int port) {\n this.port = port;\n return this;\n }\n /**\n * @param path Web server context path\n * @return this Builder\n */\n public Builder contextPath(final String path) {\n if (!contextPath.startsWith(\"/\")) {\n contextPath = \"/\" + path;\n }\n this.contextPath = path;\n return this;\n }\n\n /**\n * @param url Remote jolokia-agent url\n * @return this Builder\n */\n public Builder agentUrl(final String url) throws MalformedURLException {\n this.agentInfo.setUrl(url.endsWith(\"/\") ? url : url+\"/\");\n return this;\n }\n\n /**\n * @param username Remote jolokia-agent username\n * @param password Remote jolokia-agent password\n * @return this Builder\n */\n public Builder agentAuth(final String username, final String password) {\n this.agentInfo.setAgentUsername(username);\n this.agentInfo.setAgentPassword(password);\n return this;\n }\n\n /**\n * @param permissionArray Permissions for MBean tab READ,WRITE,EXEC\n * @return\n */\n public Builder permissions(AgentInfo.JolokiaPermission... permissionArray) {\n agentInfo.clearPermission();\n agentInfo.addPermission(permissionArray);\n return this;\n }\n\n /**\n * Enable SSL with bundled Self-signed cert\n * @return\n */\n public Builder ssl() {\n agentInfo.getSSLConfig().setUseSSL(true);\n return this;\n }\n\n /**\n * Enable SSL with custom cert\n * @return\n */\n public Builder ssl(String keyStorePath,String keyStorePassword) {\n this.ssl(keyStorePath, keyStorePassword,null);\n return this;\n }\n\n /**\n * Enable SSL with custom cert\n * @return\n */\n public Builder ssl(String keyStorePath, String keyStorePassword, String keyStoreAlias) {\n SSLConfig config = agentInfo.getSSLConfig();\n config.setUseSSL(true);\n config.setKeystorePath(keyStorePath);\n config.setKeystorePassword(keyStorePassword);\n config.setKeystoreAlias(keyStoreAlias);\n return this;\n }\n\n /**\n * Allow self-signed certs\n * @return\n */\n public Builder allowSelfSignedCert() {\n agentInfo.getSSLConfig().setAllowSelfSignedCert(true);\n return this;\n }\n\n /**\n * Require Basic Authentication\n * @return\n */\n public Builder requireAuth(String username, String password) {\n agentInfo.setWebUsername(username);\n agentInfo.setWebPassword(password);\n return this;\n }\n\n /**\n * @return new JolokiaApp instance\n */\n public JolokiaApp build() throws ServletException, URISyntaxException {\n return new JolokiaApp(this.port, contextPath, agentInfo);\n }\n }\n}", "public class ExecForm {\n private String mbean;\n private String operation;\n private List<Object> data = new ArrayList<>();\n\n public String getMbean() {\n return mbean;\n }\n\n public void setMbean(String mbean) {\n this.mbean = mbean;\n }\n\n public String getOperation() {\n return operation;\n }\n\n public void setOperation(String operation) {\n this.operation = operation;\n }\n\n public List<Object> getData() {\n return data;\n }\n\n public void setData(List<Object> data) {\n this.data = data;\n }\n}", "public class ReadForm {\n private String mbean;\n\n public String getMbean() {\n return mbean;\n }\n\n public void setMbean(String mbean) {\n this.mbean = mbean;\n }\n}", "public class WriteForm {\n private String mbean;\n private String attribute;\n private Object value;\n\n public String getMbean() {\n return mbean;\n }\n\n public void setMbean(String mbean) {\n this.mbean = mbean;\n }\n\n public String getAttribute() {\n return attribute;\n }\n\n public void setAttribute(String attribute) {\n this.attribute = attribute;\n }\n\n public Object getValue() {\n return value;\n }\n\n public void setValue(Object value) {\n this.value = value;\n }\n}", "public class AgentInfo {\n public enum JolokiaPermission {\n NONE,READ,WRITE,EXECUTE\n }\n\n private String url;\n private boolean isLocalAgent = false;\n private boolean requireAuth = false;\n private String agentUsername;\n private String agentPassword;\n\n private String webUsername;\n private String webPassword;\n private SSLConfig SSLConfig = new SSLConfig();\n\n private Set<JolokiaPermission> beanPermissions = new HashSet<>();\n\n public AgentInfo() {\n }\n\n public String getUrl() {\n return (url != null) ? url.toString() : null;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public String getAgentUsername() {\n return agentUsername;\n }\n\n public void setAgentUsername(String agentUsername) {\n this.agentUsername = agentUsername;\n }\n\n public String getAgentPassword() {\n return agentPassword;\n }\n\n public void setAgentPassword(String agentPassword) {\n this.agentPassword = agentPassword;\n }\n\n public String getWebUsername() {\n return webUsername;\n }\n\n public void setWebUsername(String webUsername) {\n this.webUsername = webUsername;\n }\n\n public String getWebPassword() {\n return webPassword;\n }\n\n public void setWebPassword(String webPassword) {\n this.webPassword = webPassword;\n }\n\n public boolean isLocalAgent() {\n return isLocalAgent;\n }\n\n public boolean requiresLocalAuth() {\n return webUsername != null;\n }\n\n public void setLocalAgent(boolean localAgent) {\n isLocalAgent = localAgent;\n }\n\n public boolean isRequireAuth() {\n return requireAuth;\n }\n\n public void setRequireAuth(boolean requireAuth) {\n this.requireAuth = requireAuth;\n }\n\n public void addPermission(JolokiaPermission ... permission) {\n this.beanPermissions.addAll(Arrays.asList(permission));\n }\n\n public void clearPermission() {\n this.beanPermissions.clear();\n }\n\n public Set<JolokiaPermission> getBeanPermissions() {\n return beanPermissions;\n }\n\n public SSLConfig getSSLConfig() {\n return SSLConfig;\n }\n\n public void setSSLConfig(SSLConfig SSLConfig) {\n this.SSLConfig = SSLConfig;\n }\n}", "public class JolokiaClient {\n private static final int MAX_CONNECTIONS = 2;\n private static J4pClient instance;\n private static AgentInfo agentInfo;\n\n\n private JolokiaClient(){\n }\n\n public static J4pClient init(AgentInfo initialAgentInfo){\n if (instance != null) {\n return instance;\n }\n agentInfo = initialAgentInfo;\n return getInstance();\n }\n\n public static synchronized J4pClient getInstance() {\n if (instance == null) {\n String user = agentInfo.getAgentUsername();\n String password = agentInfo.getAgentPassword();\n if (agentInfo.requiresLocalAuth() && agentInfo.getAgentUsername() == null) {\n user = agentInfo.getWebUsername();\n password = agentInfo.getWebPassword();\n }\n\n J4pClientBuilder clientBuilder = J4pClientBuilderFactory\n .url(agentInfo.getUrl())\n .user(user)\n .password(password)\n .maxTotalConnections(MAX_CONNECTIONS);\n\n SSLConfig config = agentInfo.getSSLConfig();\n if (config.isSelfSignedCertAllowed()) {\n try {\n SSLContext sslContext = new SSLContextBuilder()\n .loadTrustMaterial(null, new TrustSelfSignedStrategy())\n .build();\n\n SSLConnectionSocketFactory sslConnection = new SSLConnectionSocketFactory(\n sslContext,\n SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER\n );\n\n clientBuilder.sslConnectionSocketFactory(sslConnection);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n instance = clientBuilder.build();\n }\n return instance;\n }\n\n public static AgentInfo getAgentInfo() {\n return agentInfo;\n }\n}" ]
import org.jolokia.client.exception.J4pException; import org.jolokia.client.request.*; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import prj.jolokiaweb.JolokiaApp; import prj.jolokiaweb.form.ExecForm; import prj.jolokiaweb.form.ReadForm; import prj.jolokiaweb.form.WriteForm; import prj.jolokiaweb.jolokia.AgentInfo; import prj.jolokiaweb.jolokia.JolokiaClient; import javax.management.MalformedObjectNameException; import java.util.*;
package prj.jolokiaweb.controller; @RestController public class ApiController { @RequestMapping(value = "/api/checkPermissions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<JSONObject> checkPermissions() { JSONObject result = new JSONObject(); JSONArray arr = new JSONArray(); result.put("permissions", arr); if (JolokiaClient.getAgentInfo().getBeanPermissions().size() < 1) { arr.add(AgentInfo.JolokiaPermission.NONE); } else { for (AgentInfo.JolokiaPermission p: JolokiaClient.getAgentInfo().getBeanPermissions()) { arr.add(p); } } return ResponseEntity.ok(result); } @RequestMapping(value = "/api/beans", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<JSONObject> beans() { JSONObject result = new JSONObject(); try { String path = null; // null means full tree Map<J4pQueryParameter,String> params = new HashMap<>();; params.put(J4pQueryParameter.CANONICAL_NAMING,"false"); result = JolokiaClient.getInstance().execute(new J4pListRequest(path), params).asJSONObject(); } catch(Exception e) { result.put("error", e.getMessage()); return ResponseEntity.badRequest().body(result); } return ResponseEntity.ok(result); } @RequestMapping(value = "/api/version", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<JSONObject> version() { JSONObject result = new JSONObject(); try { J4pReadRequest runtimeReq = new J4pReadRequest("java.lang:type=Runtime"); J4pReadResponse runtimeRes = JolokiaClient.getInstance().execute(runtimeReq); J4pVersionResponse versionRes = JolokiaClient.getInstance().execute(new J4pVersionRequest()); result.put("runtime", runtimeRes.getValue()); result.put("version", versionRes.getValue()); } catch (Exception e) { result.put("error", e.getMessage()); return ResponseEntity.badRequest().body(result); } return ResponseEntity.ok(result); } @RequestMapping(value = "/api/read", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<JSONObject> read(@RequestBody ReadForm readForm) { JSONObject result = new JSONObject(); try { J4pReadRequest readReq = new J4pReadRequest(readForm.getMbean()); Map<J4pQueryParameter,String> params = new HashMap<>(); params.put(J4pQueryParameter.IGNORE_ERRORS,"true"); J4pReadResponse readRes = JolokiaClient.getInstance().execute(readReq, params); result = readRes.getValue(); } catch (MalformedObjectNameException e) { result.put("error", e.getMessage()); return ResponseEntity.badRequest().body(result); } catch (J4pException e) { result.put("error", e.getMessage()); return ResponseEntity.badRequest().body(result); } return ResponseEntity.ok(result); } @RequestMapping(value = "/api/execute", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<JSONObject> execute(@RequestBody ExecForm execForm) {
1
Erudika/scoold
src/main/java/com/erudika/scoold/controllers/ReportsController.java
[ "@Component\n@Named\npublic class ScooldConfig extends Config {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(ScooldConfig.class);\n\n\t@Override\n\tpublic com.typesafe.config.Config getFallbackConfig() {\n\t\treturn Para.getConfig().getConfig(); // fall back to para.* config\n\t}\n\n\t@Override\n\tpublic Set<String> getKeysExcludedFromRendering() {\n\t\treturn Set.of(\"scoold\", \"security.ignored\", \"security.protected.admin\");\n\t}\n\n\t@Override\n\tpublic String getConfigRootPrefix() {\n\t\treturn \"scoold\";\n\t}\n\n\t/* **************************************************************************************************************\n\t * Core Core *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 10,\n\t\t\tidentifier = \"app_name\",\n\t\t\tvalue = \"Scoold\",\n\t\t\tcategory = \"Core\",\n\t\t\tdescription = \"The formal name of the web application.\")\n\tpublic String appName() {\n\t\treturn getConfigParam(\"app_name\", \"Scoold\");\n\t}\n\n\t@Documented(position = 20,\n\t\t\tidentifier = \"para_access_key\",\n\t\t\tvalue = \"app:scoold\",\n\t\t\tcategory = \"Core\",\n\t\t\ttags = {\"requires restart\"},\n\t\t\tdescription = \"App identifier (access key) of the Para app used by Scoold.\")\n\tpublic String paraAccessKey() {\n\t\treturn getConfigParam(\"para_access_key\", getConfigParam(\"access_key\", \"app:scoold\"));\n\t}\n\n\t@Documented(position = 30,\n\t\t\tidentifier = \"para_secret_key\",\n\t\t\tvalue = \"x\",\n\t\t\tcategory = \"Core\",\n\t\t\ttags = {\"requires restart\"},\n\t\t\tdescription = \"Secret key of the Para app used by Scoold.\")\n\tpublic String paraSecretKey() {\n\t\treturn getConfigParam(\"para_secret_key\", getConfigParam(\"secret_key\", \"x\"));\n\t}\n\n\t@Documented(position = 40,\n\t\t\tidentifier = \"para_endpoint\",\n\t\t\tvalue = \"http://localhost:8080\",\n\t\t\tcategory = \"Core\",\n\t\t\ttags = {\"requires restart\"},\n\t\t\tdescription = \"The URL of the Para server for Scoold to connects to. For hosted Para, use `https://paraio.com`\")\n\tpublic String paraEndpoint() {\n\t\treturn getConfigParam(\"para_endpoint\", getConfigParam(\"endpoint\", \"http://localhost:8080\"));\n\t}\n\n\t@Documented(position = 50,\n\t\t\tidentifier = \"host_url\",\n\t\t\tvalue = \"http://localhost:8000\",\n\t\t\tcategory = \"Core\",\n\t\t\tdescription = \"The internet-facing (public) URL of this Scoold server.\")\n\tpublic String serverUrl() {\n\t\treturn StringUtils.removeEnd(getConfigParam(\"host_url\", \"http://localhost:\" + serverPort()), \"/\");\n\t}\n\n\t@Documented(position = 60,\n\t\t\tidentifier = \"port\",\n\t\t\tvalue = \"8000\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Core\",\n\t\t\ttags = {\"requires restart\"},\n\t\t\tdescription = \"The network port of this Scoold server. Port number should be a number above `1024`.\")\n\tpublic int serverPort() {\n\t\treturn NumberUtils.toInt(System.getProperty(\"server.port\"), getConfigInt(\"port\", 8000));\n\t}\n\n\t@Documented(position = 70,\n\t\t\tidentifier = \"env\",\n\t\t\tvalue = \"development\",\n\t\t\tcategory = \"Core\",\n\t\t\ttags = {\"requires restart\"},\n\t\t\tdescription = \"The environment profile to be used - possible values are `production` or `development`\")\n\tpublic String environment() {\n\t\treturn getConfigParam(\"env\", \"development\");\n\t}\n\n\t@Documented(position = 80,\n\t\t\tidentifier = \"app_secret_key\",\n\t\t\tcategory = \"Core\",\n\t\t\tdescription = \"A random secret string, min. 32 chars long. *Must be different from the secret key of \"\n\t\t\t\t\t+ \"the Para app*. Used for generating JWTs and passwordless authentication tokens.\")\n\tpublic String appSecretKey() {\n\t\treturn getConfigParam(\"app_secret_key\", \"\");\n\t}\n\n\t@Documented(position = 90,\n\t\t\tidentifier = \"admins\",\n\t\t\tcategory = \"Core\",\n\t\t\tdescription = \"A comma-separated list of emails of people who will be promoted to administrators with \"\n\t\t\t\t\t+ \"full rights over the content on the site. This can also contain Para user identifiers.\")\n\tpublic String admins() {\n\t\treturn getConfigParam(\"admins\", \"\");\n\t}\n\n\t@Documented(position = 100,\n\t\t\tidentifier = \"is_default_space_public\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Core\",\n\t\t\tdescription = \"When enabled, all content in the default space will be publicly visible, \"\n\t\t\t\t\t+ \"without authentication, incl. users and tags. Disable to make the site private.\")\n\tpublic boolean isDefaultSpacePublic() {\n\t\treturn getConfigBoolean(\"is_default_space_public\", true);\n\t}\n\n\t@Documented(position = 110,\n\t\t\tidentifier = \"context_path\",\n\t\t\tcategory = \"Core\",\n\t\t\ttags = {\"requires restart\"},\n\t\t\tdescription = \"The context path (subpath) of the web application, defaults to the root path `/`.\")\n\tpublic String serverContextPath() {\n\t\tString context = getConfigParam(\"context_path\", \"\");\n\t\treturn StringUtils.stripEnd((StringUtils.isBlank(context) ?\n\t\t\t\tSystem.getProperty(\"server.servlet.context-path\", \"\") : context), \"/\");\n\t}\n\n\t@Documented(position = 120,\n\t\t\tidentifier = \"webhooks_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Core\",\n\t\t\tdescription = \"Enable/disable webhooks support for events like `question.create`, `user.signup`, etc.\")\n\tpublic boolean webhooksEnabled() {\n\t\treturn getConfigBoolean(\"webhooks_enabled\", true);\n\t}\n\n\t@Documented(position = 130,\n\t\t\tidentifier = \"api_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Core\",\n\t\t\tdescription = \"Enable/disable the Scoold RESTful API. Disabled by default.\")\n\tpublic boolean apiEnabled() {\n\t\treturn getConfigBoolean(\"api_enabled\", false);\n\t}\n\n\t@Documented(position = 140,\n\t\t\tidentifier = \"feedback_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Core\",\n\t\t\tdescription = \"Enable/disable the feedback page on the site. It is intended for internal discussion \"\n\t\t\t\t\t+ \"about the website itself.\")\n\tpublic boolean feedbackEnabled() {\n\t\treturn getConfigBoolean(\"feedback_enabled\", false);\n\t}\n\n\n\t/* **************************************************************************************************************\n\t * Emails Emails *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 150,\n\t\t\tidentifier = \"support_email\",\n\t\t\tvalue = \"[email protected]\",\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"The email address to use for sending transactional emails, like welcome/password reset emails.\")\n\tpublic String supportEmail() {\n\t\treturn getConfigParam(\"support_email\", \"[email protected]\");\n\t}\n\n\t@Documented(position = 160,\n\t\t\tidentifier = \"mail.host\",\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"The SMTP server host to use for sending emails.\")\n\tpublic String mailHost() {\n\t\treturn getConfigParam(\"mail.host\", \"\");\n\t}\n\n\t@Documented(position = 170,\n\t\t\tidentifier = \"mail.port\",\n\t\t\tvalue = \"587\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"The SMTP server port to use for sending emails.\")\n\tpublic int mailPort() {\n\t\treturn getConfigInt(\"mail.port\", 587);\n\t}\n\n\t@Documented(position = 180,\n\t\t\tidentifier = \"mail.username\",\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"The SMTP server username.\")\n\tpublic String mailUsername() {\n\t\treturn getConfigParam(\"mail.username\", \"\");\n\t}\n\n\t@Documented(position = 190,\n\t\t\tidentifier = \"mail.password\",\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"The SMTP server password.\")\n\tpublic String mailPassword() {\n\t\treturn getConfigParam(\"mail.password\", \"\");\n\t}\n\n\t@Documented(position = 200,\n\t\t\tidentifier = \"mail.tls\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Enable/disable TLS for the SMTP connection.\")\n\tpublic boolean mailTLSEnabled() {\n\t\treturn getConfigBoolean(\"mail.tls\", true);\n\t}\n\n\t@Documented(position = 210,\n\t\t\tidentifier = \"mail.ssl\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Enable/disable SSL for the SMTP connection.\")\n\tpublic boolean mailSSLEnabled() {\n\t\treturn getConfigBoolean(\"mail.ssl\", false);\n\t}\n\n\t@Documented(position = 220,\n\t\t\tidentifier = \"mail.debug\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Enable/disable debug information when sending emails through SMTP.\")\n\tpublic boolean mailDebugEnabled() {\n\t\treturn getConfigBoolean(\"mail.debug\", false);\n\t}\n\n\t@Documented(position = 230,\n\t\t\tidentifier = \"favtags_emails_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Set the default toggle value for all users for receiving emails for new content \"\n\t\t\t\t\t+ \"with their favorite tags.\")\n\tpublic boolean favoriteTagsEmailsEnabled() {\n\t\treturn getConfigBoolean(\"favtags_emails_enabled\", false);\n\t}\n\n\t@Documented(position = 240,\n\t\t\tidentifier = \"reply_emails_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Set the default toggle value for all users for receiving emails for answers to their questions.\")\n\tpublic boolean replyEmailsEnabled() {\n\t\treturn getConfigBoolean(\"reply_emails_enabled\", false);\n\t}\n\n\t@Documented(position = 250,\n\t\t\tidentifier = \"comment_emails_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Set the default toggle value for all users for receiving emails for comments on their posts.\")\n\tpublic boolean commentEmailsEnabled() {\n\t\treturn getConfigBoolean(\"comment_emails_enabled\", false);\n\t}\n\n\t@Documented(position = 260,\n\t\t\tidentifier = \"summary_email_period_days\",\n\t\t\tvalue = \"7\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Emails\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"The time period between each content digest email, in days.\")\n\tpublic int emailsSummaryIntervalDays() {\n\t\treturn getConfigInt(\"summary_email_period_days\", 7);\n\t}\n\n\t@Documented(position = 270,\n\t\t\tidentifier = \"summary_email_items\",\n\t\t\tvalue = \"25\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"The number of posts to include in the digest email (a summary of new posts).\")\n\tpublic int emailsSummaryItems() {\n\t\treturn getConfigInt(\"summary_email_items\", 25);\n\t}\n\n\t@Documented(position = 280,\n\t\t\tidentifier = \"notification_emails_allowed\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Enable/disable *all* notification emails.\")\n\tpublic boolean notificationEmailsAllowed() {\n\t\treturn getConfigBoolean(\"notification_emails_allowed\", true);\n\t}\n\n\t@Documented(position = 290,\n\t\t\tidentifier = \"newpost_emails_allowed\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Enable/disable *all* email notifications for every new question that is posted on the site.\")\n\tpublic boolean emailsForNewPostsAllowed() {\n\t\treturn getConfigBoolean(\"newpost_emails_allowed\", true);\n\t}\n\n\t@Documented(position = 300,\n\t\t\tidentifier = \"favtags_emails_allowed\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Enable/disable *all* email notifications for every new question tagged with a favorite tag.\")\n\tpublic boolean emailsForFavtagsAllowed() {\n\t\treturn getConfigBoolean(\"favtags_emails_allowed\", true);\n\t}\n\n\t@Documented(position = 310,\n\t\t\tidentifier = \"reply_emails_allowed\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Enable/disable *all* email notifications for every new answer that is posted on the site.\")\n\tpublic boolean emailsForRepliesAllowed() {\n\t\treturn getConfigBoolean(\"reply_emails_allowed\", true);\n\t}\n\n\t@Documented(position = 320,\n\t\t\tidentifier = \"comment_emails_allowed\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Enable/disable *all* email notifications for every new comment that is posted on the site.\")\n\tpublic boolean emailsForCommentsAllowed() {\n\t\treturn getConfigBoolean(\"comment_emails_allowed\", true);\n\t}\n\n\t@Documented(position = 330,\n\t\t\tidentifier = \"mentions_emails_allowed\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable *all* email notifications every time a user is mentioned.\")\n\tpublic boolean emailsForMentionsAllowed() {\n\t\treturn getConfigBoolean(\"mentions_emails_allowed\", true);\n\t}\n\n\t@Documented(position = 340,\n\t\t\tidentifier = \"summary_email_controlled_by_admins\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Controls whether admins can enable/disable summary emails for everyone from the 'Settings' page\")\n\tpublic boolean emailsForSummaryControlledByAdmins() {\n\t\treturn getConfigBoolean(\"summary_email_controlled_by_admins\", false);\n\t}\n\n\t@Documented(position = 350,\n\t\t\tidentifier = \"mention_emails_controlled_by_admins\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Emails\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Controls whether admins can enable/disable mention emails for everyone from the 'Settings' page\")\n\tpublic boolean emailsForMentionsControlledByAdmins() {\n\t\treturn getConfigBoolean(\"mention_emails_controlled_by_admins\", false);\n\t}\n\n\t@Documented(position = 360,\n\t\t\tidentifier = \"emails.welcome_text1\",\n\t\t\tvalue = \"You are now part of {0} - a friendly Q&A community...\",\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Allows for changing the default text (first paragraph) in the welcome email message.\")\n\tpublic String emailsWelcomeText1(Map<String, String> lang) {\n\t\treturn getConfigParam(\"emails.welcome_text1\", lang.get(\"signin.welcome.body1\") + \"<br><br>\");\n\t}\n\n\t@Documented(position = 370,\n\t\t\tidentifier = \"emails.welcome_text2\",\n\t\t\tvalue = \"To get started, simply navigate to the \\\"Ask question\\\" page and ask a question...\",\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Allows for changing the default text (second paragraph) in the welcome email message.\")\n\tpublic String emailsWelcomeText2(Map<String, String> lang) {\n\t\treturn getConfigParam(\"emails.welcome_text2\", lang.get(\"signin.welcome.body2\") + \"<br><br>\");\n\t}\n\n\t@Documented(position = 380,\n\t\t\tidentifier = \"emails.welcome_text3\",\n\t\t\tvalue = \"Best, <br>The {0} team\",\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"Allows for changing the default text (signature at the end) in the welcome email message.\")\n\tpublic String emailsWelcomeText3(Map<String, String> lang) {\n\t\treturn getConfigParam(\"emails.welcome_text3\", lang.get(\"notification.signature\") + \"<br><br>\");\n\t}\n\n\t@Documented(position = 390,\n\t\t\tidentifier = \"emails.default_signature\",\n\t\t\tvalue = \"Best, <br>The {0} team\",\n\t\t\tcategory = \"Emails\",\n\t\t\tdescription = \"The default email signature for all transactional emails sent from Scoold.\")\n\tpublic String emailsDefaultSignatureText(String defaultText) {\n\t\treturn getConfigParam(\"emails.default_signature\", defaultText);\n\t}\n\n\t/* **************************************************************************************************************\n\t * Security Security *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 400,\n\t\t\tidentifier = \"approved_domains_for_signups\",\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"A comma-separated list of domain names, which will be used to restrict the people who \"\n\t\t\t\t\t+ \"are allowed to sign up on the site.\")\n\tpublic String approvedDomainsForSignups() {\n\t\treturn getConfigParam(\"approved_domains_for_signups\", \"\");\n\t}\n\n\t@Documented(position = 410,\n\t\t\tidentifier = \"security.allow_unverified_emails\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Enable/disable email verification after the initial user registration. Users with unverified \"\n\t\t\t\t\t+ \"emails won't be able to sign in, unless they use a social login provider.\")\n\tpublic boolean allowUnverifiedEmails() {\n\t\treturn getConfigBoolean(\"security.allow_unverified_emails\", StringUtils.isBlank(mailHost()));\n\t}\n\n\t@Documented(position = 420,\n\t\t\tidentifier = \"session_timeout\",\n\t\t\tvalue = \"86400\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"The validity period of the authentication cookie, in seconds. Default is 24h.\")\n\tpublic int sessionTimeoutSec() {\n\t\treturn getConfigInt(\"session_timeout\", Para.getConfig().sessionTimeoutSec());\n\t}\n\n\t@Documented(position = 430,\n\t\t\tidentifier = \"jwt_expires_after\",\n\t\t\tvalue = \"86400\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"The validity period of the session token (JWT), in seconds. Default is 24h.\")\n\tpublic int jwtExpiresAfterSec() {\n\t\treturn getConfigInt(\"jwt_expires_after\", Para.getConfig().jwtExpiresAfterSec());\n\t}\n\n\t@Documented(position = 440,\n\t\t\tidentifier = \"security.one_session_per_user\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"If disabled, users can sign in from multiple locations and devices, keeping a few open \"\n\t\t\t\t\t+ \"sessions at once. Otherwise, only one session will be kept open, others will be closed.\")\n\tpublic boolean oneSessionPerUser() {\n\t\treturn getConfigBoolean(\"security.one_session_per_user\", true);\n\t}\n\n\t@Documented(position = 450,\n\t\t\tidentifier = \"min_password_length\",\n\t\t\tvalue = \"8\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"The minimum length of passwords.\")\n\tpublic int minPasswordLength() {\n\t\treturn getConfigInt(\"min_password_length\", Para.getConfig().minPasswordLength());\n\t}\n\n\t@Documented(position = 460,\n\t\t\tidentifier = \"min_password_strength\",\n\t\t\tvalue = \"2\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"The minimum password strength - one of 3 levels: `1` good enough, `2` strong, `3` very strong.\")\n\tpublic int minPasswordStrength() {\n\t\treturn getConfigInt(\"min_password_strength\", 2);\n\t}\n\n\t@Documented(position = 470,\n\t\t\tidentifier = \"pass_reset_timeout\",\n\t\t\tvalue = \"1800\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"The validity period of the password reset token sent via email for resetting users' \"\n\t\t\t\t\t+ \"passwords. Default is 30 min.\")\n\tpublic int passwordResetTimeoutSec() {\n\t\treturn getConfigInt(\"pass_reset_timeout\", Para.getConfig().passwordResetTimeoutSec());\n\t}\n\n\t@Documented(position = 480,\n\t\t\tidentifier = \"profile_anonimity_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Enable/disable the option for users to anonimize their profiles on the site, \"\n\t\t\t\t\t+ \"hiding their name and picture.\")\n\tpublic boolean profileAnonimityEnabled() {\n\t\treturn getConfigBoolean(\"profile_anonimity_enabled\", false);\n\t}\n\n\t@Documented(position = 490,\n\t\t\tidentifier = \"signup_captcha_site_key\",\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"The reCAPTCHA v3 site key for protecting the signup and password reset pages.\")\n\tpublic String captchaSiteKey() {\n\t\treturn getConfigParam(\"signup_captcha_site_key\", \"\");\n\t}\n\n\t@Documented(position = 500,\n\t\t\tidentifier = \"signup_captcha_secret_key\",\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"The reCAPTCHA v3 secret.\")\n\tpublic String captchaSecretKey() {\n\t\treturn getConfigParam(\"signup_captcha_secret_key\", \"\");\n\t}\n\t@Documented(position = 510,\n\t\t\tidentifier = \"csp_reports_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Enable/disable automatic reports each time the Content Security Policy is violated.\")\n\tpublic boolean cspReportsEnabled() {\n\t\treturn getConfigBoolean(\"csp_reports_enabled\", false);\n\t}\n\n\t@Documented(position = 520,\n\t\t\tidentifier = \"csp_header_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Enable/disable the Content Security Policy (CSP) header.\")\n\tpublic boolean cspHeaderEnabled() {\n\t\treturn getConfigBoolean(\"csp_header_enabled\", true);\n\t}\n\n\t@Documented(position = 530,\n\t\t\tidentifier = \"csp_header\",\n\t\t\tvalue = \"Dynamically generated, with nonces\",\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"The CSP header value which will overwrite the default one. This can contain one or more \"\n\t\t\t\t\t+ \"`{{nonce}}` placeholders, which will be replaced with an actual nonce on each request.\")\n\tpublic String cspHeader(String nonce) {\n\t\treturn getConfigParam(\"csp_header\", getDefaultContentSecurityPolicy()).replaceAll(\"\\\\{\\\\{nonce\\\\}\\\\}\", nonce);\n\t}\n\n\t@Documented(position = 540,\n\t\t\tidentifier = \"hsts_header_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Enable/disable the `Strict-Transport-Security` security header.\")\n\tpublic boolean hstsHeaderEnabled() {\n\t\treturn getConfigBoolean(\"hsts_header_enabled\", true);\n\t}\n\n\t@Documented(position = 550,\n\t\t\tidentifier = \"framing_header_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Enable/disable the `X-Frame-Options` security header.\")\n\tpublic boolean framingHeaderEnabled() {\n\t\treturn getConfigBoolean(\"framing_header_enabled\", true);\n\t}\n\n\t@Documented(position = 560,\n\t\t\tidentifier = \"xss_header_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Enable/disable the `X-XSS-Protection` security header.\")\n\tpublic boolean xssHeaderEnabled() {\n\t\treturn getConfigBoolean(\"xss_header_enabled\", true);\n\t}\n\n\t@Documented(position = 570,\n\t\t\tidentifier = \"contenttype_header_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Enable/disable the `X-Content-Type-Options` security header.\")\n\tpublic boolean contentTypeHeaderEnabled() {\n\t\treturn getConfigBoolean(\"contenttype_header_enabled\", true);\n\t}\n\n\t@Documented(position = 580,\n\t\t\tidentifier = \"referrer_header_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Enable/disable the `Referrer-Policy` security header.\")\n\tpublic boolean referrerHeaderEnabled() {\n\t\treturn getConfigBoolean(\"referrer_header_enabled\", true);\n\t}\n\n\t@Documented(position = 590,\n\t\t\tidentifier = \"permissions_header_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Enable/disable the `Permissions-Policy` security header.\")\n\tpublic boolean permissionsHeaderEnabled() {\n\t\treturn getConfigBoolean(\"permissions_header_enabled\", true);\n\t}\n\n\t@Documented(position = 600,\n\t\t\tidentifier = \"csp_connect_sources\",\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Additional sources to add to the `connect-src` CSP directive. \"\n\t\t\t\t\t+ \"Used when adding external scripts to the site.\")\n\tpublic String cspConnectSources() {\n\t\treturn getConfigParam(\"csp_connect_sources\", \"\");\n\t}\n\n\t@Documented(position = 610,\n\t\t\tidentifier = \"csp_frame_sources\",\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Additional sources to add to the `frame-src` CSP directive. \"\n\t\t\t\t\t+ \"Used when adding external scripts to the site.\")\n\tpublic String cspFrameSources() {\n\t\treturn getConfigParam(\"csp_frame_sources\", \"\");\n\t}\n\n\t@Documented(position = 620,\n\t\t\tidentifier = \"csp_font_sources\",\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Additional sources to add to the `font-src` CSP directive. \"\n\t\t\t\t\t+ \"Used when adding external fonts to the site.\")\n\tpublic String cspFontSources() {\n\t\treturn getConfigParam(\"csp_font_sources\", \"\");\n\t}\n\n\t@Documented(position = 630,\n\t\t\tidentifier = \"csp_style_sources\",\n\t\t\tvalue = \"\",\n\t\t\tcategory = \"Security\",\n\t\t\tdescription = \"Additional sources to add to the `style-src` CSP directive. \"\n\t\t\t\t\t+ \"Used when adding external fonts to the site.\")\n\tpublic String cspStyleSources() {\n\t\treturn getConfigParam(\"csp_style_sources\", stylesheetUrl() + \" \" + externalStyles().replaceAll(\",\", \"\"));\n\t}\n\n\t/* **************************************************************************************************************\n\t * Basic Authentication Basic Authentication *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 640,\n\t\t\tidentifier = \"password_auth_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Enabled/disable the ability for users to sign in with an email and password.\")\n\tpublic boolean passwordAuthEnabled() {\n\t\treturn getConfigBoolean(\"password_auth_enabled\", true);\n\t}\n\n\t@Documented(position = 650,\n\t\t\tidentifier = \"fb_app_id\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Facebook OAuth2 app ID.\")\n\tpublic String facebookAppId() {\n\t\treturn getConfigParam(\"fb_app_id\", \"\");\n\t}\n\n\t@Documented(position = 660,\n\t\t\tidentifier = \"fb_secret\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Facebook app secret key.\")\n\tpublic String facebookSecret() {\n\t\treturn getConfigParam(\"fb_secret\", \"\");\n\t}\n\n\t@Documented(position = 670,\n\t\t\tidentifier = \"gp_app_id\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Google OAuth2 app ID.\")\n\tpublic String googleAppId() {\n\t\treturn getConfigParam(\"gp_app_id\", \"\");\n\t}\n\n\t@Documented(position = 680,\n\t\t\tidentifier = \"gp_secret\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Google app secret key.\")\n\tpublic String googleSecret() {\n\t\treturn getConfigParam(\"gp_secret\", \"\");\n\t}\n\n\t@Documented(position = 690,\n\t\t\tidentifier = \"in_app_id\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"LinkedIn OAuth2 app ID.\")\n\tpublic String linkedinAppId() {\n\t\treturn getConfigParam(\"in_app_id\", \"\");\n\t}\n\n\t@Documented(position = 700,\n\t\t\tidentifier = \"in_secret\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"LinkedIn app secret key.\")\n\tpublic String linkedinSecret() {\n\t\treturn getConfigParam(\"in_secret\", \"\");\n\t}\n\n\t@Documented(position = 710,\n\t\t\tidentifier = \"tw_app_id\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Twitter OAuth app ID.\")\n\tpublic String twitterAppId() {\n\t\treturn getConfigParam(\"tw_app_id\", \"\");\n\t}\n\n\t@Documented(position = 720,\n\t\t\tidentifier = \"tw_secret\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Twitter app secret key.\")\n\tpublic String twitterSecret() {\n\t\treturn getConfigParam(\"tw_secret\", \"\");\n\t}\n\n\t@Documented(position = 730,\n\t\t\tidentifier = \"gh_app_id\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"GitHub OAuth2 app ID.\")\n\tpublic String githubAppId() {\n\t\treturn getConfigParam(\"gh_app_id\", \"\");\n\t}\n\n\t@Documented(position = 740,\n\t\t\tidentifier = \"gh_secret\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"GitHub app secret key.\")\n\tpublic String githubSecret() {\n\t\treturn getConfigParam(\"gh_secret\", \"\");\n\t}\n\n\t@Documented(position = 750,\n\t\t\tidentifier = \"ms_app_id\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Microsoft OAuth2 app ID.\")\n\tpublic String microsoftAppId() {\n\t\treturn getConfigParam(\"ms_app_id\", \"\");\n\t}\n\n\t@Documented(position = 760,\n\t\t\tidentifier = \"ms_secret\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Microsoft app secret key.\")\n\tpublic String microsoftSecret() {\n\t\treturn getConfigParam(\"ms_secret\", \"\");\n\t}\n\n\t@Documented(position = 770,\n\t\t\tidentifier = \"ms_tenant_id\",\n\t\t\tvalue = \"common\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Microsoft OAuth2 tenant ID\")\n\tpublic String microsoftTenantId() {\n\t\treturn getConfigParam(\"ms_tenant_id\", \"common\");\n\t}\n\n\t@Documented(position = 780,\n\t\t\tidentifier = \"az_app_id\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Amazon OAuth2 app ID.\")\n\tpublic String amazonAppId() {\n\t\treturn getConfigParam(\"az_app_id\", \"\");\n\t}\n\n\t@Documented(position = 790,\n\t\t\tidentifier = \"az_secret\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\tdescription = \"Amazon app secret key.\")\n\tpublic String amazonSecret() {\n\t\treturn getConfigParam(\"az_secret\", \"\");\n\t}\n\n\t@Documented(position = 800,\n\t\t\tidentifier = \"sl_app_id\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Slack OAuth2 app ID.\")\n\tpublic String slackAppId() {\n\t\treturn getConfigParam(\"sl_app_id\", \"\");\n\t}\n\n\t@Documented(position = 810,\n\t\t\tidentifier = \"sl_secret\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Slack app secret key.\")\n\tpublic String slackSecret() {\n\t\treturn getConfigParam(\"sl_secret\", \"\");\n\t}\n\n\t@Documented(position = 820,\n\t\t\tidentifier = \"mm_app_id\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Mattermost OAuth2 app ID.\")\n\tpublic String mattermostAppId() {\n\t\treturn getConfigParam(\"mm_app_id\", \"\");\n\t}\n\n\t@Documented(position = 830,\n\t\t\tidentifier = \"mm_secret\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Mattermost app secret key.\")\n\tpublic String mattermostSecret() {\n\t\treturn getConfigParam(\"mm_secret\", \"\");\n\t}\n\n\t@Documented(position = 840,\n\t\t\tidentifier = \"security.custom.provider\",\n\t\t\tvalue = \"Continue with Acme Co.\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"The text on the button for signing in with the custom authentication scheme.\")\n\tpublic String customLoginProvider() {\n\t\treturn getConfigParam(\"security.custom.provider\", \"Continue with Acme Co.\");\n\t}\n\n\t@Documented(position = 850,\n\t\t\tidentifier = \"security.custom.login_url\",\n\t\t\tcategory = \"Basic Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"The URL address of an externally hosted, custom login page.\")\n\tpublic String customLoginUrl() {\n\t\treturn getConfigParam(\"security.custom.login_url\", \"\");\n\t}\n\n\t/* **************************************************************************************************************\n\t * LDAP Authentication LDAP Authentication *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 860,\n\t\t\tidentifier = \"security.ldap.server_url\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"LDAP server URL. LDAP will be disabled if this is blank.\")\n\tpublic String ldapServerUrl() {\n\t\treturn getConfigParam(\"security.ldap.server_url\", \"\");\n\t}\n\n\t@Documented(position = 870,\n\t\t\tidentifier = \"security.ldap.base_dn\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"LDAP base DN.\")\n\tpublic String ldapBaseDN() {\n\t\treturn getConfigParam(\"security.ldap.base_dn\", \"\");\n\t}\n\n\t@Documented(position = 880,\n\t\t\tidentifier = \"security.ldap.user_search_base\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"LDAP search base, which will be used only if a direct bind is unsuccessfull.\")\n\tpublic String ldapUserSearchBase() {\n\t\treturn getConfigParam(\"security.ldap.user_search_base\", \"\");\n\t}\n\n\t@Documented(position = 890,\n\t\t\tidentifier = \"security.ldap.user_search_filter\",\n\t\t\tvalue = \"(cn={0})\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"LDAP search filter, for finding users if a direct bind is unsuccessful.\")\n\tpublic String ldapUserSearchFilter() {\n\t\treturn getConfigParam(\"security.ldap.user_search_filter\", \"(cn={0})\");\n\t}\n\n\t@Documented(position = 900,\n\t\t\tidentifier = \"security.ldap.user_dn_pattern\",\n\t\t\tvalue = \"uid={0}\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"LDAP user DN pattern, which will be comined with the base DN to form the full path to the\"\n\t\t\t\t\t+ \"user object, for a direct binding attempt.\")\n\tpublic String ldapUserDNPattern() {\n\t\treturn getConfigParam(\"security.ldap.user_dn_pattern\", \"uid={0}\");\n\t}\n\n\t@Documented(position = 910,\n\t\t\tidentifier = \"security.ldap.active_directory_domain\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"AD domain name. Add this *only* if you are connecting to an Active Directory server.\")\n\tpublic String ldapActiveDirectoryDomain() {\n\t\treturn getConfigParam(\"security.ldap.active_directory_domain\", \"\");\n\t}\n\n\t@Documented(position = 920,\n\t\t\tidentifier = \"security.ldap.password_attribute\",\n\t\t\tvalue = \"userPassword\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"LDAP password attribute name.\")\n\tpublic String ldapPasswordAttributeName() {\n\t\treturn getConfigParam(\"security.ldap.password_attribute\", \"userPassword\");\n\t}\n\n\t@Documented(position = 930,\n\t\t\tidentifier = \"security.ldap.bind_dn\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"LDAP bind DN\")\n\tpublic String ldapBindDN() {\n\t\treturn getConfigParam(\"security.ldap.bind_dn\", \"\");\n\t}\n\n\t@Documented(position = 940,\n\t\t\tidentifier = \"security.ldap.bind_pass\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"LDAP bind password.\")\n\tpublic String ldapBindPassword() {\n\t\treturn getConfigParam(\"security.ldap.bind_pass\", \"\");\n\t}\n\n\t@Documented(position = 950,\n\t\t\tidentifier = \"security.ldap.username_as_name\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"Enable/disable the use of usernames for names on Scoold.\")\n\tpublic boolean ldapUsernameAsName() {\n\t\treturn getConfigBoolean(\"security.ldap.username_as_name\", false);\n\t}\n\n\t@Documented(position = 960,\n\t\t\tidentifier = \"security.ldap.provider\",\n\t\t\tvalue = \"Continue with LDAP\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"The text on the LDAP sign in button.\")\n\tpublic String ldapProvider() {\n\t\treturn getConfigParam(\"security.ldap.provider\", \"Continue with LDAP\");\n\t}\n\n\t@Documented(position = 970,\n\t\t\tidentifier = \"security.ldap.mods_group_node\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"Moderators group mapping, mapping LDAP users with this node, to moderators on Scoold.\")\n\tpublic String ldapModeratorsGroupNode() {\n\t\treturn getConfigParam(\"security.ldap.mods_group_node\", \"\");\n\t}\n\n\t@Documented(position = 980,\n\t\t\tidentifier = \"security.ldap.admins_group_node\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"Administrators group mapping, mapping LDAP users with this node, to administrators on Scoold.\")\n\tpublic String ldapAdministratorsGroupNode() {\n\t\treturn getConfigParam(\"security.ldap.admins_group_node\", \"\");\n\t}\n\n\t@Documented(position = 990,\n\t\t\tidentifier = \"security.ldap.compare_passwords\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"LDAP compare passwords.\")\n\tpublic String ldapComparePasswords() {\n\t\treturn getConfigParam(\"security.ldap.compare_passwords\", \"\");\n\t}\n\n\t@Documented(position = 1000,\n\t\t\tidentifier = \"security.ldap.password_param\",\n\t\t\tvalue = \"password\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"LDAP password parameter name.\")\n\tpublic String ldapPasswordParameter() {\n\t\treturn getConfigParam(\"security.ldap.password_param\", \"password\");\n\t}\n\n\t@Documented(position = 1010,\n\t\t\tidentifier = \"security.ldap.username_param\",\n\t\t\tvalue = \"username\",\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\tdescription = \"LDAP username parameter name.\")\n\tpublic String ldapUsernameParameter() {\n\t\treturn getConfigParam(\"security.ldap.username_param\", \"username\");\n\t}\n\n\t@Documented(position = 1020,\n\t\t\tidentifier = \"security.ldap.is_local\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"LDAP Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable local handling of LDAP requests, instead of sending those to Para.\")\n\tpublic boolean ldapIsLocal() {\n\t\treturn getConfigBoolean(\"security.ldap.is_local\", false);\n\t}\n\n\t/* **************************************************************************************************************\n\t * SAML Authentication SAML Authentication *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 1030,\n\t\t\tidentifier = \"security.saml.idp.metadata_url\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML metadata URL. Scoold will fetch most of the necessary information for the authentication\"\n\t\t\t\t\t+ \" request from that XML document. This will overwrite all other IDP settings.\")\n\tpublic String samlIDPMetadataUrl() {\n\t\treturn getConfigParam(\"security.saml.idp.metadata_url\", \"\");\n\t}\n\n\t@Documented(position = 1040,\n\t\t\tidentifier = \"security.saml.sp.entityid\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML SP endpoint address - e.g. `https://paraio.com/saml_auth/scoold`. The IDP will call \"\n\t\t\t\t\t+ \"this address for authentication.\")\n\tpublic String samlSPEntityId() {\n\t\tif (samlIsLocal()) {\n\t\t\treturn serverUrl() + serverContextPath() + \"/saml_auth\";\n\t\t}\n\t\treturn getConfigParam(\"security.saml.sp.entityid\", \"\");\n\t}\n\n\t@Documented(position = 1050,\n\t\t\tidentifier = \"security.saml.sp.x509cert\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML client x509 certificate for the SP (public key). **Value must be Base64-encoded**.\")\n\tpublic String samlSPX509Certificate() {\n\t\treturn getConfigParam(\"security.saml.sp.x509cert\", \"\");\n\t}\n\n\t@Documented(position = 1060,\n\t\t\tidentifier = \"security.saml.sp.privatekey\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML client private key in PKCS#8 format for the SP. **Value must be Base64-encoded**.\")\n\tpublic String samlSPX509PrivateKey() {\n\t\treturn getConfigParam(\"security.saml.sp.privatekey\", \"\");\n\t}\n\n\t@Documented(position = 1070,\n\t\t\tidentifier = \"security.saml.attributes.id\",\n\t\t\tvalue = \"UserID\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML attribute name of the user `id`.\")\n\tpublic String samlIdAttribute() {\n\t\treturn getConfigParam(\"security.saml.attributes.id\", \"UserID\");\n\t}\n\n\t@Documented(position = 1080,\n\t\t\tidentifier = \"security.saml.attributes.picture\",\n\t\t\tvalue = \"Picture\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML attribute name of the user `picture`.\")\n\tpublic String samlPictureAttribute() {\n\t\treturn getConfigParam(\"security.saml.attributes.picture\", \"Picture\");\n\t}\n\n\t@Documented(position = 1090,\n\t\t\tidentifier = \"security.saml.attributes.email\",\n\t\t\tvalue = \"EmailAddress\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML attribute name of the user `email`.\")\n\tpublic String samlEmailAttribute() {\n\t\treturn getConfigParam(\"security.saml.attributes.email\", \"EmailAddress\");\n\t}\n\n\t@Documented(position = 1100,\n\t\t\tidentifier = \"security.saml.attributes.name\",\n\t\t\tvalue = \"GivenName\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML attribute name of the user `name`.\")\n\tpublic String samlNameAttribute() {\n\t\treturn getConfigParam(\"security.saml.attributes.name\", \"GivenName\");\n\t}\n\n\t@Documented(position = 1110,\n\t\t\tidentifier = \"security.saml.attributes.firstname\",\n\t\t\tvalue = \"FirstName\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML attribute name of the user `firstname`.\")\n\tpublic String samlFirstNameAttribute() {\n\t\treturn getConfigParam(\"security.saml.attributes.firstname\", \"FirstName\");\n\t}\n\n\t@Documented(position = 1120,\n\t\t\tidentifier = \"security.saml.attributes.lastname\",\n\t\t\tvalue = \"LastName\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML attribute name of the user `lastname`.\")\n\tpublic String samlLastNameAttribute() {\n\t\treturn getConfigParam(\"security.saml.attributes.lastname\", \"LastName\");\n\t}\n\n\t@Documented(position = 1130,\n\t\t\tidentifier = \"security.saml.provider\",\n\t\t\tvalue = \"Continue with SAML\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"The text on the button for signing in with SAML.\")\n\tpublic String samlProvider() {\n\t\treturn getConfigParam(\"security.saml.provider\", \"Continue with SAML\");\n\t}\n\n\t@Documented(position = 1140,\n\t\t\tidentifier = \"security.saml.sp.assertion_consumer_service.url\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML ACS URL.\")\n\tpublic String samlSPAssertionConsumerServiceUrl() {\n\t\treturn getConfigParam(\"security.saml.sp.assertion_consumer_service.url\", samlIsLocal() ? samlSPEntityId() : \"\");\n\t}\n\n\t@Documented(position = 1150,\n\t\t\tidentifier = \"security.saml.sp.nameidformat\",\n\t\t\tvalue = \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML name id format.\")\n\tpublic String samlSPNameIdFormat() {\n\t\treturn getConfigParam(\"security.saml.sp.nameidformat\", \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\");\n\t}\n\n\t@Documented(position = 1160,\n\t\t\tidentifier = \"security.saml.idp.entityid\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML IDP entity id for manually setting the endpoint address of the IDP, instead of getting \"\n\t\t\t\t\t+ \"it from the provided metadata URL.\")\n\tpublic String samlIDPEntityId() {\n\t\treturn getConfigParam(\"security.saml.idp.entityid\", \"\");\n\t}\n\n\t@Documented(position = 1170,\n\t\t\tidentifier = \"security.saml.idp.single_sign_on_service.url\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML SSO service URL of the IDP.\")\n\tpublic String samlIDPSingleSignOnServiceUrl() {\n\t\treturn getConfigParam(\"security.saml.idp.single_sign_on_service.url\", \"\");\n\t}\n\n\t@Documented(position = 1180,\n\t\t\tidentifier = \"security.saml.idp.x509cert\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML server x509 certificate for the IDP (public key). **Value must be Base64-encoded**.\")\n\tpublic String samlIDPX509Certificate() {\n\t\treturn getConfigParam(\"security.saml.idp.x509cert\", \"\");\n\t}\n\n\t@Documented(position = 1190,\n\t\t\tidentifier = \"security.saml.security.authnrequest_signed\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable SAML authentication request signing.\")\n\tpublic boolean samlAuthnRequestSigningEnabled() {\n\t\treturn getConfigBoolean(\"security.saml.security.authnrequest_signed\", false);\n\t}\n\n\t@Documented(position = 1200,\n\t\t\tidentifier = \"security.saml.security.want_messages_signed\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable SAML message signing.\")\n\tpublic boolean samlMessageSigningEnabled() {\n\t\treturn getConfigBoolean(\"security.saml.security.want_messages_signed\", false);\n\t}\n\n\t@Documented(position = 1210,\n\t\t\tidentifier = \"security.saml.security.want_assertions_signed\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable SAML assertion signing.\")\n\tpublic boolean samlAssertionSigningEnabled() {\n\t\treturn getConfigBoolean(\"security.saml.security.want_assertions_signed\", false);\n\t}\n\n\t@Documented(position = 1220,\n\t\t\tidentifier = \"security.saml.security.want_assertions_encrypted\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable SAML assertion encryption.\")\n\tpublic boolean samlAssertionEncryptionEnabled() {\n\t\treturn getConfigBoolean(\"security.saml.security.want_assertions_encrypted\", false);\n\t}\n\n\t@Documented(position = 1230,\n\t\t\tidentifier = \"security.saml.security.want_nameid_encrypted\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable SAML name id encryption.\")\n\tpublic boolean samlNameidEncryptionEnabled() {\n\t\treturn getConfigBoolean(\"security.saml.security.want_nameid_encrypted\", false);\n\t}\n\n\t@Documented(position = 1240,\n\t\t\tidentifier = \"security.saml.security.sign_metadata\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable SAML metadata signing.\")\n\tpublic boolean samlMetadataSigningEnabled() {\n\t\treturn getConfigBoolean(\"security.saml.security.sign_metadata\", false);\n\t}\n\n\t@Documented(position = 1250,\n\t\t\tidentifier = \"security.saml.security.want_xml_validation\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable SAML XML validation.\")\n\tpublic boolean samlXMLValidationEnabled() {\n\t\treturn getConfigBoolean(\"security.saml.security.want_xml_validation\", true);\n\t}\n\n\t@Documented(position = 1260,\n\t\t\tidentifier = \"security.saml.security.signature_algorithm\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML signature algorithm.\")\n\tpublic String samlSignatureAlgorithm() {\n\t\treturn getConfigParam(\"security.saml.security.signature_algorithm\", \"\");\n\t}\n\n\t@Documented(position = 1270,\n\t\t\tidentifier = \"security.saml.domain\",\n\t\t\tvalue = \"paraio.com\",\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"SAML domain name.\")\n\tpublic String samlDomain() {\n\t\treturn getConfigParam(\"security.saml.domain\", \"paraio.com\");\n\t}\n\n\t@Documented(position = 1280,\n\t\t\tidentifier = \"security.saml.is_local\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SAML Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable local handling of SAML requests, instead of sending those to Para.\")\n\tpublic boolean samlIsLocal() {\n\t\treturn getConfigBoolean(\"security.saml.is_local\", false);\n\t}\n\n\t/* **************************************************************************************************************\n\t * OAuth 2.0 authentication OAuth 2.0 authentication *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 1290,\n\t\t\tidentifier = \"oa2_app_id\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 client app identifier. Alternatives: `oa2second_app_id`, `oa2third_app_id`\")\n\tpublic String oauthAppId(String a) {\n\t\treturn getConfigParam(\"oa2\" + a + \"_app_id\", \"\");\n\t}\n\n\t@Documented(position = 1300,\n\t\t\tidentifier = \"oa2_secret\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 client app secret key. Alternatives: `oa2second_secret`, `oa2third_secret`\")\n\tpublic String oauthSecret(String a) {\n\t\treturn getConfigParam(\"oa2\" + a + \"_secret\", \"\");\n\t}\n\n\t@Documented(position = 1310,\n\t\t\tidentifier = \"security.oauth.authz_url\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 client app authorization URL (login page). Alternatives: \"\n\t\t\t\t\t+ \"`security.oauthsecond.authz_url`, `security.oauththird.authz_url`\")\n\tpublic String oauthAuthorizationUrl(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".authz_url\", \"\");\n\t}\n\n\t@Documented(position = 1320,\n\t\t\tidentifier = \"security.oauth.token_url\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 client app token endpoint URL. Alternatives: `security.oauthsecond.token_url`, \"\n\t\t\t\t\t+ \"`security.oauththird.token_url`\")\n\tpublic String oauthTokenUrl(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".token_url\", \"\");\n\t}\n\n\t@Documented(position = 1330,\n\t\t\tidentifier = \"security.oauth.profile_url\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 client app user info endpoint URL. Alternatives: `security.oauthsecond.profile_url`, \"\n\t\t\t\t\t+ \"`security.oauththird.profile_url`\")\n\tpublic String oauthProfileUrl(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".profile_url\", \"\");\n\t}\n\n\t@Documented(position = 1340,\n\t\t\tidentifier = \"security.oauth.scope\",\n\t\t\tvalue = \"openid email profile\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 client app scope. Alternatives: `security.oauthsecond.scope`, \"\n\t\t\t\t\t+ \"`security.oauththird.scope`\")\n\tpublic String oauthScope(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".scope\", \"openid email profile\");\n\t}\n\n\t@Documented(position = 1350,\n\t\t\tidentifier = \"security.oauth.accept_header\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 `Accept` header customization. Alternatives: `security.oauthsecond.accept_header`, \"\n\t\t\t\t\t+ \"`security.oauththird.accept_header`\")\n\tpublic String oauthAcceptHeader(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".accept_header\", \"\");\n\t}\n\n\t@Documented(position = 1360,\n\t\t\tidentifier = \"security.oauth.parameters.id\",\n\t\t\tvalue = \"sub\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 attribute mapping for `id`. Alternatives: `security.oauthsecond.parameters.id`, \"\n\t\t\t\t\t+ \"`security.oauththird.parameters.id`\")\n\tpublic String oauthIdParameter(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".parameters.id\", null);\n\t}\n\n\t@Documented(position = 1370,\n\t\t\tidentifier = \"security.oauth.parameters.name\",\n\t\t\tvalue = \"name\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 attribute mapping for `name`. Alternatives: `security.oauthsecond.parameters.name`, \"\n\t\t\t\t\t+ \"`security.oauththird.parameters.name`\")\n\tpublic String oauthNameParameter(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".parameters.name\", null);\n\t}\n\n\t@Documented(position = 1380,\n\t\t\tidentifier = \"security.oauth.parameters.given_name\",\n\t\t\tvalue = \"given_name\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 attribute mapping for `given_name`. Alternatives: \"\n\t\t\t\t\t+ \"`security.oauthsecond.parameters.given_name`, `security.oauththird.parameters.given_name`\")\n\tpublic String oauthGivenNameParameter(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".parameters.given_name\", null);\n\t}\n\n\t@Documented(position = 1390,\n\t\t\tidentifier = \"security.oauth.parameters.family_name\",\n\t\t\tvalue = \"family_name\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 attribute mapping for `family_name`. Alternatives: \"\n\t\t\t\t\t+ \"`security.oauthsecond.parameters.family_name`, `security.oauththird.parameters.family_name`\")\n\tpublic String oauthFamiliNameParameter(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".parameters.family_name\", null);\n\t}\n\n\t@Documented(position = 1400,\n\t\t\tidentifier = \"security.oauth.parameters.email\",\n\t\t\tvalue = \"email\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 attribute mapping for `email`. Alternatives: `security.oauthsecond.parameters.email`, \"\n\t\t\t\t\t+ \"`security.oauththird.parameters.email`\")\n\tpublic String oauthEmailParameter(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".parameters.email\", null);\n\t}\n\n\t@Documented(position = 1410,\n\t\t\tidentifier = \"security.oauth.parameters.picture\",\n\t\t\tvalue = \"picture\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 attribute mapping for `picture`. Alternatives: `security.oauthsecond.parameters.picture`, \"\n\t\t\t\t\t+ \"`security.oauththird.parameters.picture`\")\n\tpublic String oauthPictureParameter(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".parameters.picture\", null);\n\t}\n\n\t@Documented(position = 1420,\n\t\t\tidentifier = \"security.oauth.download_avatars\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"Enable/disable OAauth 2.0 avatar downloading to local disk. Used when avatars are large in size. \"\n\t\t\t\t\t+ \"Alternatives: `security.oauthsecond.download_avatars`, `security.oauththird.download_avatars`\")\n\tpublic boolean oauthAvatarDownloadingEnabled(String a) {\n\t\treturn getConfigBoolean(\"security.oauth\" + a + \".download_avatars\", false);\n\t}\n\n\t@Documented(position = 1430,\n\t\t\tidentifier = \"security.oauth.token_delegation_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable OAauth 2.0 token delegation. The ID and access tokens will be saved and \"\n\t\t\t\t\t+ \"delegated to Scoold from Para. Alternatives: `security.oauthsecond.token_delegation_enabled`, \"\n\t\t\t\t\t+ \"`security.oauththird.token_delegation_enabled`\")\n\tpublic boolean oauthTokenDelegationEnabled(String a) {\n\t\treturn getConfigBoolean(\"security.oauth\" + a + \".token_delegation_enabled\", false);\n\t}\n\n\t@Documented(position = 1440,\n\t\t\tidentifier = \"security.oauth.spaces_attribute_name\",\n\t\t\tvalue = \"spaces\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"OAauth 2.0 attribute mapping for users' `spaces`. The spaces can be comma-separated. \"\n\t\t\t\t\t+ \"Alternatives: `security.oauthsecond.spaces_attribute_name`, \"\n\t\t\t\t\t+ \"`security.oauththird.spaces_attribute_name`\")\n\tpublic String oauthSpacesAttributeName(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".spaces_attribute_name\", \"spaces\");\n\t}\n\n\t@Documented(position = 1450,\n\t\t\tidentifier = \"security.oauth.groups_attribute_name\",\n\t\t\tvalue = \"roles\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"OAauth 2.0 attribute mapping for users' `groups`. \"\n\t\t\t\t\t+ \"Alternatives: `security.oauthsecond.groups_attribute_name`, \"\n\t\t\t\t\t+ \"`security.oauththird.groups_attribute_name`\")\n\tpublic String oauthGroupsAttributeName(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".groups_attribute_name\", \"roles\");\n\t}\n\n\t@Documented(position = 1460,\n\t\t\tidentifier = \"security.oauth.mods_equivalent_claim_value\",\n\t\t\tvalue = \"mod\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"OAauth 2.0 claim used for mapping OAuth2 users having it, \"\n\t\t\t\t\t+ \"to moderators on Scoold. Alternatives: `security.oauthsecond.mods_equivalent_claim_value`, \"\n\t\t\t\t\t+ \"`security.oauththird.mods_equivalent_claim_value`\")\n\tpublic String oauthModeratorsEquivalentClaim(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".mods_equivalent_claim_value\", \"mod\");\n\t}\n\n\t@Documented(position = 1470,\n\t\t\tidentifier = \"security.oauth.admins_equivalent_claim_value\",\n\t\t\tvalue = \"admin\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"OAauth 2.0 claim used for mapping OAuth2 users having it, \"\n\t\t\t\t\t+ \"to administrators on Scoold. Alternatives: `security.oauthsecond.admins_equivalent_claim_value`, \"\n\t\t\t\t\t+ \"`security.oauththird.admins_equivalent_claim_value`\")\n\tpublic String oauthAdministratorsEquivalentClaim(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".admins_equivalent_claim_value\", \"admin\");\n\t}\n\n\t@Documented(position = 1480,\n\t\t\tidentifier = \"security.oauth.users_equivalent_claim_value\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"OAauth 2.0 claim used for **denying access** to OAuth2 users **not** having it. \"\n\t\t\t\t\t+ \"Alternatives: `security.oauthsecond.users_equivalent_claim_value`, \"\n\t\t\t\t\t+ \"`security.oauththird.users_equivalent_claim_value`\")\n\tpublic String oauthUsersEquivalentClaim(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".users_equivalent_claim_value\", \"\");\n\t}\n\n\t@Documented(position = 1490,\n\t\t\tidentifier = \"security.oauth.domain\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"OAauth 2.0 domain name for constructing user email addresses in case they are missing. \"\n\t\t\t\t\t+ \"Alternatives: `security.oauthsecond.domain`, `security.oauththird.domain`\")\n\tpublic String oauthDomain(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".domain\", null);\n\t}\n\n\t@Documented(position = 1500,\n\t\t\tidentifier = \"security.oauth.provider\",\n\t\t\tvalue = \"Continue with OpenID Connect\",\n\t\t\tcategory = \"OAuth 2.0 Authentication\",\n\t\t\tdescription = \"The text on the button for signing in with OAuth2 or OIDC.\")\n\tpublic String oauthProvider(String a) {\n\t\treturn getConfigParam(\"security.oauth\" + a + \".provider\", \"Continue with \" + a + \"OpenID Connect\");\n\t}\n\n\t/* **************************************************************************************************************\n\t * Posts Posts *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 1510,\n\t\t\tidentifier = \"new_users_can_comment\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"Enable/disable the ability for users with reputation below 100 to comments on posts.\")\n\tpublic boolean newUsersCanComment() {\n\t\treturn getConfigBoolean(\"new_users_can_comment\", true);\n\t}\n\n\t@Documented(position = 1520,\n\t\t\tidentifier = \"posts_need_approval\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"Enable/disable the need for approval of new posts by a moderator. \")\n\tpublic boolean postsNeedApproval() {\n\t\treturn getConfigBoolean(\"posts_need_approval\", false);\n\t}\n\n\t@Documented(position = 1530,\n\t\t\tidentifier = \"wiki_answers_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Posts\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for users to create wiki-style answers, editable by everyone.\")\n\tpublic boolean wikiAnswersEnabled() {\n\t\treturn getConfigBoolean(\"wiki_answers_enabled\", true);\n\t}\n\n\t@Documented(position = 1540,\n\t\t\tidentifier = \"media_recording_allowed\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Posts\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable support for attaching recorded videos and voice messages to posts.\")\n\tpublic boolean mediaRecordingAllowed() {\n\t\treturn getConfigBoolean(\"media_recording_allowed\", true);\n\t}\n\n\t@Documented(position = 1550,\n\t\t\tidentifier = \"delete_protection_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"Enable/disable the ability for authors to delete their own question, when it already has \"\n\t\t\t\t\t+ \"answers and activity.\")\n\tpublic boolean deleteProtectionEnabled() {\n\t\treturn getConfigBoolean(\"delete_protection_enabled\", true);\n\t}\n\n\t@Documented(position = 1560,\n\t\t\tidentifier = \"max_text_length\",\n\t\t\tvalue = \"20000\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"The maximum text length of each post (question or answer). Longer content will be truncated.\")\n\tpublic int maxPostLength() {\n\t\treturn getConfigInt(\"max_post_length\", 20000);\n\t}\n\n\t@Documented(position = 1570,\n\t\t\tidentifier = \"max_tags_per_post\",\n\t\t\tvalue = \"5\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"The maximum number of tags a question can have. The minimum is 0 - then the default tag is used.\")\n\tpublic int maxTagsPerPost() {\n\t\treturn getConfigInt(\"max_tags_per_post\", 5);\n\t}\n\n\t@Documented(position = 1580,\n\t\t\tidentifier = \"max_replies_per_post\",\n\t\t\tvalue = \"500\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"The maximum number of answers a question can have.\")\n\tpublic int maxRepliesPerPost() {\n\t\treturn getConfigInt(\"max_replies_per_post\", 500);\n\t}\n\n\t@Documented(position = 1590,\n\t\t\tidentifier = \"max_comments_per_id\",\n\t\t\tvalue = \"1000\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"The maximum number of comments a post can have.\")\n\tpublic int maxCommentsPerPost() {\n\t\treturn getConfigInt(\"max_comments_per_id\", 1000);\n\t}\n\n\t@Documented(position = 1600,\n\t\t\tidentifier = \"max_comment_length\",\n\t\t\tvalue = \"600\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"The maximum length of each comment.\")\n\tpublic int maxCommentLength() {\n\t\treturn getConfigInt(\"max_comment_length\", 600);\n\t}\n\n\t@Documented(position = 1610,\n\t\t\tidentifier = \"max_mentions_in_posts\",\n\t\t\tvalue = \"10\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Posts\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"The maximum number of mentioned users a post can have.\")\n\tpublic int maxMentionsInPosts() {\n\t\treturn getConfigInt(\"max_mentions_in_posts\", 10);\n\t}\n\n\t@Documented(position = 1620,\n\t\t\tidentifier = \"anonymous_posts_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Posts\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for unathenticated users to create new questions.\")\n\tpublic boolean anonymousPostsEnabled() {\n\t\treturn getConfigBoolean(\"anonymous_posts_enabled\", false);\n\t}\n\n\t@Documented(position = 1630,\n\t\t\tidentifier = \"nearme_feature_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"Enable/disable the ability for users to attach geolocation data to questions and \"\n\t\t\t\t\t+ \"location-based filtering of questions.\")\n\tpublic boolean postsNearMeEnabled() {\n\t\treturn getConfigBoolean(\"nearme_feature_enabled\", !googleMapsApiKey().isEmpty());\n\t}\n\n\t@Documented(position = 1640,\n\t\t\tidentifier = \"merge_question_bodies\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"Enable/disable the merging of question bodies when two questions are merged into one.\")\n\tpublic boolean mergeQuestionBodies() {\n\t\treturn getConfigBoolean(\"merge_question_bodies\", true);\n\t}\n\n\t@Documented(position = 1650,\n\t\t\tidentifier = \"max_similar_posts\",\n\t\t\tvalue = \"7\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"The maximum number of similar posts which will be displayed on the side.\")\n\tpublic int maxSimilarPosts() {\n\t\treturn getConfigInt(\"max_similar_posts\", 7);\n\t}\n\n\t@Documented(position = 1660,\n\t\t\tidentifier = \"default_question_tag\",\n\t\t\tvalue = \"question\",\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"The default question tag, used when no other tags are provided by its author.\")\n\tpublic String defaultQuestionTag() {\n\t\treturn getConfigParam(\"default_question_tag\", \"\");\n\t}\n\n\t@Documented(position = 1670,\n\t\t\tidentifier = \"posts_rep_threshold\",\n\t\t\tvalue = \"100\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"The minimum reputation an author needs to create a post without approval by moderators. \"\n\t\t\t\t\t+ \"This is only required if new posts need apporval.\")\n\tpublic int postsReputationThreshold() {\n\t\treturn getConfigInt(\"posts_rep_threshold\", enthusiastIfHasRep());\n\t}\n\n\t/* **************************************************************************************************************\n\t * Spaces Spaces *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 1680,\n\t\t\tidentifier = \"auto_assign_spaces\",\n\t\t\tcategory = \"Spaces\",\n\t\t\tdescription = \"A comma-separated list of spaces to assign to all new users.\")\n\tpublic String autoAssignSpaces() {\n\t\treturn getConfigParam(\"auto_assign_spaces\", \"\");\n\t}\n\n\t@Documented(position = 1690,\n\t\t\tidentifier = \"reset_spaces_on_new_assignment\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Spaces\",\n\t\t\tdescription = \"Spaces delegated from identity providers will overwrite the existing ones for users.\")\n\tpublic boolean resetSpacesOnNewAssignment(boolean def) {\n\t\treturn getConfigBoolean(\"reset_spaces_on_new_assignment\", def);\n\t}\n\n\t/* **************************************************************************************************************\n\t * Reputation and Rewards Reputation and Rewards *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 1700,\n\t\t\tidentifier = \"answer_voteup_reward_author\",\n\t\t\tvalue = \"10\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points given to author of answer as reward when a user upvotes it.\")\n\tpublic int answerVoteupRewardAuthor() {\n\t\treturn getConfigInt(\"answer_voteup_reward_author\", 10);\n\t}\n\n\t@Documented(position = 1710,\n\t\t\tidentifier = \"question_voteup_reward_author\",\n\t\t\tvalue = \"5\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points given to author of question as reward when a user upvotes it.\")\n\tpublic int questionVoteupRewardAuthor() {\n\t\treturn getConfigInt(\"question_voteup_reward_author\", 5);\n\t}\n\n\t@Documented(position = 1720,\n\t\t\tidentifier = \"voteup_reward_author\",\n\t\t\tvalue = \"2\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points given to author of comment or other post as reward when a user upvotes it.\")\n\tpublic int voteupRewardAuthor() {\n\t\treturn getConfigInt(\"voteup_reward_author\", 2);\n\t}\n\n\t@Documented(position = 1730,\n\t\t\tidentifier = \"answer_approve_reward_author\",\n\t\t\tvalue = \"10\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points given to author of answer as reward when the question's author accepts it.\")\n\tpublic int answerApprovedRewardAuthor() {\n\t\treturn getConfigInt(\"answer_approve_reward_author\", 10);\n\t}\n\n\t@Documented(position = 1740,\n\t\t\tidentifier = \"answer_approve_reward_voter\",\n\t\t\tvalue = \"3\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points given to author of question who accepted an answer.\")\n\tpublic int answerApprovedRewardVoter() {\n\t\treturn getConfigInt(\"answer_approve_reward_voter\", 3);\n\t}\n\n\t@Documented(position = 1750,\n\t\t\tidentifier = \"post_votedown_penalty_author\",\n\t\t\tvalue = \"3\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points taken from author of post as penalty when their post was downvoted.\")\n\tpublic int postVotedownPenaltyAuthor() {\n\t\treturn getConfigInt(\"post_votedown_penalty_author\", 3);\n\t}\n\n\t@Documented(position = 1760,\n\t\t\tidentifier = \"post_votedown_penalty_voter\",\n\t\t\tvalue = \"1\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points taken from the user who downvotes any content. Discourages downvoting slightly.\")\n\tpublic int postVotedownPenaltyVoter() {\n\t\treturn getConfigInt(\"post_votedown_penalty_voter\", 1);\n\t}\n\n\t@Documented(position = 1770,\n\t\t\tidentifier = \"voter_ifhas\",\n\t\t\tvalue = \"100\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Number of votes (up or down) needed from a user for earning the `voter` badge.\")\n\tpublic int voterIfHasRep() {\n\t\treturn getConfigInt(\"voter_ifhas\", 100);\n\t}\n\n\t@Documented(position = 1780,\n\t\t\tidentifier = \"commentator_ifhas\",\n\t\t\tvalue = \"100\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Number of comments a user needs to have posted for earning the `commentator` badge.\")\n\tpublic int commentatorIfHasRep() {\n\t\treturn getConfigInt(\"commentator_ifhas\", 100);\n\t}\n\n\t@Documented(position = 1790,\n\t\t\tidentifier = \"critic_ifhas\",\n\t\t\tvalue = \"10\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Number of cast downvotes needed from a user for earning the `critic` badge.\")\n\tpublic int criticIfHasRep() {\n\t\treturn getConfigInt(\"critic_ifhas\", 10);\n\t}\n\n\t@Documented(position = 1800,\n\t\t\tidentifier = \"supporter_ifhas\",\n\t\t\tvalue = \"50\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Number of cast upvotes needed from a user for earning the `supporter` badge`.\")\n\tpublic int supporterIfHasRep() {\n\t\treturn getConfigInt(\"supporter_ifhas\", 50);\n\t}\n\n\t@Documented(position = 1810,\n\t\t\tidentifier = \"goodquestion_ifhas\",\n\t\t\tvalue = \"20\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Votes needed on a question before its author gets to earn the `good question` badge.\")\n\tpublic int goodQuestionIfHasRep() {\n\t\treturn getConfigInt(\"goodquestion_ifhas\", 20);\n\t}\n\n\t@Documented(position = 1820,\n\t\t\tidentifier = \"goodanswer_ifhas\",\n\t\t\tvalue = \"10\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Votes needed on an answer before its author gets to earn the `good answer` badge.\")\n\tpublic int goodAnswerIfHasRep() {\n\t\treturn getConfigInt(\"goodanswer_ifhas\", 10);\n\t}\n\n\t@Documented(position = 1830,\n\t\t\tidentifier = \"enthusiast_ifhas\",\n\t\t\tvalue = \"100\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points needed for earning the `enthusiast` badge.\")\n\tpublic int enthusiastIfHasRep() {\n\t\treturn getConfigInt(\"enthusiast_ifhas\", 100);\n\t}\n\n\t@Documented(position = 1840,\n\t\t\tidentifier = \"freshman_ifhas\",\n\t\t\tvalue = \"300\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points needed for earning the `freshman` badge.\")\n\tpublic int freshmanIfHasRep() {\n\t\treturn getConfigInt(\"freshman_ifhas\", 300);\n\t}\n\n\t@Documented(position = 1850,\n\t\t\tidentifier = \"scholar_ifhas\",\n\t\t\tvalue = \"500\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points needed for earning the `scholar` badge.\")\n\tpublic int scholarIfHasRep() {\n\t\treturn getConfigInt(\"scholar_ifhas\", 500);\n\t}\n\n\t@Documented(position = 1860,\n\t\t\tidentifier = \"teacher_ifhas\",\n\t\t\tvalue = \"1000\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points needed for earning the `teacher` badge.\")\n\tpublic int teacherIfHasRep() {\n\t\treturn getConfigInt(\"teacher_ifhas\", 1000);\n\t}\n\n\t@Documented(position = 1870,\n\t\t\tidentifier = \"\",\n\t\t\tvalue = \"5000\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points needed for earning the `professor` badge.\")\n\tpublic int professorIfHasRep() {\n\t\treturn getConfigInt(\"professor_ifhas\", 5000);\n\t}\n\n\t@Documented(position = 1880,\n\t\t\tidentifier = \"geek_ifhas\",\n\t\t\tvalue = \"9000\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Reputation and Rewards\",\n\t\t\tdescription = \"Reputation points needed for earning the `geek` badge.\")\n\tpublic int geekIfHasRep() {\n\t\treturn getConfigInt(\"geek_ifhas\", 9000);\n\t}\n\n\t/* **************************************************************************************************************\n\t * File Storage File Storage *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 1890,\n\t\t\tidentifier = \"uploads_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable file uploads.\")\n\tpublic boolean uploadsEnabled() {\n\t\treturn getConfigBoolean(\"uploads_enabled\", true);\n\t}\n\n\t@Documented(position = 1900,\n\t\t\tidentifier = \"file_uploads_dir\",\n\t\t\tvalue = \"uploads\",\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"The directory (local or in the cloud) where files will be stored.\")\n\tpublic String fileUploadsDirectory() {\n\t\treturn getConfigParam(\"file_uploads_dir\", \"uploads\");\n\t}\n\n\t@Documented(position = 1910,\n\t\t\tidentifier = \"uploads_require_auth\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the requirement that uploaded files can only be accessed by authenticated users.\")\n\tpublic boolean uploadsRequireAuthentication() {\n\t\treturn getConfigBoolean(\"uploads_require_auth\", !isDefaultSpacePublic());\n\t}\n\n\t@Documented(position = 1920,\n\t\t\tidentifier = \"allowed_upload_formats\",\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"A comma-separated list of allowed MIME types in the format `extension:mime_type`, e.g.\"\n\t\t\t\t\t+ \"`py:text/plain` or just the extensions `py,yml`\")\n\tpublic String allowedUploadFormats() {\n\t\treturn getConfigParam(\"allowed_upload_formats\", \"\");\n\t}\n\n\t@Documented(position = 1930,\n\t\t\tidentifier = \"s3_bucket\",\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"AWS S3 bucket name as target for storing files.\")\n\tpublic String s3Bucket() {\n\t\treturn getConfigParam(\"s3_bucket\", \"\");\n\t}\n\n\t@Documented(position = 1940,\n\t\t\tidentifier = \"s3_path\",\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"AWS S3 object prefix (directory) inside the bucket.\")\n\tpublic String s3Path() {\n\t\treturn getConfigParam(\"s3_path\", \"uploads\");\n\t}\n\n\t@Documented(position = 1950,\n\t\t\tidentifier = \"s3_region\",\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"AWS S3 region.\")\n\tpublic String s3Region() {\n\t\treturn getConfigParam(\"s3_region\", \"\");\n\t}\n\n\t@Documented(position = 1960,\n\t\t\tidentifier = \"s3_access_key\",\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"AWS S3 access key.\")\n\tpublic String s3AccessKey() {\n\t\treturn getConfigParam(\"s3_access_key\", \"\");\n\t}\n\n\t@Documented(position = 1970,\n\t\t\tidentifier = \"s3_secret_key\",\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"AWS S3 secret key.\")\n\tpublic String s3SecretKey() {\n\t\treturn getConfigParam(\"s3_secret_key\", \"\");\n\t}\n\n\t@Documented(position = 1980,\n\t\t\tidentifier = \"blob_storage_account\",\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Azure Blob Storage account ID.\")\n\tpublic String azureStorageAccount() {\n\t\treturn getConfigParam(\"blob_storage_account\", \"\");\n\t}\n\n\t@Documented(position = 1990,\n\t\t\tidentifier = \"blob_storage_token\",\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Azure Blob Storage token.\")\n\tpublic String azureStorageToken() {\n\t\treturn getConfigParam(\"blob_storage_token\", \"\");\n\t}\n\n\t@Documented(position = 2000,\n\t\t\tidentifier = \"blob_storage_container\",\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Azure Blob Storage container.\")\n\tpublic String azureStorageContainer() {\n\t\treturn getConfigParam(\"blob_storage_container\", \"\");\n\t}\n\n\t@Documented(position = 2010,\n\t\t\tidentifier = \"blob_storage_path\",\n\t\t\tcategory = \"File Storage\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Azure Blob Storage path prefix (subfolder) within a container.\")\n\tpublic String azureStoragePath() {\n\t\treturn getConfigParam(\"blob_storage_path\", \"uploads\");\n\t}\n\n\t/* **************************************************************************************************************\n\t * Customization Customization *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 2020,\n\t\t\tidentifier = \"default_language_code\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The default language code to use for the site. Set this to make the site load a \"\n\t\t\t\t\t+ \"different language from English.\")\n\tpublic String defaultLanguageCode() {\n\t\treturn getConfigParam(\"default_language_code\", \"\");\n\t}\n\n\t@Documented(position = 2030,\n\t\t\tidentifier = \"welcome_message\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Adds a brief intro text inside a banner at the top of the main page for new visitors to see.\")\n\tpublic String welcomeMessage() {\n\t\treturn getConfigParam(\"welcome_message\", \"\");\n\t}\n\n\t@Documented(position = 2040,\n\t\t\tidentifier = \"welcome_message_onlogin\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Adds a brief intro text inside a banner at the top of the 'Sign in' page only.\")\n\tpublic String welcomeMessageOnLogin() {\n\t\treturn getConfigParam(\"welcome_message_onlogin\", \"\");\n\t}\n\n\t@Documented(position = 2050,\n\t\t\tidentifier = \"dark_mode_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable the option for users to switch to the dark theme.\")\n\tpublic boolean darkModeEnabled() {\n\t\treturn getConfigBoolean(\"dark_mode_enabled\", true);\n\t}\n\n\t@Documented(position = 2060,\n\t\t\tidentifier = \"meta_description\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The content inside the description `<meta>` tag.\")\n\tpublic String metaDescription() {\n\t\treturn getConfigParam(\"meta_description\", \"\");\n\t}\n\n\t@Documented(position = 2070,\n\t\t\tidentifier = \"meta_keywords\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The content inside the keywords `<meta>` tag.\")\n\tpublic String metaKeywords() {\n\t\treturn getConfigParam(\"meta_keywords\", \"\");\n\t}\n\n\t@Documented(position = 2080,\n\t\t\tidentifier = \"show_branding\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable the 'Powered by Scoold' branding in the footer.\")\n\tpublic boolean scooldBrandingEnabled() {\n\t\treturn getConfigBoolean(\"show_branding\", true);\n\t}\n\n\t@Documented(position = 2090,\n\t\t\tidentifier = \"mathjax_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable support for MathJax and LaTeX for scientific expressions in Markdown.\")\n\tpublic boolean mathjaxEnabled() {\n\t\treturn getConfigBoolean(\"mathjax_enabled\", false);\n\t}\n\n\t@Documented(position = 2100,\n\t\t\tidentifier = \"gravatars_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable support for Gravatars.\")\n\tpublic boolean gravatarsEnabled() {\n\t\treturn getConfigBoolean(\"gravatars_enabled\", true);\n\t}\n\n\t@Documented(position = 2110,\n\t\t\tidentifier = \"gravatars_pattern\",\n\t\t\tvalue = \"retro\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The pattern to use when displaying empty/anonymous gravatar pictures.\")\n\tpublic String gravatarsPattern() {\n\t\treturn getConfigParam(\"gravatars_pattern\", \"retro\");\n\t}\n\n\t@Documented(position = 2120,\n\t\t\tidentifier = \"avatar_repository\",\n\t\t\tcategory = \"Customization\",\n\t\t\ttags = {\"preview\"},\n\t\t\tdescription = \"The avatar repository - one of `imgur`, `cloudinary`.\")\n\tpublic String avatarRepository() {\n\t\treturn getConfigParam(\"avatar_repository\", \"\");\n\t}\n\n\t@Documented(position = 2130,\n\t\t\tidentifier = \"footer_html\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Some custom HTML content to be added to the website footer.\")\n\tpublic String footerHtml() {\n\t\treturn getConfigParam(\"footer_html\", \"\");\n\t}\n\n\t@Documented(position = 2140,\n\t\t\tidentifier = \"navbar_link1_url\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The URL of an extra custom link which will be added to the top navbar.\")\n\tpublic String navbarCustomLink1Url() {\n\t\treturn getConfigParam(\"navbar_link1_url\", \"\");\n\t}\n\n\t@Documented(position = 2150,\n\t\t\tidentifier = \"navbar_link1_text\",\n\t\t\tvalue = \"Link1\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The title of an extra custom link which will be added to the top navbar.\")\n\tpublic String navbarCustomLink1Text() {\n\t\treturn getConfigParam(\"navbar_link1_text\", \"Link1\");\n\t}\n\n\t@Documented(position = 2160,\n\t\t\tidentifier = \"navbar_link2_url\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The URL of an extra custom link which will be added to the top navbar.\")\n\tpublic String navbarCustomLink2Url() {\n\t\treturn getConfigParam(\"navbar_link2_url\", \"\");\n\t}\n\n\t@Documented(position = 2170,\n\t\t\tidentifier = \"navbar_link2_text\",\n\t\t\tvalue = \"Link2\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The title of an extra custom link which will be added to the top navbar.\")\n\tpublic String navbarCustomLink2Text() {\n\t\treturn getConfigParam(\"navbar_link2_text\", \"Link2\");\n\t}\n\n\t@Documented(position = 2180,\n\t\t\tidentifier = \"navbar_menu_link1_url\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The URL of an extra custom link which will be added to user's dropdown menu.\"\n\t\t\t\t\t+ \" Only shown to authenticated users.\")\n\tpublic String navbarCustomMenuLink1Url() {\n\t\treturn getConfigParam(\"navbar_menu_link1_url\", \"\");\n\t}\n\n\t@Documented(position = 2190,\n\t\t\tidentifier = \"navbar_menu_link1_text\",\n\t\t\tvalue = \"Menu Link1\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The title of an extra custom link which will be added to the user's dropdown menu.\")\n\tpublic String navbarCustomMenuLink1Text() {\n\t\treturn getConfigParam(\"navbar_menu_link1_text\", \"Menu Link1\");\n\t}\n\n\t@Documented(position = 2200,\n\t\t\tidentifier = \"navbar_menu_link2_url\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The URL of an extra custom link which will be added to user's dropdown menu.\"\n\t\t\t\t\t+ \" Only shown to authenticated users.\")\n\tpublic String navbarCustomMenuLink2Url() {\n\t\treturn getConfigParam(\"navbar_menu_link2_url\", \"\");\n\t}\n\n\t@Documented(position = 2210,\n\t\t\tidentifier = \"navbar_menu_link2_text\",\n\t\t\tvalue = \"Menu Link2\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The title of an extra custom link which will be added to the user's dropdown menu.\")\n\tpublic String navbarCustomMenuLink2Text() {\n\t\treturn getConfigParam(\"navbar_menu_link2_text\", \"Menu Link2\");\n\t}\n\n\t@Documented(position = 2220,\n\t\t\tidentifier = \"always_hide_comment_forms\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable a visual tweak which keeps all comment text editors closed at all times.\")\n\tpublic boolean alwaysHideCommentForms() {\n\t\treturn getConfigBoolean(\"always_hide_comment_forms\", true);\n\t}\n\n\t@Documented(position = 2230,\n\t\t\tidentifier = \"footer_links_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable all links in the website footer.\")\n\tpublic boolean footerLinksEnabled() {\n\t\treturn getConfigBoolean(\"footer_links_enabled\", true);\n\t}\n\n\t@Documented(position = 2240,\n\t\t\tidentifier = \"emails_footer_html\",\n\t\t\tvalue = \"<a href=\\\"{host_url}\\\">{app_name}</a> &bull; <a href=\\\"https://scoold.com\\\">Powered by Scoold</a>\",\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The HTML code snippet to embed at the end of each transactional email message.\")\n\tpublic String emailsFooterHtml() {\n\t\treturn getConfigParam(\"emails_footer_html\", \"<a href=\\\"\" + serverUrl() + \"\\\">\" + appName() + \"</a> &bull; \" +\n\t\t\t\t\"<a href=\\\"https://scoold.com\\\">Powered by Scoold</a>\");\n\t}\n\n\t@Documented(position = 2250,\n\t\t\tidentifier = \"cookie_consent_required\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable the cookie consent popup box and blocks all external JS scripts from loading. \"\n\t\t\t\t\t+ \"Used for compliance with GDPR/CCPA.\")\n\tpublic boolean cookieConsentRequired() {\n\t\treturn getConfigBoolean(\"cookie_consent_required\", false);\n\t}\n\n\t@Documented(position = 2260,\n\t\t\tidentifier = \"fixed_nav\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable a fixed navigation bar.\")\n\tpublic boolean fixedNavEnabled() {\n\t\treturn getConfigBoolean(\"fixed_nav\", false);\n\t}\n\n\t@Documented(position = 2270,\n\t\t\tidentifier = \"logo_width\",\n\t\t\tvalue = \"100\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"The width of the logo image in the nav bar, in pixels. Used for fine adjustments to the logo size.\")\n\tpublic int logoWidth() {\n\t\treturn getConfigInt(\"logo_width\", 100);\n\t}\n\n\t@Documented(position = 2280,\n\t\t\tidentifier = \"code_highlighting_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable support for syntax highlighting in code blocks.\")\n\tpublic boolean codeHighlightingEnabled() {\n\t\treturn getConfigBoolean(\"code_highlighting_enabled\", true);\n\t}\n\n\t@Documented(position = 2290,\n\t\t\tidentifier = \"max_pages\",\n\t\t\tvalue = \"1000\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Maximum number of pages to return as results.\")\n\tpublic int maxPages() {\n\t\treturn getConfigInt(\"max_pages\", 1000);\n\t}\n\n\t@Documented(position = 2300,\n\t\t\tidentifier = \"numeric_pagination_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable the numeric pagination style `(< 1 2 3...N >)`.\")\n\tpublic boolean numericPaginationEnabled() {\n\t\treturn getConfigBoolean(\"numeric_pagination_enabled\", false);\n\t}\n\n\t@Documented(position = 2310,\n\t\t\tidentifier = \"html_in_markdown_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable the ability for users to insert basic HTML tags inside Markdown content.\")\n\tpublic boolean htmlInMarkdownEnabled() {\n\t\treturn getConfigBoolean(\"html_in_markdown_enabled\", false);\n\t}\n\n\t@Documented(position = 2320,\n\t\t\tidentifier = \"max_items_per_page\",\n\t\t\tvalue = \"30\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Maximum number of results to return in a single page of results.\")\n\tpublic int maxItemsPerPage() {\n\t\treturn getConfigInt(\"max_items_per_page\", Para.getConfig().maxItemsPerPage());\n\t}\n\n\t@Documented(position = 2330,\n\t\t\tidentifier = \"avatar_edits_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable the ability for users to edit their profile pictures.\")\n\tpublic boolean avatarEditsEnabled() {\n\t\treturn getConfigBoolean(\"avatar_edits_enabled\", true);\n\t}\n\n\t@Documented(position = 2340,\n\t\t\tidentifier = \"name_edits_enabled\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Customization\",\n\t\t\tdescription = \"Enable/disable the ability for users to edit their name.\")\n\tpublic boolean nameEditsEnabled() {\n\t\treturn getConfigBoolean(\"name_edits_enabled\", true);\n\t}\n\n\t/* **************************************************************************************************************\n\t * Frontend Assets Frontend Assets *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 2350,\n\t\t\tidentifier = \"logo_url\",\n\t\t\tvalue = \"/images/logo.svg\",\n\t\t\tcategory = \"Frontend Assets\",\n\t\t\tdescription = \"The URL of the logo in the nav bar.\")\n\tpublic String logoUrl() {\n\t\treturn getConfigParam(\"logo_url\", imagesLink() + \"/logo.svg\");\n\t}\n\n\t@Documented(position = 2360,\n\t\t\tidentifier = \"small_logo_url\",\n\t\t\tvalue = \"/images/logowhite.png\",\n\t\t\tcategory = \"Frontend Assets\",\n\t\t\tdescription = \"The URL of a smaller logo. Mainly used in transactional emails.\")\n\tpublic String logoSmallUrl() {\n\t\treturn getConfigParam(\"small_logo_url\", serverUrl() + imagesLink() + \"/logowhite.png\");\n\t}\n\n\t@Documented(position = 2370,\n\t\t\tidentifier = \"cdn_url\",\n\t\t\tcategory = \"miscellaneous\",\n\t\t\tdescription = \"A CDN URL where all static assets might be stored.\")\n\tpublic String cdnUrl() {\n\t\treturn StringUtils.stripEnd(getConfigParam(\"cdn_url\", serverContextPath()), \"/\");\n\t}\n\n\t@Documented(position = 2380,\n\t\t\tidentifier = \"stylesheet_url\",\n\t\t\tvalue = \"/styles/style.css\",\n\t\t\tcategory = \"Frontend Assets\",\n\t\t\tdescription = \"A stylesheet URL of a CSS file which will be used as the main stylesheet. *This will overwrite\"\n\t\t\t\t\t+ \" all existing CSS styles!*\")\n\tpublic String stylesheetUrl() {\n\t\treturn getConfigParam(\"stylesheet_url\", stylesLink() + \"/style.css\");\n\t}\n\n\t@Documented(position = 2390,\n\t\t\tidentifier = \"external_styles\",\n\t\t\tcategory = \"Frontend Assets\",\n\t\t\tdescription = \"A comma-separated list of external CSS files. These will be loaded *after* the main stylesheet.\")\n\tpublic String externalStyles() {\n\t\treturn getConfigParam(\"external_styles\", \"\");\n\t}\n\n\t@Documented(position = 2400,\n\t\t\tidentifier = \"external_scripts._id_\",\n\t\t\ttype = Map.class,\n\t\t\tcategory = \"Frontend Assets\",\n\t\t\tdescription = \"A map of external JS scripts. These will be loaded after the main JS script. For example: \"\n\t\t\t\t\t+ \"`scoold.external_scripts.script1 = \\\"alert('Hi')\\\"`\")\n\tpublic Map<String, Object> externalScripts() {\n\t\tif (getConfig().hasPath(\"external_scripts\")) {\n\t\t\tConfigObject extScripts = getConfig().getObject(\"external_scripts\");\n\t\t\tif (extScripts != null && !extScripts.isEmpty()) {\n\t\t\t\treturn new LinkedHashMap<>(extScripts.unwrapped());\n\t\t\t}\n\t\t}\n\t\treturn Collections.emptyMap();\n\t}\n\n\t@Documented(position = 2410,\n\t\t\tidentifier = \"inline_css\",\n\t\t\tcategory = \"Frontend Assets\",\n\t\t\tdescription = \"Some short, custom CSS snippet to embed inside the `<head>` element.\")\n\tpublic String inlineCSS() {\n\t\treturn getConfigParam(\"inline_css\", \"\");\n\t}\n\n\t@Documented(position = 2420,\n\t\t\tidentifier = \"favicon_url\",\n\t\t\tvalue = \"/images/favicon.ico\",\n\t\t\tcategory = \"Frontend Assets\",\n\t\t\tdescription = \"The URL of the favicon image.\")\n\tpublic String faviconUrl() {\n\t\treturn getConfigParam(\"favicon_url\", imagesLink() + \"/favicon.ico\");\n\t}\n\n\t@Documented(position = 2430,\n\t\t\tidentifier = \"meta_app_icon\",\n\t\t\tvalue = \"/images/logowhite.png\",\n\t\t\tcategory = \"Frontend Assets\",\n\t\t\tdescription = \"The URL of the app icon image in the `<meta property='og:image'>` tag.\")\n\tpublic String metaAppIconUrl() {\n\t\treturn getConfigParam(\"meta_app_icon\", imagesLink() + \"/logowhite.png\");\n\t}\n\n\t/* **************************************************************************************************************\n\t * Mattermost Integration Mattermost Integration *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 2440,\n\t\t\tidentifier = \"mattermost.server_url\",\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Mattermost server URL.\")\n\tpublic String mattermostServerUrl() {\n\t\treturn getConfigParam(\"mattermost.server_url\", \"\");\n\t}\n\n\t@Documented(position = 2450,\n\t\t\tidentifier = \"mattermost.bot_username\",\n\t\t\tvalue = \"scoold\",\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Mattermost bot username.\")\n\tpublic String mattermostBotUsername() {\n\t\treturn getConfigParam(\"mattermost.bot_username\", \"scoold\");\n\t}\n\n\t@Documented(position = 2460,\n\t\t\tidentifier = \"mattermost.bot_icon_url\",\n\t\t\tvalue = \"/images/logowhite.png\",\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Mattermost bot avatar URL.\")\n\tpublic String mattermostBotIconUrl() {\n\t\treturn getConfigParam(\"mattermost.bot_icon_url\", serverUrl() + imagesLink() + \"/logowhite.png\");\n\t}\n\n\t@Documented(position = 2470,\n\t\t\tidentifier = \"mattermost.post_to_space\",\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Default space on Scoold where questions created on Mattermost will be published. Set it to \"\n\t\t\t\t\t+ \"`workspace` for using the team's name.\")\n\tpublic String mattermostPostToSpace() {\n\t\treturn getConfigParam(\"mattermost.post_to_space\", \"\");\n\t}\n\n\t@Documented(position = 2480,\n\t\t\tidentifier = \"mattermost.map_channels_to_spaces\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable mapping of Mattermost channels to Scoold spaces. When enabled, will create a \"\n\t\t\t\t\t+ \"Scoold space for each Mattermost channel.\")\n\tpublic boolean mattermostMapChannelsToSpaces() {\n\t\treturn getConfigBoolean(\"mattermost.map_channels_to_spaces\", false);\n\t}\n\n\t@Documented(position = 2490,\n\t\t\tidentifier = \"mattermost.map_workspaces_to_spaces\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable mapping of Mattermost teams to Scoold spaces. When enabled, will create a \"\n\t\t\t\t\t+ \"Scoold space for each Mattermost team.\")\n\tpublic boolean mattermostMapWorkspacesToSpaces() {\n\t\treturn getConfigBoolean(\"mattermost.map_workspaces_to_spaces\", true);\n\t}\n\n\t@Documented(position = 2500,\n\t\t\tidentifier = \"mattermost.max_notification_webhooks\",\n\t\t\tvalue = \"10\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"The maximum number of incoming webhooks which can be created on Scoold. Each webhook links a\"\n\t\t\t\t\t+ \" Mattermost channel to Scoold.\")\n\tpublic int mattermostMaxNotificationWebhooks() {\n\t\treturn getConfigInt(\"mattermost.max_notification_webhooks\", 10);\n\t}\n\n\t@Documented(position = 2510,\n\t\t\tidentifier = \"mattermost.notify_on_new_answer\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send notifications to Mattermost for new answers.\")\n\tpublic boolean mattermostNotifyOnNewAnswer() {\n\t\treturn getConfigBoolean(\"mattermost.notify_on_new_answer\", true);\n\t}\n\n\t@Documented(position = 2520,\n\t\t\tidentifier = \"mattermost.notify_on_new_question\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send notifications to Mattermost for new questions.\")\n\tpublic boolean mattermostNotifyOnNewQuestion() {\n\t\treturn getConfigBoolean(\"mattermost.notify_on_new_question\", true);\n\t}\n\n\t@Documented(position = 2530,\n\t\t\tidentifier = \"mattermost.notify_on_new_comment\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send notifications to Mattermost for new comments.\")\n\tpublic boolean mattermostNotifyOnNewComment() {\n\t\treturn getConfigBoolean(\"mattermost.notify_on_new_comment\", true);\n\t}\n\n\t@Documented(position = 2540,\n\t\t\tidentifier = \"mattermost.dm_on_new_comment\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send direct messages to Mattermost users for new comments.\")\n\tpublic boolean mattermostDmOnNewComment() {\n\t\treturn getConfigBoolean(\"mattermost.dm_on_new_comment\", false);\n\t}\n\n\t@Documented(position = 2550,\n\t\t\tidentifier = \"mattermost.default_question_tags\",\n\t\t\tvalue = \"via-mattermost\",\n\t\t\tcategory = \"Mattermost Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Default question tags for questions created on Mattermost (comma-separated list).\")\n\tpublic String mattermostDefaultQuestionTags() {\n\t\treturn getConfigParam(\"mattermost.default_question_tags\", \"via-mattermost\");\n\t}\n\n\t/* **************************************************************************************************************\n\t * Slack Integration Slack Integration *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 2560,\n\t\t\tidentifier = \"slack.auth_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable authentication with Slack.\")\n\tpublic boolean slackAuthEnabled() {\n\t\treturn getConfigBoolean(\"slack.auth_enabled\", !slackAppId().isEmpty());\n\t}\n\n\t@Documented(position = 2570,\n\t\t\tidentifier = \"slack.app_id\",\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"The Slack app ID (first ID from the app's credentials, not the OAuth2 Client ID).\")\n\tpublic String slackIntegrationAppId() {\n\t\treturn getConfigParam(\"slack.app_id\", \"\");\n\t}\n\n\t@Documented(position = 2580,\n\t\t\tidentifier = \"slack.signing_secret\",\n\t\t\tvalue = \"x\",\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Slack signing secret key for verifying request signatures.\")\n\tpublic String slackSigningSecret() {\n\t\treturn getConfigParam(\"slack.signing_secret\", \"x\");\n\t}\n\n\t@Documented(position = 2590,\n\t\t\tidentifier = \"slack.max_notification_webhooks\",\n\t\t\tvalue = \"10\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"The maximum number of incoming webhooks which can be created on Scoold. Each webhook links a\"\n\t\t\t\t\t+ \" Slack channel to Scoold.\")\n\tpublic int slackMaxNotificationWebhooks() {\n\t\treturn getConfigInt(\"slack.max_notification_webhooks\", 10);\n\t}\n\n\t@Documented(position = 2600,\n\t\t\tidentifier = \"slack.map_channels_to_spaces\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable mapping of Slack channels to Scoold spaces. When enabled, will create a \"\n\t\t\t\t\t+ \"Scoold space for each Slack channel.\")\n\tpublic boolean slackMapChannelsToSpaces() {\n\t\treturn getConfigBoolean(\"slack.map_channels_to_spaces\", false);\n\t}\n\n\t@Documented(position = 2610,\n\t\t\tidentifier = \"slack.map_workspaces_to_spaces\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable mapping of Slack teams to Scoold spaces. When enabled, will create a \"\n\t\t\t\t\t+ \"Scoold space for each Slack team.\")\n\tpublic boolean slackMapWorkspacesToSpaces() {\n\t\treturn getConfigBoolean(\"slack.map_workspaces_to_spaces\", true);\n\t}\n\n\t@Documented(position = 2620,\n\t\t\tidentifier = \"slack.post_to_space\",\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Default space on Scoold where questions created on Slack will be published. Set it to \"\n\t\t\t\t\t+ \"`workspace` for using the team's name.\")\n\tpublic String slackPostToSpace() {\n\t\treturn getConfigParam(\"slack.post_to_space\", \"\");\n\t}\n\n\t@Documented(position = 2630,\n\t\t\tidentifier = \"slack.default_title\",\n\t\t\tvalue = \"A question from Slack\",\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Default question title for questions created on Slack.\")\n\tpublic String slackDefaultQuestionTitle() {\n\t\treturn getConfigParam(\"slack.default_title\", \"A question from Slack\");\n\t}\n\n\t@Documented(position = 2640,\n\t\t\tidentifier = \"slack.notify_on_new_answer\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send notifications to Slack for new answers.\")\n\tpublic boolean slackNotifyOnNewAnswer() {\n\t\treturn getConfigBoolean(\"slack.notify_on_new_answer\", true);\n\t}\n\n\t@Documented(position = 2650,\n\t\t\tidentifier = \"slack.notify_on_new_question\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send notifications to Slack for new questions.\")\n\tpublic boolean slackNotifyOnNewQuestion() {\n\t\treturn getConfigBoolean(\"slack.notify_on_new_question\", true);\n\t}\n\n\t@Documented(position = 2660,\n\t\t\tidentifier = \"slack.notify_on_new_comment\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send notifications to Slack for new comments.\")\n\tpublic boolean slackNotifyOnNewComment() {\n\t\treturn getConfigBoolean(\"slack.notify_on_new_comment\", true);\n\t}\n\n\t@Documented(position = 2670,\n\t\t\tidentifier = \"slack.dm_on_new_comment\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send direct messages to Slack users for new comments.\")\n\tpublic boolean slacDmOnNewComment() {\n\t\treturn getConfigBoolean(\"slack.dm_on_new_comment\", false);\n\t}\n\n\t@Documented(position = 2680,\n\t\t\tidentifier = \"slack.default_question_tags\",\n\t\t\tvalue = \"via-slack\",\n\t\t\tcategory = \"Slack Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Default question tags for questions created on Slack (comma-separated list).\")\n\tpublic String slackDefaultQuestionTags() {\n\t\treturn getConfigParam(\"slack.default_question_tags\", \"via-slack\");\n\t}\n\n\t/* **************************************************************************************************************\n\t * Microsoft Teams Integration Microsoft Teams Integration *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 2690,\n\t\t\tidentifier = \"teams.bot_id\",\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Teams bot ID.\")\n\tpublic String teamsBotId() {\n\t\treturn getConfigParam(\"teams.bot_id\", \"\");\n\t}\n\n\t@Documented(position = 2700,\n\t\t\tidentifier = \"teams.bot_secret\",\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Teams bot secret key.\")\n\tpublic String teamsBotSecret() {\n\t\treturn getConfigParam(\"teams.bot_secret\", \"\");\n\t}\n\n\t@Documented(position = 2710,\n\t\t\tidentifier = \"teams.bot_service_url\",\n\t\t\tvalue = \"https://smba.trafficmanager.net/emea/\",\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Teams bot service URL.\")\n\tpublic String teamsBotServiceUrl() {\n\t\treturn getConfigParam(\"teams.bot_service_url\", \"https://smba.trafficmanager.net/emea/\");\n\t}\n\n\t@Documented(position = 2720,\n\t\t\tidentifier = \"teams.notify_on_new_answer\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send notifications to Teams for new answers.\")\n\tpublic boolean teamsNotifyOnNewAnswer() {\n\t\treturn getConfigBoolean(\"teams.notify_on_new_answer\", true);\n\t}\n\n\t@Documented(position = 2730,\n\t\t\tidentifier = \"teams.notify_on_new_question\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send notifications to Teams for new questions.\")\n\tpublic boolean teamsNotifyOnNewQuestion() {\n\t\treturn getConfigBoolean(\"teams.notify_on_new_question\", true);\n\t}\n\n\t@Documented(position = 2740,\n\t\t\tidentifier = \"teams.notify_on_new_comment\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send notifications to Teams for new comments.\")\n\tpublic boolean teamsNotifyOnNewComment() {\n\t\treturn getConfigBoolean(\"teams.notify_on_new_comment\", true);\n\t}\n\n\t@Documented(position = 2750,\n\t\t\tidentifier = \"teams.dm_on_new_comment\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable the ability for Scoold to send direct messages to Teams users for new comments.\")\n\tpublic boolean teamsDmOnNewComment() {\n\t\treturn getConfigBoolean(\"teams.dm_on_new_comment\", false);\n\t}\n\n\t@Documented(position = 2760,\n\t\t\tidentifier = \"teams.post_to_space\",\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Default space on Scoold where questions created on Teams will be published. Set it to \"\n\t\t\t\t\t+ \"`workspace` for using the team's name.\")\n\tpublic String teamsPostToSpace() {\n\t\treturn getConfigParam(\"teams.post_to_space\", \"\");\n\t}\n\n\t@Documented(position = 2770,\n\t\t\tidentifier = \"teams.map_channels_to_spaces\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable mapping of Teams channels to Scoold spaces. When enabled, will create a \"\n\t\t\t\t\t+ \"Scoold space for each Teams channel.\")\n\tpublic boolean teamsMapChannelsToSpaces() {\n\t\treturn getConfigBoolean(\"teams.map_channels_to_spaces\", false);\n\t}\n\n\t@Documented(position = 2780,\n\t\t\tidentifier = \"teams.map_workspaces_to_spaces\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Enable/disable mapping of Teams teams to Scoold spaces. When enabled, will create a \"\n\t\t\t\t\t+ \"Scoold space for each Teams team.\")\n\tpublic boolean teamsMapWorkspacesToSpaces() {\n\t\treturn getConfigBoolean(\"teams.map_workspaces_to_spaces\", true);\n\t}\n\n\t@Documented(position = 2790,\n\t\t\tidentifier = \"teams.max_notification_webhooks\",\n\t\t\tvalue = \"10\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"The maximum number of incoming webhooks which can be created on Scoold. Each webhook links a\"\n\t\t\t\t\t+ \" Teams channel to Scoold.\")\n\tpublic int teamsMaxNotificationWebhooks() {\n\t\treturn getConfigInt(\"teams.max_notification_webhooks\", 10);\n\t}\n\n\t@Documented(position = 2800,\n\t\t\tidentifier = \"teams.default_title\",\n\t\t\tvalue = \"A question from Microsoft Teams\",\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Default question title for questions created on Teams.\")\n\tpublic String teamsDefaultQuestionTitle() {\n\t\treturn getConfigParam(\"teams.default_title\", \"A question from Microsoft Teams\");\n\t}\n\n\t@Documented(position = 2810,\n\t\t\tidentifier = \"teams.default_question_tags\",\n\t\t\tvalue = \"via-teams\",\n\t\t\tcategory = \"Microsoft Teams Integration\",\n\t\t\ttags = {\"Pro\"},\n\t\t\tdescription = \"Default question tags for questions created on Teams (comma-separated list).\")\n\tpublic String teamsDefaultQuestionTags() {\n\t\treturn getConfigParam(\"teams.default_question_tags\", \"via-teams\");\n\t}\n\n\t/* **************************************************************************************************************\n\t * SCIM SCIM *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 2820,\n\t\t\tidentifier = \"scim_enabled\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SCIM\",\n\t\t\ttags = {\"Pro\", \"preview\"},\n\t\t\tdescription = \"Enable/disable support for SCIM user provisioning.\")\n\tpublic boolean scimEnabled() {\n\t\treturn getConfigBoolean(\"scim_enabled\", false);\n\t}\n\n\t@Documented(position = 2830,\n\t\t\tidentifier = \"scim_secret_token\",\n\t\t\tcategory = \"SCIM\",\n\t\t\ttags = {\"Pro\", \"preview\"},\n\t\t\tdescription = \"SCIM secret token.\")\n\tpublic String scimSecretToken() {\n\t\treturn getConfigParam(\"scim_secret_token\", \"\");\n\t}\n\n\t@Documented(position = 2840,\n\t\t\tidentifier = \"scim_allow_provisioned_users_only\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SCIM\",\n\t\t\ttags = {\"Pro\", \"preview\"},\n\t\t\tdescription = \"Enable/disable the restriction that only SCIM-provisioned users can sign in.\")\n\tpublic boolean scimAllowProvisionedUsersOnly() {\n\t\treturn getConfigBoolean(\"scim_allow_provisioned_users_only\", false);\n\t}\n\n\t@Documented(position = 2850,\n\t\t\tidentifier = \"scim_map_groups_to_spaces\",\n\t\t\tvalue = \"true\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"SCIM\",\n\t\t\ttags = {\"Pro\", \"preview\"},\n\t\t\tdescription = \"Enable/disable mapping of SCIM groups to Scoold spaces.\")\n\tpublic boolean scimMapGroupsToSpaces() {\n\t\treturn getConfigBoolean(\"scim_map_groups_to_spaces\", true);\n\t}\n\n\t@Documented(position = 2860,\n\t\t\tidentifier = \"security.scim.admins_group_equivalent_to\",\n\t\t\tvalue = \"admins\",\n\t\t\tcategory = \"SCIM\",\n\t\t\ttags = {\"Pro\", \"preview\"},\n\t\t\tdescription = \"SCIM group whose members will be promoted to administrators on Scoold.\")\n\tpublic String scimAdminsGroupEquivalentTo() {\n\t\treturn getConfigParam(\"security.scim.admins_group_equivalent_to\", \"admins\");\n\t}\n\n\t@Documented(position = 2870,\n\t\t\tidentifier = \"security.scim.mods_group_equivalent_to\",\n\t\t\tvalue = \"mods\",\n\t\t\tcategory = \"SCIM\",\n\t\t\ttags = {\"Pro\", \"preview\"},\n\t\t\tdescription = \"SCIM group whose members will be promoted to moderators on Scoold.\")\n\tpublic String scimModeratorsGroupEquivalentTo() {\n\t\treturn getConfigParam(\"security.scim.mods_group_equivalent_to\", \"mods\");\n\t}\n\n\t/* **************************************************************************************************************\n\t * Miscellaneous Miscellaneous *\n\t ****************************************************************************************************************/\n\n\t@Documented(position = 2880,\n\t\t\tidentifier = \"security.redirect_uri\",\n\t\t\tvalue = \"http://localhost:8080\",\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"Publicly accessible, internet-facing URL of the Para endpoint where authenticated users \"\n\t\t\t\t\t+ \"will be redirected to, from the identity provider. Used when Para is hosted behind a proxy.\")\n\tpublic String redirectUri() {\n\t\treturn getConfigParam(\"security.redirect_uri\", paraEndpoint());\n\t}\n\n\t@Documented(position = 2890,\n\t\t\tidentifier = \"redirect_signin_to_idp\",\n\t\t\tvalue = \"false\",\n\t\t\ttype = Boolean.class,\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"Enable/disable the redirection of users from the signin page, directly to the IDP login page.\")\n\tpublic boolean redirectSigninToIdp() {\n\t\treturn getConfigBoolean(\"redirect_signin_to_idp\", false);\n\t}\n\n\t@Documented(position = 2900,\n\t\t\tidentifier = \"gmaps_api_key\",\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"The Google Maps API key. Used for geolocation functionality, (e.g. 'posts near me', location).\")\n\tpublic String googleMapsApiKey() {\n\t\treturn getConfigParam(\"gmaps_api_key\", \"\");\n\t}\n\n\t@Documented(position = 2910,\n\t\t\tidentifier = \"imgur_client_id\",\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\ttags = {\"preview\"},\n\t\t\tdescription = \"Imgur API client id. Used for uploading avatars to Imgur. **Note:** Imgur have some breaking \"\n\t\t\t\t\t+ \"restrictions going on in their API and this might not work.\")\n\tpublic String imgurClientId() {\n\t\treturn getConfigParam(\"imgur_client_id\", \"\");\n\t}\n\n\t@Documented(position = 2920,\n\t\t\tidentifier = \"max_fav_tags\",\n\t\t\tvalue = \"50\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Posts\",\n\t\t\tdescription = \"Maximum number of favorite tags.\")\n\tpublic int maxFavoriteTags() {\n\t\treturn getConfigInt(\"max_fav_tags\", 50);\n\t}\n\n\t@Documented(position = 2930,\n\t\t\tidentifier = \"batch_request_size\",\n\t\t\tvalue = \"0\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"Maximum batch size for the Para client pagination requests.\")\n\tpublic int batchRequestSize() {\n\t\treturn getConfigInt(\"batch_request_size\", 0);\n\t}\n\n\t@Documented(position = 2940,\n\t\t\tidentifier = \"signout_url\",\n\t\t\tvalue = \"/signin?code=5&success=true\",\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"The URL which users will be redirected to after they click 'Sign out'. Can be a page hosted\"\n\t\t\t\t\t+ \" externally.\")\n\tpublic String signoutUrl(int... code) {\n\t\tif (code == null || code.length < 1) {\n\t\t\tcode = new int[]{5};\n\t\t}\n\t\treturn getConfigParam(\"signout_url\", SIGNINLINK + \"?code=\" + code[0] + \"&success=true\");\n\t}\n\n\t@Documented(position = 2950,\n\t\t\tidentifier = \"vote_expires_after_sec\",\n\t\t\tvalue = \"2592000\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"Vote expiration timeout, in seconds. Users can vote again on the same content after \"\n\t\t\t\t\t+ \"this period has elapsed. Default is 30 days.\")\n\tpublic int voteExpiresAfterSec() {\n\t\treturn getConfigInt(\"vote_expires_after_sec\", Para.getConfig().voteExpiresAfterSec());\n\t}\n\n\t@Documented(position = 2960,\n\t\t\tidentifier = \"vote_locked_after_sec\",\n\t\t\tvalue = \"30\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"Vote locking period, in seconds. Vote cannot be changed after this period has elapsed. \"\n\t\t\t\t\t+ \"Default is 30 sec.\")\n\tpublic int voteLockedAfterSec() {\n\t\treturn getConfigInt(\"vote_locked_after_sec\", Para.getConfig().voteLockedAfterSec());\n\t}\n\n\t@Documented(position = 2970,\n\t\t\tidentifier = \"import_batch_size\",\n\t\t\tvalue = \"100\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"Maximum number objects to read and send to Para when importing data from a backup.\")\n\tpublic int importBatchSize() {\n\t\treturn getConfigInt(\"import_batch_size\", 100);\n\t}\n\n\t@Documented(position = 2980,\n\t\t\tidentifier = \"connection_retries_max\",\n\t\t\tvalue = \"10\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"Maximum number of connection retries to Para.\")\n\tpublic int paraConnectionRetryAttempts() {\n\t\treturn getConfigInt(\"connection_retries_max\", 10);\n\t}\n\n\t@Documented(position = 2990,\n\t\t\tidentifier = \"connection_retry_interval_sec\",\n\t\t\tvalue = \"10\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"Para connection retry interval, in seconds.\")\n\tpublic int paraConnectionRetryIntervalSec() {\n\t\treturn getConfigInt(\"connection_retry_interval_sec\", 10);\n\t}\n\n\t@Documented(position = 3000,\n\t\t\tidentifier = \"rewrite_inbound_links_with_fqdn\",\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"If set, links to Scoold in emails will be replaced with a public-facing FQDN.\")\n\tpublic String rewriteInboundLinksWithFQDN() {\n\t\treturn getConfigParam(\"rewrite_inbound_links_with_fqdn\", \"\");\n\t}\n\n\t@Documented(position = 3010,\n\t\t\tidentifier = \"cluster_nodes\",\n\t\t\tvalue = \"1\",\n\t\t\ttype = Integer.class,\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"Total number of nodes present in the cluster when Scoold is deployed behind a reverse proxy.\")\n\tpublic int clusterNodes() {\n\t\treturn getConfigInt(\"cluster_nodes\", 1);\n\t}\n\n\t@Documented(position = 3020,\n\t\t\tidentifier = \"autoinit.root_app_secret_key\",\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"If configured, Scoold will try to automatically initialize itself with Para and create its \"\n\t\t\t\t\t+ \"own Para app, called `app:scoold`. The keys for that new app will be saved in the configuration file.\")\n\tpublic String autoInitWithRootAppSecretKey() {\n\t\treturn getConfigParam(\"autoinit.root_app_secret_key\", \"\");\n\t}\n\n\t@Documented(position = 3030,\n\t\t\tidentifier = \"autoinit.para_config_file\",\n\t\t\tcategory = \"Miscellaneous\",\n\t\t\tdescription = \"Does the same as `scoold.autoinit.root_app_secret_key` but tries to read the secret key for\"\n\t\t\t\t\t+ \" the root Para app from the Para configuration file, wherever that may be.\")\n\tpublic String autoInitWithParaConfigFile() {\n\t\treturn getConfigParam(\"autoinit.para_config_file\", \"\");\n\t}\n\n\t/* **********************************************************************************************************/\n\n\tpublic boolean inDevelopment() {\n\t\treturn environment().equals(\"development\");\n\t}\n\n\tpublic boolean inProduction() {\n\t\treturn environment().equals(\"production\");\n\t}\n\n\tpublic boolean hasValue(String key) {\n\t\treturn !StringUtils.isBlank(getConfigParam(key, \"\"));\n\t}\n\n\tprivate String getAppId() {\n\t\treturn App.identifier(paraAccessKey());\n\t}\n\n\tpublic String localeCookie() {\n\t\treturn getAppId() + \"-locale\";\n\t}\n\n\tpublic String spaceCookie() {\n\t\treturn getAppId() + \"-space\";\n\t}\n\n\tpublic String authCookie() {\n\t\treturn getAppId() + \"-auth\";\n\t}\n\n\tpublic String imagesLink() {\n\t\treturn (inProduction() ? cdnUrl() : serverContextPath()) + \"/images\";\n\t}\n\n\tpublic String scriptsLink() {\n\t\treturn (inProduction() ? cdnUrl() : serverContextPath()) + \"/scripts\";\n\t}\n\n\tpublic String stylesLink() {\n\t\treturn (inProduction() ? cdnUrl() : serverContextPath()) + \"/styles\";\n\t}\n\n\tpublic Map<String, Object> oauthSettings(String alias) {\n\t\tString a = StringUtils.trimToEmpty(alias);\n\t\tMap<String, Object> settings = new LinkedHashMap<>();\n\t\tsettings.put(\"oa2\" + a + \"_app_id\", oauthAppId(a));\n\t\tsettings.put(\"oa2\" + a + \"_secret\", oauthSecret(a));\n\t\tsettings.put(\"security.oauth\" + a + \".token_url\", oauthTokenUrl(a));\n\t\tsettings.put(\"security.oauth\" + a + \".profile_url\", oauthProfileUrl(a));\n\t\tsettings.put(\"security.oauth\" + a + \".scope\", oauthScope(a));\n\t\tsettings.put(\"security.oauth\" + a + \".accept_header\", oauthAcceptHeader(a));\n\t\tsettings.put(\"security.oauth\" + a + \".parameters.id\", oauthIdParameter(a));\n\t\tsettings.put(\"security.oauth\" + a + \".parameters.name\", oauthNameParameter(a));\n\t\tsettings.put(\"security.oauth\" + a + \".parameters.given_name\", oauthGivenNameParameter(a));\n\t\tsettings.put(\"security.oauth\" + a + \".parameters.family_name\", oauthFamiliNameParameter(a));\n\t\tsettings.put(\"security.oauth\" + a + \".parameters.email\", oauthEmailParameter(a));\n\t\tsettings.put(\"security.oauth\" + a + \".parameters.picture\", oauthPictureParameter(a));\n\t\tsettings.put(\"security.oauth\" + a + \".download_avatars\", oauthAvatarDownloadingEnabled(a));\n\t\tsettings.put(\"security.oauth\" + a + \".domain\", oauthDomain(a));\n\t\tsettings.put(\"security.oauth\" + a + \".token_delegation_enabled\", oauthTokenDelegationEnabled(a));\n\t\treturn settings;\n\t}\n\n\tpublic Map<String, Object> ldapSettings() {\n\t\tMap<String, Object> settings = new LinkedHashMap<>();\n\t\tsettings.put(\"security.ldap.server_url\", ldapServerUrl());\n\t\tsettings.put(\"security.ldap.base_dn\", ldapBaseDN());\n\t\tsettings.put(\"security.ldap.bind_dn\", ldapBindDN());\n\t\tsettings.put(\"security.ldap.bind_pass\", ldapBindPassword());\n\t\tsettings.put(\"security.ldap.user_search_base\", ldapUserSearchBase());\n\t\tsettings.put(\"security.ldap.user_search_filter\", ldapUserSearchFilter());\n\t\tsettings.put(\"security.ldap.user_dn_pattern\", ldapUserDNPattern());\n\t\tsettings.put(\"security.ldap.password_attribute\", ldapPasswordAttributeName());\n\t\tsettings.put(\"security.ldap.username_as_name\", ldapUsernameAsName());\n\t\tsettings.put(\"security.ldap.active_directory_domain\", ldapActiveDirectoryDomain());\n\t\tsettings.put(\"security.ldap.mods_group_node\", ldapModeratorsGroupNode());\n\t\tsettings.put(\"security.ldap.admins_group_node\", ldapAdministratorsGroupNode());\n\t\tif (!ldapComparePasswords().isEmpty()) {\n\t\t\tsettings.put(\"security.ldap.compare_passwords\", ldapComparePasswords());\n\t\t}\n\t\treturn settings;\n\t}\n\n\tpublic Map<String, Object> samlSettings() {\n\t\tMap<String, Object> settings = new LinkedHashMap<>();\n\t\tsettings.put(\"security.saml.sp.entityid\", samlSPEntityId());\n\t\tsettings.put(\"security.saml.sp.assertion_consumer_service.url\", samlSPAssertionConsumerServiceUrl());\n\t\tsettings.put(\"security.saml.sp.nameidformat\", samlSPNameIdFormat());\n\t\tsettings.put(\"security.saml.sp.x509cert\", samlSPX509Certificate());\n\t\tsettings.put(\"security.saml.sp.privatekey\", samlSPX509PrivateKey());\n\n\t\tsettings.put(\"security.saml.idp.entityid\", samlIDPEntityId());\n\t\tsettings.put(\"security.saml.idp.single_sign_on_service.url\", samlIDPSingleSignOnServiceUrl());\n\t\tsettings.put(\"security.saml.idp.x509cert\", samlIDPX509Certificate());\n\t\tsettings.put(\"security.saml.idp.metadata_url\", samlIDPMetadataUrl());\n\n\t\tsettings.put(\"security.saml.security.authnrequest_signed\", samlAuthnRequestSigningEnabled());\n\t\tsettings.put(\"security.saml.security.want_messages_signed\", samlMessageSigningEnabled());\n\t\tsettings.put(\"security.saml.security.want_assertions_signed\", samlAssertionSigningEnabled());\n\t\tsettings.put(\"security.saml.security.want_assertions_encrypted\", samlAssertionEncryptionEnabled());\n\t\tsettings.put(\"security.saml.security.want_nameid_encrypted\", samlNameidEncryptionEnabled());\n\t\tsettings.put(\"security.saml.security.sign_metadata\", samlMetadataSigningEnabled());\n\t\tsettings.put(\"security.saml.security.want_xml_validation\", samlXMLValidationEnabled());\n\t\tsettings.put(\"security.saml.security.signature_algorithm\", samlSignatureAlgorithm());\n\n\t\tsettings.put(\"security.saml.attributes.id\", samlIdAttribute());\n\t\tsettings.put(\"security.saml.attributes.picture\", samlPictureAttribute());\n\t\tsettings.put(\"security.saml.attributes.email\", samlEmailAttribute());\n\t\tsettings.put(\"security.saml.attributes.name\", samlNameAttribute());\n\t\tsettings.put(\"security.saml.attributes.firstname\", samlFirstNameAttribute());\n\t\tsettings.put(\"security.saml.attributes.lastname\", samlLastNameAttribute());\n\t\tsettings.put(\"security.saml.domain\", samlDomain());\n\t\treturn settings;\n\t}\n\n\tpublic Map<String, Object> getParaAppSettings() {\n\t\tMap<String, Object> settings = new LinkedHashMap<String, Object>();\n\t\tsettings.put(\"gp_app_id\", googleAppId());\n\t\tsettings.put(\"gp_secret\", googleSecret());\n\t\tsettings.put(\"fb_app_id\", facebookAppId());\n\t\tsettings.put(\"fb_secret\", facebookSecret());\n\t\tsettings.put(\"gh_app_id\", githubAppId());\n\t\tsettings.put(\"gh_secret\", githubSecret());\n\t\tsettings.put(\"in_app_id\", linkedinAppId());\n\t\tsettings.put(\"in_secret\", linkedinSecret());\n\t\tsettings.put(\"tw_app_id\", twitterAppId());\n\t\tsettings.put(\"tw_secret\", twitterSecret());\n\t\tsettings.put(\"ms_app_id\", microsoftAppId());\n\t\tsettings.put(\"ms_secret\", microsoftSecret());\n\t\tsettings.put(\"sl_app_id\", slackAppId());\n\t\tsettings.put(\"sl_secret\", slackSecret());\n\t\tsettings.put(\"az_app_id\", amazonAppId());\n\t\tsettings.put(\"az_secret\", amazonSecret());\n\t\t// Microsoft tenant id support - https://github.com/Erudika/scoold/issues/208\n\t\tsettings.put(\"ms_tenant_id\", microsoftTenantId());\n\t\t// OAuth 2 settings\n\t\tsettings.putAll(oauthSettings(\"\"));\n\t\tsettings.putAll(oauthSettings(\"second\"));\n\t\tsettings.putAll(oauthSettings(\"third\"));\n\t\t// LDAP settings\n\t\tsettings.putAll(ldapSettings());\n\t\t// SAML settings\n\t\tsettings.putAll(samlSettings());\n\t\t// secret key\n\t\tsettings.put(\"app_secret_key\", appSecretKey());\n\t\t// email verification\n\t\tsettings.put(\"security.allow_unverified_emails\", allowUnverifiedEmails());\n\t\t// sessions\n\t\tsettings.put(\"security.one_session_per_user\", oneSessionPerUser());\n\t\tsettings.put(\"session_timeout\", sessionTimeoutSec());\n\n\t\t// URLs for success and failure\n\t\tsettings.put(\"signin_success\", serverUrl() + serverContextPath() + SIGNINLINK + \"/success?jwt=id\");\n\t\tsettings.put(\"signin_failure\", serverUrl() + serverContextPath() + SIGNINLINK + \"?code=3&error=true\");\n\t\treturn settings;\n\t}\n\n\tString getDefaultContentSecurityPolicy() {\n\t\treturn \"default-src 'self'; \"\n\t\t\t\t+ \"base-uri 'self'; \"\n\t\t\t\t+ \"media-src 'self' blob:; \"\n\t\t\t\t+ \"form-action 'self' \" + signoutUrl() + \"; \"\n\t\t\t\t+ \"connect-src 'self' \" + (inProduction() ? serverUrl() : \"\")\n\t\t\t\t+ \" maps.googleapis.com api.imgur.com accounts.google.com \" + cspConnectSources() + \"; \"\n\t\t\t\t+ \"frame-src 'self' *.google.com staticxx.facebook.com \" + cspFrameSources() + \"; \"\n\t\t\t\t+ \"font-src 'self' cdnjs.cloudflare.com fonts.gstatic.com fonts.googleapis.com \" + cspFontSources() + \"; \"\n\t\t\t\t// unsafe-inline required by MathJax and Google Maps!\n\t\t\t\t+ \"style-src 'self' 'unsafe-inline' fonts.googleapis.com accounts.google.com \"\n\t\t\t\t+ (cdnUrl().startsWith(\"/\") ? \"\" : cdnUrl()) + \" \" + cspStyleSources() + \"; \"\n\t\t\t\t+ \"img-src 'self' https: data:; \"\n\t\t\t\t+ \"object-src 'none'; \"\n\t\t\t\t+ \"report-uri /reports/cspv; \"\n\t\t\t\t+ \"script-src 'unsafe-inline' https: 'nonce-{{nonce}}' 'strict-dynamic';\"; // CSP2 backward compatibility\n\t}\n\n}", "public static final String REPORTSLINK = HOMEPAGE + \"reports\";", "public static final String SIGNINLINK = HOMEPAGE + \"signin\";", "public class Profile extends Sysprop {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\t@Stored private String originalName;\n\t@Stored private String originalPicture;\n\t@Stored private Long lastseen;\n\t@Stored private String location;\n\t@Stored private String latlng;\n\t@Stored private String status;\n\t@Stored private String aboutme;\n\t@Stored private String badges;\n\t@Stored private String groups;\n\t@Stored private Long upvotes;\n\t@Stored private Long downvotes;\n\t@Stored private Long comments;\n\t@Stored @URL private String picture;\n\t@Stored @URL private String website;\n\t@Stored private List<String> favtags;\n\t@Stored private Set<String> favspaces;\n\t@Stored private Set<String> spaces;\n\t@Stored private Boolean replyEmailsEnabled;\n\t@Stored private Boolean commentEmailsEnabled;\n\t@Stored private Boolean favtagsEmailsEnabled;\n\t@Stored private Boolean anonymityEnabled;\n\t@Stored private Boolean darkmodeEnabled;\n\t@Stored private Integer yearlyVotes;\n\t@Stored private Integer quarterlyVotes;\n\t@Stored private Integer monthlyVotes;\n\t@Stored private Integer weeklyVotes;\n\n\tprivate transient String newbadges;\n\tprivate transient Integer newreports;\n\tprivate transient User user;\n\n\tpublic enum Badge {\n\t\tVETERAN(10),\t\t//regular visitor\t\t//NOT IMPLEMENTED\n\n\t\tNICEPROFILE(10),\t//100% profile completed\n\t\tREPORTER(0),\t\t//for every report\n\t\tVOTER(0),\t\t\t//100 total votes\n\t\tCOMMENTATOR(0),\t\t//100+ comments\n\t\tCRITIC(0),\t\t\t//10+ downvotes\n\t\tSUPPORTER(10),\t\t//50+ upvotes\n\t\tEDITOR(0),\t\t\t//first edit of post\n\t\tBACKINTIME(0),\t\t//for each rollback of post\n\t\tNOOB(10),\t\t\t//first question + first approved answer\n\t\tENTHUSIAST(0),\t\t//100+ rep [//\t\t\t ]\n\t\tFRESHMAN(0),\t\t//300+ rep\t[////\t\t ]\n\t\tSCHOLAR(0),\t\t\t//500+ rep\t[//////\t\t ]\n\t\tTEACHER(0),\t\t\t//1000+ rep\t[////////\t ]\n\t\tPROFESSOR(0),\t\t//5000+ rep\t[//////////\t ]\n\t\tGEEK(0),\t\t\t//9000+ rep\t[////////////]\n\t\tGOODQUESTION(10),\t//20+ votes\n\t\tGOODANSWER(10),\t\t//10+ votes\n\t\tEUREKA(0),\t\t\t//for every answer to own question\n\t\tSENIOR(0),\t\t\t//one year + member\n\t\tDISCIPLINED(0);\t\t//each time user deletes own comment\n\n\t\tprivate final int reward;\n\n\t\tBadge(int reward) {\n\t\t\tthis.reward = reward;\n\t\t}\n\n\t\tpublic String toString() {\n\t\t\treturn super.toString().toLowerCase();\n\t\t}\n\n\t\tpublic Integer getReward() {\n\t\t\treturn this.reward;\n\t\t}\n\t}\n\n\tpublic Profile() {\n\t\tthis(null, null);\n\t}\n\n\tpublic Profile(String id) {\n\t\tthis(id, null);\n\t}\n\n\tpublic Profile(String userid, String name) {\n\t\tsetId(id(userid));\n\t\tsetName(name);\n\t\tthis.status = \"\";\n\t\tthis.aboutme = \"\";\n\t\tthis.location = \"\";\n\t\tthis.website = \"\";\n\t\tthis.badges = \"\";\n\t\tthis.upvotes = 0L;\n\t\tthis.downvotes = 0L;\n\t\tthis.comments = 0L;\n\t\tthis.yearlyVotes = 0;\n\t\tthis.quarterlyVotes = 0;\n\t\tthis.monthlyVotes = 0;\n\t\tthis.weeklyVotes = 0;\n\t\tthis.anonymityEnabled = false;\n\t\tthis.darkmodeEnabled = false;\n\t\tthis.favtagsEmailsEnabled = ScooldUtils.getConfig().favoriteTagsEmailsEnabled();\n\t\tthis.replyEmailsEnabled = ScooldUtils.getConfig().replyEmailsEnabled();\n\t\tthis.commentEmailsEnabled = ScooldUtils.getConfig().commentEmailsEnabled();\n\t}\n\n\tpublic static final String id(String userid) {\n\t\tif (StringUtils.endsWith(userid, Para.getConfig().separator() + \"profile\")) {\n\t\t\treturn userid;\n\t\t} else {\n\t\t\treturn userid != null ? userid + Para.getConfig().separator() + \"profile\" : null;\n\t\t}\n\t}\n\n\tpublic static Profile fromUser(User u) {\n\t\tProfile p = new Profile(u.getId(), u.getName());\n\t\tp.setUser(u);\n\t\tp.setOriginalName(u.getName());\n\t\tp.setPicture(u.getPicture());\n\t\tp.setAppid(u.getAppid());\n\t\tp.setCreatorid(u.getId());\n\t\tp.setTimestamp(u.getTimestamp());\n\t\tp.setGroups(ScooldUtils.getInstance().isRecognizedAsAdmin(u)\n\t\t\t\t? User.Groups.ADMINS.toString() : u.getGroups());\n\t\t// auto-assign spaces to new users\n\t\tString space = StringUtils.substringBefore(ScooldUtils.getConfig().autoAssignSpaces(), \",\");\n\t\tif (!StringUtils.isBlank(space) && !ScooldUtils.getInstance().isDefaultSpace(space)) {\n\t\t\tSysprop s = client().read(ScooldUtils.getInstance().getSpaceId(space));\n\t\t\tif (s == null) {\n\t\t\t\ts = ScooldUtils.getInstance().buildSpaceObject(space);\n\t\t\t\tclient().create(s); // create the space it it's missing\n\t\t\t}\n\t\t\tif (ScooldUtils.getConfig().resetSpacesOnNewAssignment(u.isOAuth2User() || u.isLDAPUser() || u.isSAMLUser())) {\n\t\t\t\tp.setSpaces(Collections.singleton(s.getId() + Para.getConfig().separator() + s.getName()));\n\t\t\t} else {\n\t\t\t\tp.getSpaces().add(s.getId() + Para.getConfig().separator() + s.getName());\n\t\t\t}\n\t\t}\n\t\treturn p;\n\t}\n\n\tprivate static ParaClient client() {\n\t\treturn ScooldUtils.getInstance().getParaClient();\n\t}\n\n\t@JsonIgnore\n\tpublic User getUser() {\n\t\tif (user == null) {\n\t\t\tuser = client().read(getCreatorid() == null\n\t\t\t\t\t? StringUtils.removeEnd(getId(), Para.getConfig().separator() + \"profile\") : getCreatorid());\n\t\t}\n\t\treturn user;\n\t}\n\n\tpublic Integer getYearlyVotes() {\n\t\tif (yearlyVotes < 0) {\n\t\t\tyearlyVotes = 0;\n\t\t}\n\t\treturn yearlyVotes;\n\t}\n\n\tpublic void setYearlyVotes(Integer yearlyVotes) {\n\t\tthis.yearlyVotes = yearlyVotes;\n\t}\n\n\tpublic Integer getQuarterlyVotes() {\n\t\tif (quarterlyVotes < 0) {\n\t\t\tquarterlyVotes = 0;\n\t\t}\n\t\treturn quarterlyVotes;\n\t}\n\n\tpublic void setQuarterlyVotes(Integer quarterlyVotes) {\n\t\tthis.quarterlyVotes = quarterlyVotes;\n\t}\n\n\tpublic Integer getMonthlyVotes() {\n\t\tif (monthlyVotes < 0) {\n\t\t\tmonthlyVotes = 0;\n\t\t}\n\t\treturn monthlyVotes;\n\t}\n\n\tpublic void setMonthlyVotes(Integer monthlyVotes) {\n\t\tthis.monthlyVotes = monthlyVotes;\n\t}\n\n\tpublic Integer getWeeklyVotes() {\n\t\tif (weeklyVotes < 0) {\n\t\t\tweeklyVotes = 0;\n\t\t}\n\t\treturn weeklyVotes;\n\t}\n\n\tpublic void setWeeklyVotes(Integer weeklyVotes) {\n\t\tthis.weeklyVotes = weeklyVotes;\n\t}\n\n\tpublic Boolean getReplyEmailsEnabled() {\n\t\treturn replyEmailsEnabled;\n\t}\n\n\tpublic void setReplyEmailsEnabled(Boolean replyEmailsEnabled) {\n\t\tthis.replyEmailsEnabled = replyEmailsEnabled;\n\t}\n\n\tpublic Boolean getCommentEmailsEnabled() {\n\t\treturn commentEmailsEnabled;\n\t}\n\n\tpublic void setCommentEmailsEnabled(Boolean commentEmailsEnabled) {\n\t\tthis.commentEmailsEnabled = commentEmailsEnabled;\n\t}\n\n\tpublic Boolean getFavtagsEmailsEnabled() {\n\t\treturn favtagsEmailsEnabled;\n\t}\n\n\tpublic void setFavtagsEmailsEnabled(Boolean favtagsEmailsEnabled) {\n\t\tthis.favtagsEmailsEnabled = favtagsEmailsEnabled;\n\t}\n\n\tpublic Boolean getAnonymityEnabled() {\n\t\treturn anonymityEnabled;\n\t}\n\n\tpublic void setAnonymityEnabled(Boolean anonymityEnabled) {\n\t\tthis.anonymityEnabled = anonymityEnabled;\n\t}\n\n\tpublic Boolean getDarkmodeEnabled() {\n\t\treturn darkmodeEnabled;\n\t}\n\n\tpublic void setDarkmodeEnabled(Boolean darkmodeEnabled) {\n\t\tthis.darkmodeEnabled = darkmodeEnabled;\n\t}\n\n\tpublic String getGroups() {\n\t\treturn groups;\n\t}\n\n\tpublic void setGroups(String groups) {\n\t\tthis.groups = groups;\n\t}\n\n\tpublic String getPicture() {\n\t\treturn picture;\n\t}\n\n\tpublic void setPicture(String picture) {\n\t\tthis.picture = picture;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic String getLatlng() {\n\t\treturn latlng;\n\t}\n\n\tpublic void setLatlng(String latlng) {\n\t\tthis.latlng = latlng;\n\t}\n\n\tpublic String getNewbadges() {\n\t\treturn newbadges;\n\t}\n\n\tpublic void setNewbadges(String newbadges) {\n\t\tthis.newbadges = newbadges;\n\t}\n\n\tpublic List<String> getFavtags() {\n\t\tif (favtags == null) {\n\t\t\tfavtags = new LinkedList<String>();\n\t\t}\n\t\treturn favtags;\n\t}\n\n\tpublic void setFavtags(List<String> favtags) {\n\t\tthis.favtags = favtags;\n\t}\n\n\tpublic Set<String> getFavspaces() {\n\t\tif (favspaces == null) {\n\t\t\tfavspaces = new LinkedHashSet<String>();\n\t\t}\n\t\treturn favspaces;\n\t}\n\n\tpublic void setFavspaces(Set<String> favspaces) {\n\t\tthis.favspaces = favspaces;\n\t}\n\n\tpublic Set<String> getSpaces() {\n\t\tif (ScooldUtils.getInstance().isMod(this)) {\n\t\t\tspaces = ScooldUtils.getInstance().getAllSpaces().stream().\n\t\t\t\t\tmap(s -> s.getId() + Para.getConfig().separator() + s.getName()).collect(Collectors.toSet());\n\t\t}\n\t\tif (spaces == null) {\n\t\t\tspaces = new LinkedHashSet<String>();\n\t\t}\n\t\tif (spaces.isEmpty()) {\n\t\t\tspaces.add(Post.DEFAULT_SPACE);\n\t\t}\n\t\t// this is confusing - let admins control who is in the default space\n\t\t//if (spaces.size() > 1 && spaces.contains(Post.DEFAULT_SPACE)) {\n\t\t//\tspaces.remove(Post.DEFAULT_SPACE);\n\t\t//}\n\t\treturn spaces;\n\t}\n\n\tpublic void setSpaces(Set<String> spaces) {\n\t\tthis.spaces = spaces;\n\t}\n\n\t@JsonIgnore\n\tpublic Set<String> getAllSpaces() {\n\t\treturn getSpaces().stream().filter(s -> !s.equalsIgnoreCase(Post.DEFAULT_SPACE)).collect(Collectors.toSet());\n\t}\n\n\tpublic Long getLastseen() {\n\t\treturn lastseen;\n\t}\n\n\tpublic void setLastseen(Long val) {\n\t\tthis.lastseen = val;\n\t}\n\n\tpublic String getWebsite() {\n\t\treturn website;\n\t}\n\n\tpublic void setWebsite(String website) {\n\t\tthis.website = website;\n\t}\n\n\tpublic Long getComments() {\n\t\treturn comments;\n\t}\n\n\tpublic void setComments(Long comments) {\n\t\tthis.comments = comments;\n\t}\n\n\tpublic Long getDownvotes() {\n\t\treturn downvotes;\n\t}\n\n\tpublic void setDownvotes(Long downvotes) {\n\t\tthis.downvotes = downvotes;\n\t}\n\n\tpublic Long getUpvotes() {\n\t\treturn upvotes;\n\t}\n\n\tpublic void setUpvotes(Long upvotes) {\n\t\tthis.upvotes = upvotes;\n\t}\n\n\tpublic String getBadges() {\n\t\treturn badges;\n\t}\n\n\tpublic void setBadges(String badges) {\n\t\tthis.badges = badges;\n\t}\n\n\tpublic String getLocation() {\n\t\treturn location;\n\t}\n\n\tpublic void setLocation(String location) {\n\t\tthis.location = location;\n\t}\n\n\tpublic String getStatus() {\n\t\treturn status;\n\t}\n\n\tpublic void setStatus(String status) {\n\t\tthis.status = status;\n\t}\n\n\tpublic String getAboutme() {\n\t\treturn this.aboutme;\n\t}\n\n\tpublic void setAboutme(String aboutme) {\n\t\tthis.aboutme = aboutme;\n\t}\n\n\tpublic String getOriginalName() {\n\t\treturn originalName;\n\t}\n\n\tpublic void setOriginalName(String originalName) {\n\t\tthis.originalName = originalName;\n\t}\n\n\tpublic String getOriginalPicture() {\n\t\treturn originalPicture;\n\t}\n\n\tpublic void setOriginalPicture(String originalPicture) {\n\t\tthis.originalPicture = originalPicture;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Question> getAllQuestions(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList<Question>();\n\t\t}\n\t\treturn (List<Question>) getPostsForUser(Utils.type(Question.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Reply> getAllAnswers(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList<Reply>();\n\t\t}\n\t\treturn (List<Reply>) getPostsForUser(Utils.type(Reply.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Question> getAllUnapprovedQuestions(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList<Question>();\n\t\t}\n\t\treturn (List<Question>) getPostsForUser(Utils.type(UnapprovedQuestion.class), pager);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Reply> getAllUnapprovedAnswers(Pager pager) {\n\t\tif (getId() == null) {\n\t\t\treturn new ArrayList<Reply>();\n\t\t}\n\t\treturn (List<Reply>) getPostsForUser(Utils.type(UnapprovedReply.class), pager);\n\t}\n\n\tprivate List<? extends Post> getPostsForUser(String type, Pager pager) {\n\t\tpager.setSortby(\"votes\");\n\t\treturn client().findTerms(type, Collections.singletonMap(Config._CREATORID, getId()), true, pager);\n\t}\n\n\tpublic String getFavtagsString() {\n\t\tif (getFavtags().isEmpty()) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn StringUtils.join(getFavtags(), \", \");\n\t}\n\n\tpublic boolean hasFavtags() {\n\t\treturn !getFavtags().isEmpty();\n\t}\n\n\tpublic boolean hasSpaces() {\n\t\treturn !(getSpaces().size() <= 1 && getSpaces().contains(Post.DEFAULT_SPACE));\n\t}\n\n\tpublic void removeSpace(String space) {\n\t\tString sid = ScooldUtils.getInstance().getSpaceId(space);\n\t\tIterator<String> it = getSpaces().iterator();\n\t\twhile (it.hasNext()) {\n\t\t\tif (it.next().startsWith(sid + Para.getConfig().separator())) {\n\t\t\t\tit.remove();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic long getTotalVotes() {\n\t\tif (upvotes == null) {\n\t\t\tupvotes = 0L;\n\t\t}\n\t\tif (downvotes == null) {\n\t\t\tdownvotes = 0L;\n\t\t}\n\n\t\treturn upvotes + downvotes;\n\t}\n\n\tpublic void addRep(int rep) {\n\t\tif (getVotes() == null) {\n\t\t\tsetVotes(0);\n\t\t}\n\t\tsetVotes(getVotes() + rep);\n\t\tupdateVoteGains(rep);\n\t}\n\n\tpublic void removeRep(int rep) {\n\t\tif (getVotes() == null) {\n\t\t\tsetVotes(0);\n\t\t}\n\t\tsetVotes(getVotes() - rep);\n\t\tupdateVoteGains(-rep);\n\t\tif (getVotes() < 0) {\n\t\t\tsetVotes(0);\n\t\t}\n\t}\n\n\tpublic void incrementUpvotes() {\n\t\tif (this.upvotes == null) {\n\t\t\tthis.upvotes = 1L;\n\t\t} else {\n\t\t\tthis.upvotes = this.upvotes + 1L;\n\t\t}\n\t}\n\n\tpublic void incrementDownvotes() {\n\t\tif (this.downvotes == null) {\n\t\t\tthis.downvotes = 1L;\n\t\t} else {\n\t\t\tthis.downvotes = this.downvotes + 1L;\n\t\t}\n\t}\n\n\tprivate void updateVoteGains(int rep) {\n\t\tLong updated = Optional.ofNullable(getUpdated()).orElse(getTimestamp());\n\t\tLocalDateTime lastUpdate = LocalDateTime.ofInstant(Instant.ofEpochMilli(updated), ZoneId.systemDefault());\n\t\tLocalDate now = LocalDate.now();\n\t\tif (now.getYear() != lastUpdate.getYear()) {\n\t\t\tyearlyVotes = rep;\n\t\t} else {\n\t\t\tyearlyVotes += rep;\n\t\t}\n\t\tif (now.get(IsoFields.QUARTER_OF_YEAR) != lastUpdate.get(IsoFields.QUARTER_OF_YEAR)) {\n\t\t\tquarterlyVotes = rep;\n\t\t} else {\n\t\t\tquarterlyVotes += rep;\n\t\t}\n\t\tif (now.getMonthValue() != lastUpdate.getMonthValue()) {\n\t\t\tmonthlyVotes = rep;\n\t\t} else {\n\t\t\tmonthlyVotes += rep;\n\t\t}\n\t\tif (now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR) != lastUpdate.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)) {\n\t\t\tweeklyVotes = rep;\n\t\t} else {\n\t\t\tweeklyVotes += rep;\n\t\t}\n\t\tsetUpdated(Utils.timestamp());\n\t}\n\n\tpublic boolean hasBadge(Badge b) {\n\t\treturn StringUtils.containsIgnoreCase(badges, \",\".concat(b.toString()).concat(\",\"));\n\t}\n\n\tpublic void addBadge(Badge b) {\n\t\tString badge = b.toString();\n\t\tif (StringUtils.isBlank(badges)) {\n\t\t\tbadges = \",\";\n\t\t}\n\t\tbadges = badges.concat(badge).concat(\",\");\n\t\taddRep(b.getReward());\n\t}\n\n\tpublic void addBadges(Badge[] larr) {\n\t\tfor (Badge badge : larr) {\n\t\t\taddBadge(badge);\n\t\t\taddRep(badge.getReward());\n\t\t}\n\t}\n\n\tpublic void removeBadge(Badge b) {\n\t\tString badge = b.toString();\n\t\tif (StringUtils.isBlank(badges)) {\n\t\t\treturn;\n\t\t}\n\t\tbadge = \",\".concat(badge).concat(\",\");\n\n\t\tif (badges.contains(badge)) {\n\t\t\tbadges = badges.replaceFirst(badge, \",\");\n\t\t\tremoveRep(b.getReward());\n\t\t}\n\t\tif (StringUtils.isBlank(badges.replaceAll(\",\", \"\"))) {\n\t\t\tbadges = \"\";\n\t\t}\n\t}\n\n\tpublic HashMap<String, Integer> getBadgesMap() {\n\t\tHashMap<String, Integer> badgeMap = new HashMap<String, Integer>(0);\n\t\tif (StringUtils.isBlank(badges)) {\n\t\t\treturn badgeMap;\n\t\t}\n\n\t\tfor (String badge : badges.split(\",\")) {\n\t\t\tInteger val = badgeMap.get(badge);\n\t\t\tint count = (val == null) ? 0 : val.intValue();\n\t\t\tbadgeMap.put(badge, ++count);\n\t\t}\n\n\t\tbadgeMap.remove(\"\");\n\t\treturn badgeMap;\n\t}\n\n\tpublic boolean isComplete() {\n\t\treturn (!StringUtils.isBlank(location)\n\t\t\t\t&& !StringUtils.isBlank(aboutme)\n\t\t\t\t&& !StringUtils.isBlank(website));\n\t}\n\n\tpublic String create() {\n\t\tsetLastseen(System.currentTimeMillis());\n\t\tclient().create(this);\n\t\treturn getId();\n\t}\n\n\tpublic void update() {\n\t\tsetLastseen(System.currentTimeMillis());\n\t\tupdateVoteGains(0); // reset vote gains if they we're past the time frame\n\t\tclient().update(this);\n\t}\n\n\tpublic void delete() {\n\t\tclient().delete(this);\n\t\tclient().delete(getUser());\n\t\tScooldUtils.getInstance().unsubscribeFromAllNotifications(this);\n\t}\n\n\tpublic int countNewReports() {\n\t\tif (newreports == null) {\n\t\t\tnewreports = client().getCount(Utils.type(Report.class),\n\t\t\t\t\tCollections.singletonMap(\"properties.closed\", false)).intValue();\n\t\t}\n\t\treturn newreports;\n\t}\n\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == null || getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\treturn Objects.equals(getName(), ((Profile) obj).getName())\n\t\t\t\t&& Objects.equals(getLocation(), ((Profile) obj).getLocation())\n\t\t\t\t&& Objects.equals(getId(), ((Profile) obj).getId());\n\t}\n\n\tpublic int hashCode() {\n\t\treturn Objects.hashCode(getName()) + Objects.hashCode(getId());\n\t}\n}", "public class Report extends Sysprop {\n\tprivate static final long serialVersionUID = 1L;\n\n\t@Stored private String subType;\n\t@Stored private String description;\n\t@Stored private String authorName;\n\t@Stored private String link;\n\t@Stored private String solution;\n\t@Stored private Boolean closed;\n\n\tpublic enum ReportType {\n\t\tSPAM, OFFENSIVE, DUPLICATE, INCORRECT, OTHER;\n\n\t\tpublic String toString() {\n\t\t\treturn super.toString().toLowerCase();\n\t\t}\n\t}\n\n\tpublic Report() {\n\t\tthis(null, null, null, null);\n\t}\n\n\tpublic Report(String id) {\n\t\tthis(null, null, null, null);\n\t\tsetId(id);\n\t}\n\n\tpublic Report(String parentid, String type, String description, String creatorid) {\n\t\tsetParentid(parentid);\n\t\tsetCreatorid(creatorid);\n\t\tthis.subType = ReportType.OTHER.toString();\n\t\tthis.description = subType;\n\t\tthis.closed = false;\n\t}\n\n\tprivate ParaClient client() {\n\t\treturn ScooldUtils.getInstance().getParaClient();\n\t}\n\n\tpublic Boolean getClosed() {\n\t\treturn closed;\n\t}\n\n\tpublic void setClosed(Boolean closed) {\n\t\tthis.closed = closed;\n\t}\n\n\tpublic String getSolution() {\n\t\treturn solution;\n\t}\n\n\tpublic void setSolution(String solution) {\n\t\tthis.solution = solution;\n\t}\n\n\tpublic String getLink() {\n\t\treturn link;\n\t}\n\n\tpublic void setLink(String link) {\n\t\tthis.link = link;\n\t}\n\n\tpublic String getAuthorName() {\n\t\treturn authorName;\n\t}\n\n\tpublic void setAuthorName(String authorName) {\n\t\tthis.authorName = authorName;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic String getSubType() {\n\t\tif (subType == null) {\n\t\t\tsubType = ReportType.OTHER.toString();\n\t\t}\n\t\treturn subType;\n\t}\n\n\tpublic void setSubType(String subType) {\n\t\tthis.subType = subType;\n\t}\n\n\tpublic void setSubType(ReportType subType) {\n\t\tif (subType != null) {\n\t\t\tthis.subType = subType.name();\n\t\t}\n\t}\n\n\tpublic void delete() {\n\t\tclient().delete(this);\n\t}\n\n\tpublic void update() {\n\t\tclient().update(this);\n\t}\n\n\tpublic String create() {\n\t\tReport r = client().create(this);\n\t\tif (r != null) {\n\t\t\tScooldUtils.getInstance().triggerHookEvent(\"report.create\", this);\n\t\t\tsetId(r.getId());\n\t\t\tsetTimestamp(r.getTimestamp());\n\t\t\treturn r.getId();\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == null || getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\treturn Objects.equals(getSubType(), ((Report) obj).getSubType()) &&\n\t\t\t\tObjects.equals(getDescription(), ((Report) obj).getDescription()) &&\n\t\t\t\tObjects.equals(getCreatorid(), ((Report) obj).getCreatorid());\n\t}\n\n\tpublic int hashCode() {\n\t\treturn Objects.hashCode(getSubType()) + Objects.hashCode(getDescription()) +\n\t\t\t\tObjects.hashCode(getCreatorid()) + Objects.hashCode(getParentid());\n\t}\n\n}", "@Component\n@Named\npublic final class ScooldUtils {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(ScooldUtils.class);\n\tprivate static final Map<String, String> FILE_CACHE = new ConcurrentHashMap<String, String>();\n\tprivate static final Set<String> APPROVED_DOMAINS = new HashSet<>();\n\tprivate static final Set<String> ADMINS = new HashSet<>();\n\tprivate static final String EMAIL_ALERTS_PREFIX = \"email-alerts\" + Para.getConfig().separator();\n\n\tprivate static final Profile API_USER;\n\tprivate static final Set<String> CORE_TYPES;\n\tprivate static final Set<String> HOOK_EVENTS;\n\tprivate static final Map<String, String> WHITELISTED_MACROS;\n\tprivate static final Map<String, Object> API_KEYS = new LinkedHashMap<>(); // jti => jwt\n\n\tprivate List<Sysprop> allSpaces;\n\n\tprivate static final ScooldConfig CONF = new ScooldConfig();\n\n\tstatic {\n\t\tAPI_USER = new Profile(\"1\", \"System\");\n\t\tAPI_USER.setVotes(1);\n\t\tAPI_USER.setCreatorid(\"1\");\n\t\tAPI_USER.setTimestamp(Utils.timestamp());\n\t\tAPI_USER.setGroups(User.Groups.ADMINS.toString());\n\n\t\tCORE_TYPES = new HashSet<>(Arrays.asList(Utils.type(Comment.class),\n\t\t\t\tUtils.type(Feedback.class),\n\t\t\t\tUtils.type(Profile.class),\n\t\t\t\tUtils.type(Question.class),\n\t\t\t\tUtils.type(Reply.class),\n\t\t\t\tUtils.type(Report.class),\n\t\t\t\tUtils.type(Revision.class),\n\t\t\t\tUtils.type(UnapprovedQuestion.class),\n\t\t\t\tUtils.type(UnapprovedReply.class),\n\t\t\t\t// Para core types\n\t\t\t\tUtils.type(Address.class),\n\t\t\t\tUtils.type(Sysprop.class),\n\t\t\t\tUtils.type(Tag.class),\n\t\t\t\tUtils.type(User.class),\n\t\t\t\tUtils.type(Vote.class)\n\t\t));\n\n\t\tHOOK_EVENTS = new HashSet<>(Arrays.asList(\n\t\t\t\t\"question.create\",\n\t\t\t\t\"question.close\",\n\t\t\t\t\"answer.create\",\n\t\t\t\t\"answer.accept\",\n\t\t\t\t\"report.create\",\n\t\t\t\t\"comment.create\",\n\t\t\t\t\"user.signup\",\n\t\t\t\t\"revision.restore\"));\n\n\t\tWHITELISTED_MACROS = new HashMap<String, String>();\n\t\tWHITELISTED_MACROS.put(\"spaces\", \"#spacespage($spaces)\");\n\t\tWHITELISTED_MACROS.put(\"webhooks\", \"#webhookspage($webhooks)\");\n\t\tWHITELISTED_MACROS.put(\"comments\", \"#commentspage($commentslist)\");\n\t\tWHITELISTED_MACROS.put(\"simplecomments\", \"#simplecommentspage($commentslist)\");\n\t\tWHITELISTED_MACROS.put(\"postcomments\", \"#commentspage($showpost.comments)\");\n\t\tWHITELISTED_MACROS.put(\"replies\", \"#answerspage($answerslist $showPost)\");\n\t\tWHITELISTED_MACROS.put(\"feedback\", \"#questionspage($feedbacklist)\");\n\t\tWHITELISTED_MACROS.put(\"people\", \"#peoplepage($userlist)\");\n\t\tWHITELISTED_MACROS.put(\"questions\", \"#questionspage($questionslist)\");\n\t\tWHITELISTED_MACROS.put(\"compactanswers\", \"#compactanswerspage($answerslist)\");\n\t\tWHITELISTED_MACROS.put(\"answers\", \"#answerspage($answerslist)\");\n\t\tWHITELISTED_MACROS.put(\"reports\", \"#reportspage($reportslist)\");\n\t\tWHITELISTED_MACROS.put(\"revisions\", \"#revisionspage($revisionslist $showPost)\");\n\t\tWHITELISTED_MACROS.put(\"tags\", \"#tagspage($tagslist)\");\n\t}\n\n\tprivate final ParaClient pc;\n\tprivate final LanguageUtils langutils;\n\tprivate final AvatarRepository avatarRepository;\n\tprivate final GravatarAvatarGenerator gravatarAvatarGenerator;\n\tprivate static ScooldUtils instance;\n\tprivate Sysprop customTheme;\n\t@Inject private Emailer emailer;\n\n\t@Inject\n\tpublic ScooldUtils(ParaClient pc, LanguageUtils langutils, AvatarRepositoryProxy avatarRepository,\n\t\t\tGravatarAvatarGenerator gravatarAvatarGenerator) {\n\t\tthis.pc = pc;\n\t\tthis.langutils = langutils;\n\t\tthis.avatarRepository = avatarRepository;\n\t\tthis.gravatarAvatarGenerator = gravatarAvatarGenerator;\n\t\tAPI_USER.setPicture(avatarRepository.getAnonymizedLink(CONF.supportEmail()));\n\t}\n\n\tpublic ParaClient getParaClient() {\n\t\treturn pc;\n\t}\n\n\tpublic LanguageUtils getLangutils() {\n\t\treturn langutils;\n\t}\n\n\tpublic static ScooldUtils getInstance() {\n\t\treturn instance;\n\t}\n\n\tstatic void setInstance(ScooldUtils instance) {\n\t\tScooldUtils.instance = instance;\n\t}\n\n\tpublic static ScooldConfig getConfig() {\n\t\treturn CONF;\n\t}\n\n\tstatic {\n\t\t// multiple domains/admins are allowed only in Scoold PRO\n\t\tString approvedDomain = StringUtils.substringBefore(CONF.approvedDomainsForSignups(), \",\");\n\t\tif (!StringUtils.isBlank(approvedDomain)) {\n\t\t\tAPPROVED_DOMAINS.add(approvedDomain);\n\t\t}\n\t\t// multiple admins are allowed only in Scoold PRO\n\t\tString admin = StringUtils.substringBefore(CONF.admins(), \",\");\n\t\tif (!StringUtils.isBlank(admin)) {\n\t\t\tADMINS.add(admin);\n\t\t}\n\t}\n\n\tpublic static void tryConnectToPara(Callable<Boolean> callable) {\n\t\tretryConnection(callable, 0);\n\t}\n\n\tprivate static void retryConnection(Callable<Boolean> callable, int retryCount) {\n\t\ttry {\n\t\t\tif (!callable.call()) {\n\t\t\t\tthrow new Exception();\n\t\t\t} else if (retryCount > 0) {\n\t\t\t\tlogger.info(\"Connected to Para backend.\");\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tint maxRetries = CONF.paraConnectionRetryAttempts();\n\t\t\tint retryInterval = CONF.paraConnectionRetryIntervalSec();\n\t\t\tint count = ++retryCount;\n\t\t\tlogger.error(\"No connection to Para backend. Retrying connection in {}s (attempt {} of {})...\",\n\t\t\t\t\tretryInterval, count, maxRetries);\n\t\t\tif (maxRetries < 0 || retryCount < maxRetries) {\n\t\t\t\tPara.asyncExecute(new Runnable() {\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tThread.sleep(retryInterval * 1000L);\n\t\t\t\t\t\t} catch (InterruptedException ex) {\n\t\t\t\t\t\t\tlogger.error(null, ex);\n\t\t\t\t\t\t\tThread.currentThread().interrupt();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tretryConnection(callable, count);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic ParaObject checkAuth(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {\n\t\tProfile authUser = null;\n\t\tString jwt = HttpUtils.getStateParam(CONF.authCookie(), req);\n\t\tif (isApiRequest(req)) {\n\t\t\treturn checkApiAuth(req);\n\t\t} else if (jwt != null && !StringUtils.endsWithAny(req.getRequestURI(),\n\t\t\t\t\".js\", \".css\", \".svg\", \".png\", \".jpg\", \".ico\", \".gif\", \".woff2\", \".woff\", \"people/avatar\")) {\n\t\t\tUser u = pc.me(jwt);\n\t\t\tif (u != null && isEmailDomainApproved(u.getEmail())) {\n\t\t\t\tauthUser = getOrCreateProfile(u, req);\n\t\t\t\tauthUser.setUser(u);\n\t\t\t\tauthUser.setOriginalPicture(u.getPicture());\n\t\t\t\tboolean updatedRank = promoteOrDemoteUser(authUser, u);\n\t\t\t\tboolean updatedProfile = updateProfilePictureAndName(authUser, u);\n\t\t\t\tif (updatedRank || updatedProfile) {\n\t\t\t\t\tauthUser.update();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tclearSession(req, res);\n\t\t\t\tlogger.info(\"Invalid JWT found in cookie {}.\", CONF.authCookie());\n\t\t\t\tres.sendRedirect(CONF.serverUrl() + CONF.serverContextPath() + SIGNINLINK + \"?code=3&error=true\");\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\treturn authUser;\n\t}\n\n\tprivate ParaObject checkApiAuth(HttpServletRequest req) {\n\t\tif (req.getRequestURI().equals(CONF.serverContextPath() + \"/api\")) {\n\t\t\treturn null;\n\t\t}\n\t\tString apiKeyJWT = StringUtils.removeStart(req.getHeader(HttpHeaders.AUTHORIZATION), \"Bearer \");\n\t\tif (req.getRequestURI().equals(CONF.serverContextPath() + \"/api/ping\")) {\n\t\t\treturn API_USER;\n\t\t} else if (req.getRequestURI().equals(CONF.serverContextPath() + \"/api/stats\") && isValidJWToken(apiKeyJWT)) {\n\t\t\treturn API_USER;\n\t\t} else if (!isApiEnabled() || StringUtils.isBlank(apiKeyJWT) || !isValidJWToken(apiKeyJWT)) {\n\t\t\tthrow new UnauthorizedException();\n\t\t}\n\t\treturn API_USER;\n\t}\n\n\tprivate boolean promoteOrDemoteUser(Profile authUser, User u) {\n\t\tif (authUser != null) {\n\t\t\tif (!isAdmin(authUser) && isRecognizedAsAdmin(u)) {\n\t\t\t\tlogger.info(\"User '{}' with id={} promoted to admin.\", u.getName(), authUser.getId());\n\t\t\t\tauthUser.setGroups(User.Groups.ADMINS.toString());\n\t\t\t\treturn true;\n\t\t\t} else if (isAdmin(authUser) && !isRecognizedAsAdmin(u)) {\n\t\t\t\tlogger.info(\"User '{}' with id={} demoted to regular user.\", u.getName(), authUser.getId());\n\t\t\t\tauthUser.setGroups(User.Groups.USERS.toString());\n\t\t\t\treturn true;\n\t\t\t} else if (!isMod(authUser) && u.isModerator()) {\n\t\t\t\tauthUser.setGroups(User.Groups.MODS.toString());\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate Profile getOrCreateProfile(User u, HttpServletRequest req) {\n\t\tProfile authUser = pc.read(Profile.id(u.getId()));\n\t\tif (authUser == null) {\n\t\t\tauthUser = Profile.fromUser(u);\n\t\t\tauthUser.create();\n\t\t\tif (!u.getIdentityProvider().equals(\"generic\")) {\n\t\t\t\tsendWelcomeEmail(u, false, req);\n\t\t\t}\n\t\t\tMap<String, Object> payload = new LinkedHashMap<>(ParaObjectUtils.getAnnotatedFields(authUser, false));\n\t\t\tpayload.put(\"user\", u);\n\t\t\ttriggerHookEvent(\"user.signup\", payload);\n\t\t\tlogger.info(\"Created new user '{}' with id={}, groups={}, spaces={}.\",\n\t\t\t\t\tu.getName(), authUser.getId(), authUser.getGroups(), authUser.getSpaces());\n\t\t}\n\t\treturn authUser;\n\t}\n\n\tprivate boolean updateProfilePictureAndName(Profile authUser, User u) {\n\t\tboolean update = false;\n\t\tif (!StringUtils.equals(u.getPicture(), authUser.getPicture())\n\t\t\t\t&& !gravatarAvatarGenerator.isLink(authUser.getPicture())\n\t\t\t\t&& !CONF.avatarEditsEnabled()) {\n\t\t\tauthUser.setPicture(u.getPicture());\n\t\t\tupdate = true;\n\t\t}\n\t\tif (!CONF.nameEditsEnabled() &&\t!StringUtils.equals(u.getName(), authUser.getName())) {\n\t\t\tauthUser.setName(u.getName());\n\t\t\tupdate = true;\n\t\t}\n\t\tif (!StringUtils.equals(u.getName(), authUser.getOriginalName())) {\n\t\t\tauthUser.setOriginalName(u.getName());\n\t\t\tupdate = true;\n\t\t}\n\t\treturn update;\n\t}\n\n\tpublic boolean isDarkModeEnabled(Profile authUser, HttpServletRequest req) {\n\t\treturn (authUser != null && authUser.getDarkmodeEnabled()) ||\n\t\t\t\t\"1\".equals(HttpUtils.getCookieValue(req, \"dark-mode\"));\n\t}\n\n\tprivate String getDefaultEmailSignature(String defaultText) {\n\t\tString template = CONF.emailsDefaultSignatureText(defaultText);\n\t\treturn Utils.formatMessage(template, CONF.appName());\n\t}\n\n\tpublic void sendWelcomeEmail(User user, boolean verifyEmail, HttpServletRequest req) {\n\t\t// send welcome email notification\n\t\tif (user != null) {\n\t\t\tMap<String, Object> model = new HashMap<String, Object>();\n\t\t\tMap<String, String> lang = getLang(req);\n\t\t\tString subject = Utils.formatMessage(lang.get(\"signin.welcome\"), CONF.appName());\n\t\t\tString body1 = Utils.formatMessage(CONF.emailsWelcomeText1(lang), CONF.appName());\n\t\t\tString body2 = CONF.emailsWelcomeText2(lang);\n\t\t\tString body3 = getDefaultEmailSignature(CONF.emailsWelcomeText3(lang));\n\n\t\t\tif (verifyEmail && !user.getActive() && !StringUtils.isBlank(user.getIdentifier())) {\n\t\t\t\tSysprop s = pc.read(user.getIdentifier());\n\t\t\t\tif (s != null) {\n\t\t\t\t\tString token = Utils.base64encURL(Utils.generateSecurityToken().getBytes());\n\t\t\t\t\ts.addProperty(Config._EMAIL_TOKEN, token);\n\t\t\t\t\tpc.update(s);\n\t\t\t\t\ttoken = CONF.serverUrl() + CONF.serverContextPath() + SIGNINLINK + \"/register?id=\" + user.getId() + \"&token=\" + token;\n\t\t\t\t\tbody3 = \"<b><a href=\\\"\" + token + \"\\\">\" + lang.get(\"signin.welcome.verify\") + \"</a></b><br><br>\" + body3;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmodel.put(\"subject\", escapeHtml(subject));\n\t\t\tmodel.put(\"logourl\", getSmallLogoUrl());\n\t\t\tmodel.put(\"heading\", Utils.formatMessage(lang.get(\"signin.welcome.title\"), escapeHtml(user.getName())));\n\t\t\tmodel.put(\"body\", body1 + body2 + body3);\n\t\t\temailer.sendEmail(Arrays.asList(user.getEmail()), subject, compileEmailTemplate(model));\n\t\t}\n\t}\n\n\tpublic void sendVerificationEmail(Sysprop identifier, HttpServletRequest req) {\n\t\tif (identifier != null) {\n\t\t\tMap<String, Object> model = new HashMap<String, Object>();\n\t\t\tMap<String, String> lang = getLang(req);\n\t\t\tString subject = Utils.formatMessage(lang.get(\"signin.welcome\"), CONF.appName());\n\t\t\tString body = getDefaultEmailSignature(CONF.emailsWelcomeText3(lang));\n\n\t\t\tString token = Utils.base64encURL(Utils.generateSecurityToken().getBytes());\n\t\t\tidentifier.addProperty(Config._EMAIL_TOKEN, token);\n\t\t\tidentifier.addProperty(\"confirmationTimestamp\", Utils.timestamp());\n\t\t\tpc.update(identifier);\n\t\t\ttoken = CONF.serverUrl() + CONF.serverContextPath() + SIGNINLINK + \"/register?id=\" +\n\t\t\t\t\tidentifier.getCreatorid() + \"&token=\" + token;\n\t\t\tbody = \"<b><a href=\\\"\" + token + \"\\\">\" + lang.get(\"signin.welcome.verify\") + \"</a></b><br><br>\" + body;\n\n\t\t\tmodel.put(\"subject\", escapeHtml(subject));\n\t\t\tmodel.put(\"logourl\", getSmallLogoUrl());\n\t\t\tmodel.put(\"heading\", lang.get(\"hello\"));\n\t\t\tmodel.put(\"body\", body);\n\t\t\temailer.sendEmail(Arrays.asList(identifier.getId()), subject, compileEmailTemplate(model));\n\t\t}\n\t}\n\n\tpublic void sendPasswordResetEmail(String email, String token, HttpServletRequest req) {\n\t\tif (email != null && token != null) {\n\t\t\tMap<String, Object> model = new HashMap<String, Object>();\n\t\t\tMap<String, String> lang = getLang(req);\n\t\t\tString url = CONF.serverUrl() + CONF.serverContextPath() + SIGNINLINK + \"/iforgot?email=\" + email + \"&token=\" + token;\n\t\t\tString subject = lang.get(\"iforgot.title\");\n\t\t\tString body1 = lang.get(\"notification.iforgot.body1\") + \"<br><br>\";\n\t\t\tString body2 = Utils.formatMessage(\"<b><a href=\\\"{0}\\\">\" + lang.get(\"notification.iforgot.body2\") +\n\t\t\t\t\t\"</a></b><br><br>\", url);\n\t\t\tString body3 = getDefaultEmailSignature(lang.get(\"notification.signature\") + \"<br><br>\");\n\n\t\t\tmodel.put(\"subject\", escapeHtml(subject));\n\t\t\tmodel.put(\"logourl\", getSmallLogoUrl());\n\t\t\tmodel.put(\"heading\", lang.get(\"hello\"));\n\t\t\tmodel.put(\"body\", body1 + body2 + body3);\n\t\t\temailer.sendEmail(Arrays.asList(email), subject, compileEmailTemplate(model));\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic void subscribeToNotifications(String email, String channelId) {\n\t\tif (!StringUtils.isBlank(email) && !StringUtils.isBlank(channelId)) {\n\t\t\tSysprop s = pc.read(channelId);\n\t\t\tif (s == null || !s.hasProperty(\"emails\")) {\n\t\t\t\ts = new Sysprop(channelId);\n\t\t\t\ts.addProperty(\"emails\", new LinkedList<>());\n\t\t\t}\n\t\t\tSet<String> emails = new HashSet<>((List<String>) s.getProperty(\"emails\"));\n\t\t\tif (emails.add(email)) {\n\t\t\t\ts.addProperty(\"emails\", emails);\n\t\t\t\tpc.create(s);\n\t\t\t}\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic void unsubscribeFromNotifications(String email, String channelId) {\n\t\tif (!StringUtils.isBlank(email) && !StringUtils.isBlank(channelId)) {\n\t\t\tSysprop s = pc.read(channelId);\n\t\t\tif (s == null || !s.hasProperty(\"emails\")) {\n\t\t\t\ts = new Sysprop(channelId);\n\t\t\t\ts.addProperty(\"emails\", new LinkedList<>());\n\t\t\t}\n\t\t\tSet<String> emails = new HashSet<>((List<String>) s.getProperty(\"emails\"));\n\t\t\tif (emails.remove(email)) {\n\t\t\t\ts.addProperty(\"emails\", emails);\n\t\t\t\tpc.create(s);\n\t\t\t}\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Set<String> getNotificationSubscribers(String channelId) {\n\t\treturn ((List<String>) Optional.ofNullable(((Sysprop) pc.read(channelId))).\n\t\t\t\torElse(new Sysprop()).getProperties().getOrDefault(\"emails\", Collections.emptyList())).\n\t\t\t\tstream().collect(Collectors.toSet());\n\t}\n\n\tpublic void unsubscribeFromAllNotifications(Profile p) {\n\t\tUser u = p.getUser();\n\t\tif (u != null) {\n\t\t\tunsubscribeFromNewPosts(u);\n\t\t}\n\t}\n\n\tpublic boolean isEmailDomainApproved(String email) {\n\t\tif (StringUtils.isBlank(email)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!APPROVED_DOMAINS.isEmpty() && !APPROVED_DOMAINS.contains(StringUtils.substringAfter(email, \"@\"))) {\n\t\t\tlogger.warn(\"Attempted signin from an unknown domain - email {} is part of an unapproved domain.\", email);\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic Object isSubscribedToNewPosts(HttpServletRequest req) {\n\t\tif (!isNewPostNotificationAllowed()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tProfile authUser = getAuthUser(req);\n\t\tif (authUser != null) {\n\t\t\tUser u = authUser.getUser();\n\t\t\tif (u != null) {\n\t\t\t\treturn getNotificationSubscribers(EMAIL_ALERTS_PREFIX + \"new_post_subscribers\").contains(u.getEmail());\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic void subscribeToNewPosts(User u) {\n\t\tif (u != null) {\n\t\t\tsubscribeToNotifications(u.getEmail(), EMAIL_ALERTS_PREFIX + \"new_post_subscribers\");\n\t\t}\n\t}\n\n\tpublic void unsubscribeFromNewPosts(User u) {\n\t\tif (u != null) {\n\t\t\tunsubscribeFromNotifications(u.getEmail(), EMAIL_ALERTS_PREFIX + \"new_post_subscribers\");\n\t\t}\n\t}\n\n\tprivate Map<String, Profile> buildProfilesMap(List<User> users) {\n\t\tif (users != null && !users.isEmpty()) {\n\t\t\tMap<String, User> userz = users.stream().collect(Collectors.toMap(u -> u.getId(), u -> u));\n\t\t\tList<Profile> profiles = pc.readAll(userz.keySet().stream().\n\t\t\t\t\tmap(uid -> Profile.id(uid)).collect(Collectors.toList()));\n\t\t\tMap<String, Profile> profilesMap = new HashMap<String, Profile>(users.size());\n\t\t\tprofiles.forEach(pr -> profilesMap.put(userz.get(pr.getCreatorid()).getEmail(), pr));\n\t\t\treturn profilesMap;\n\t\t}\n\t\treturn Collections.emptyMap();\n\t}\n\n\tprivate void sendEmailsToSubscribersInSpace(Set<String> emails, String space, String subject, String html) {\n\t\tint i = 0;\n\t\tint max = CONF.maxItemsPerPage();\n\t\tList<String> terms = new ArrayList<>(max);\n\t\tfor (String email : emails) {\n\t\t\tterms.add(email);\n\t\t\tif (++i == max) {\n\t\t\t\temailer.sendEmail(buildProfilesMap(pc.findTermInList(Utils.type(User.class), Config._EMAIL, terms)).\n\t\t\t\t\t\tentrySet().stream().filter(e -> canAccessSpace(e.getValue(), space) &&\n\t\t\t\t\t\t\t\t!isIgnoredSpaceForNotifications(e.getValue(), space)).\n\t\t\t\t\t\tmap(e -> e.getKey()).collect(Collectors.toList()), subject, html);\n\t\t\t\ti = 0;\n\t\t\t\tterms.clear();\n\t\t\t}\n\t\t}\n\t\tif (!terms.isEmpty()) {\n\t\t\temailer.sendEmail(buildProfilesMap(pc.findTermInList(Utils.type(User.class), Config._EMAIL, terms)).\n\t\t\t\t\tentrySet().stream().filter(e -> canAccessSpace(e.getValue(), space) &&\n\t\t\t\t\t\t\t!isIgnoredSpaceForNotifications(e.getValue(), space)).\n\t\t\t\t\tmap(e -> e.getKey()).collect(Collectors.toList()), subject, html);\n\t\t}\n\t}\n\n\tprivate Set<String> getFavTagsSubscribers(List<String> tags) {\n\t\tif (!tags.isEmpty()) {\n\t\t\tSet<String> emails = new LinkedHashSet<>();\n\t\t\t// find all user objects even if there are more than 10000 users in the system\n\t\t\tPager pager = new Pager(1, \"_docid\", false, CONF.maxItemsPerPage());\n\t\t\tList<Profile> profiles;\n\t\t\tdo {\n\t\t\t\tprofiles = pc.findQuery(Utils.type(Profile.class),\n\t\t\t\t\t\t\"properties.favtags:(\" + tags.stream().\n\t\t\t\t\t\t\t\tmap(t -> \"\\\"\".concat(t).concat(\"\\\"\")).distinct().\n\t\t\t\t\t\t\t\tcollect(Collectors.joining(\" \")) + \") AND properties.favtagsEmailsEnabled:true\", pager);\n\t\t\t\tif (!profiles.isEmpty()) {\n\t\t\t\t\tList<User> users = pc.readAll(profiles.stream().map(p -> p.getCreatorid()).\n\t\t\t\t\t\t\tdistinct().collect(Collectors.toList()));\n\n\t\t\t\t\tusers.stream().forEach(u -> emails.add(u.getEmail()));\n\t\t\t\t}\n\t\t\t} while (!profiles.isEmpty());\n\t\t\treturn emails;\n\t\t}\n\t\treturn Collections.emptySet();\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic void sendUpdatedFavTagsNotifications(Post question, List<String> addedTags, HttpServletRequest req) {\n\t\tif (!isFavTagsNotificationAllowed()) {\n\t\t\treturn;\n\t\t}\n\t\t// sends a notification to subscibers of a tag if that tag was added to an existing question\n\t\tif (question != null && !question.isReply() && addedTags != null && !addedTags.isEmpty()) {\n\t\t\tProfile postAuthor = question.getAuthor(); // the current user - same as utils.getAuthUser(req)\n\t\t\tMap<String, Object> model = new HashMap<String, Object>();\n\t\t\tMap<String, String> lang = getLang(req);\n\t\t\tString name = postAuthor.getName();\n\t\t\tString body = Utils.markdownToHtml(question.getBody());\n\t\t\tString picture = Utils.formatMessage(\"<img src='{0}' width='25'>\", escapeHtmlAttribute(avatarRepository.\n\t\t\t\t\tgetLink(postAuthor, AvatarFormat.Square25)));\n\t\t\tString postURL = CONF.serverUrl() + question.getPostLink(false, false);\n\t\t\tString tagsString = Optional.ofNullable(question.getTags()).orElse(Collections.emptyList()).stream().\n\t\t\t\t\tmap(t -> \"<span class=\\\"tag\\\">\" +\n\t\t\t\t\t\t\t(addedTags.contains(t) ? \"<b>\" + escapeHtml(t) + \"<b>\" : escapeHtml(t)) + \"</span>\").\n\t\t\t\t\tcollect(Collectors.joining(\"&nbsp;\"));\n\t\t\tString subject = Utils.formatMessage(lang.get(\"notification.favtags.subject\"), name,\n\t\t\t\t\tUtils.abbreviate(question.getTitle(), 255));\n\t\t\tmodel.put(\"subject\", escapeHtml(subject));\n\t\t\tmodel.put(\"logourl\", getSmallLogoUrl());\n\t\t\tmodel.put(\"heading\", Utils.formatMessage(lang.get(\"notification.favtags.heading\"), picture, escapeHtml(name)));\n\t\t\tmodel.put(\"body\", Utils.formatMessage(\"<h2><a href='{0}'>{1}</a></h2><div>{2}</div><br>{3}\",\n\t\t\t\t\tpostURL, escapeHtml(question.getTitle()), body, tagsString));\n\n\t\t\tSet<String> emails = getFavTagsSubscribers(addedTags);\n\t\t\tsendEmailsToSubscribersInSpace(emails, question.getSpace(), subject, compileEmailTemplate(model));\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic void sendNewPostNotifications(Post question, HttpServletRequest req) {\n\t\tif (question == null) {\n\t\t\treturn;\n\t\t}\n\t\t// the current user - same as utils.getAuthUser(req)\n\t\tProfile postAuthor = question.getAuthor() != null ? question.getAuthor() : pc.read(question.getCreatorid());\n\t\tif (!question.getType().equals(Utils.type(UnapprovedQuestion.class))) {\n\t\t\tif (!isNewPostNotificationAllowed()) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tMap<String, Object> model = new HashMap<String, Object>();\n\t\t\tMap<String, String> lang = getLang(req);\n\t\t\tString name = postAuthor.getName();\n\t\t\tString body = Utils.markdownToHtml(question.getBody());\n\t\t\tString picture = Utils.formatMessage(\"<img src='{0}' width='25'>\", escapeHtmlAttribute(avatarRepository.\n\t\t\t\t\tgetLink(postAuthor, AvatarFormat.Square25)));\n\t\t\tString postURL = CONF.serverUrl() + question.getPostLink(false, false);\n\t\t\tString tagsString = Optional.ofNullable(question.getTags()).orElse(Collections.emptyList()).stream().\n\t\t\t\t\tmap(t -> \"<span class=\\\"tag\\\">\" + escapeHtml(t) + \"</span>\").\n\t\t\t\t\tcollect(Collectors.joining(\"&nbsp;\"));\n\t\t\tString subject = Utils.formatMessage(lang.get(\"notification.newposts.subject\"), name,\n\t\t\t\t\tUtils.abbreviate(question.getTitle(), 255));\n\t\t\tmodel.put(\"subject\", escapeHtml(subject));\n\t\t\tmodel.put(\"logourl\", getSmallLogoUrl());\n\t\t\tmodel.put(\"heading\", Utils.formatMessage(lang.get(\"notification.newposts.heading\"), picture, escapeHtml(name)));\n\t\t\tmodel.put(\"body\", Utils.formatMessage(\"<h2><a href='{0}'>{1}</a></h2><div>{2}</div><br>{3}\",\n\t\t\t\t\tpostURL, escapeHtml(question.getTitle()), body, tagsString));\n\n\t\t\tSet<String> emails = new HashSet<String>(getNotificationSubscribers(EMAIL_ALERTS_PREFIX + \"new_post_subscribers\"));\n\t\t\temails.addAll(getFavTagsSubscribers(question.getTags()));\n\t\t\tsendEmailsToSubscribersInSpace(emails, question.getSpace(), subject, compileEmailTemplate(model));\n\t\t} else if (postsNeedApproval() && question instanceof UnapprovedQuestion) {\n\t\t\tReport rep = new Report();\n\t\t\trep.setDescription(\"New question awaiting approval\");\n\t\t\trep.setSubType(Report.ReportType.OTHER);\n\t\t\trep.setLink(question.getPostLink(false, false));\n\t\t\trep.setAuthorName(postAuthor.getName());\n\t\t\trep.create();\n\t\t}\n\t}\n\n\tpublic void sendReplyNotifications(Post parentPost, Post reply, HttpServletRequest req) {\n\t\t// send email notification to author of post except when the reply is by the same person\n\t\tif (parentPost != null && reply != null && !StringUtils.equals(parentPost.getCreatorid(), reply.getCreatorid())) {\n\t\t\tProfile replyAuthor = reply.getAuthor(); // the current user - same as utils.getAuthUser(req)\n\t\t\tMap<String, Object> model = new HashMap<String, Object>();\n\t\t\tMap<String, String> lang = getLang(req);\n\t\t\tString name = replyAuthor.getName();\n\t\t\tString body = Utils.markdownToHtml(reply.getBody());\n\t\t\tString picture = Utils.formatMessage(\"<img src='{0}' width='25'>\", escapeHtmlAttribute(avatarRepository.\n\t\t\t\t\tgetLink(replyAuthor, AvatarFormat.Square25)));\n\t\t\tString postURL = CONF.serverUrl() + parentPost.getPostLink(false, false);\n\t\t\tString subject = Utils.formatMessage(lang.get(\"notification.reply.subject\"), name,\n\t\t\t\t\tUtils.abbreviate(reply.getTitle(), 255));\n\t\t\tmodel.put(\"subject\", escapeHtml(subject));\n\t\t\tmodel.put(\"logourl\", getSmallLogoUrl());\n\t\t\tmodel.put(\"heading\", Utils.formatMessage(lang.get(\"notification.reply.heading\"),\n\t\t\t\t\tUtils.formatMessage(\"<a href='{0}'>{1}</a>\", postURL, escapeHtml(parentPost.getTitle()))));\n\t\t\tmodel.put(\"body\", Utils.formatMessage(\"<h2>{0} {1}:</h2><div>{2}</div>\", picture, escapeHtml(name), body));\n\n\t\t\tProfile authorProfile = pc.read(parentPost.getCreatorid());\n\t\t\tif (authorProfile != null) {\n\t\t\t\tUser author = authorProfile.getUser();\n\t\t\t\tif (author != null) {\n\t\t\t\t\tif (authorProfile.getReplyEmailsEnabled()) {\n\t\t\t\t\t\tparentPost.addFollower(author);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (postsNeedApproval() && reply instanceof UnapprovedReply) {\n\t\t\t\tReport rep = new Report();\n\t\t\t\trep.setDescription(\"New reply awaiting approval\");\n\t\t\t\trep.setSubType(Report.ReportType.OTHER);\n\t\t\t\trep.setLink(parentPost.getPostLink(false, false) + \"#post-\" + reply.getId());\n\t\t\t\trep.setAuthorName(reply.getAuthor().getName());\n\t\t\t\trep.create();\n\t\t\t}\n\n\t\t\tif (isReplyNotificationAllowed() && parentPost.hasFollowers()) {\n\t\t\t\temailer.sendEmail(new ArrayList<String>(parentPost.getFollowers().values()),\n\t\t\t\t\t\tsubject,\n\t\t\t\t\t\tcompileEmailTemplate(model));\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void sendCommentNotifications(Post parentPost, Comment comment, Profile commentAuthor, HttpServletRequest req) {\n\t\t// send email notification to author of post except when the comment is by the same person\n\t\tif (parentPost != null && comment != null) {\n\t\t\tparentPost.setAuthor(pc.read(Profile.id(parentPost.getCreatorid()))); // parent author is not current user (authUser)\n\t\t\tMap<String, Object> payload = new LinkedHashMap<>(ParaObjectUtils.getAnnotatedFields(comment, false));\n\t\t\tpayload.put(\"parent\", parentPost);\n\t\t\tpayload.put(\"author\", commentAuthor);\n\t\t\ttriggerHookEvent(\"comment.create\", payload);\n\t\t\t// get the last 5-6 commentators who want to be notified - https://github.com/Erudika/scoold/issues/201\n\t\t\tPager p = new Pager(1, Config._TIMESTAMP, false, 5);\n\t\t\tboolean isCommentatorThePostAuthor = StringUtils.equals(parentPost.getCreatorid(), comment.getCreatorid());\n\t\t\tSet<String> last5ids = pc.findChildren(parentPost, Utils.type(Comment.class),\n\t\t\t\t\t\"!(\" + Config._CREATORID + \":\\\"\" + comment.getCreatorid() + \"\\\")\", p).\n\t\t\t\t\tstream().map(c -> c.getCreatorid()).distinct().collect(Collectors.toSet());\n\t\t\tif (!isCommentatorThePostAuthor && !last5ids.contains(parentPost.getCreatorid())) {\n\t\t\t\tlast5ids = new HashSet<>(last5ids);\n\t\t\t\tlast5ids.add(parentPost.getCreatorid());\n\t\t\t}\n\t\t\tMap<String, String> lang = getLang(req);\n\t\t\tList<Profile> last5commentators = pc.readAll(new ArrayList<>(last5ids));\n\t\t\tlast5commentators = last5commentators.stream().filter(u -> u.getCommentEmailsEnabled()).collect(Collectors.toList());\n\t\t\tpc.readAll(last5commentators.stream().map(u -> u.getCreatorid()).collect(Collectors.toList())).forEach(author -> {\n\t\t\t\tif (isCommentNotificationAllowed()) {\n\t\t\t\t\tMap<String, Object> model = new HashMap<String, Object>();\n\t\t\t\t\tString name = commentAuthor.getName();\n\t\t\t\t\tString body = Utils.markdownToHtml(comment.getComment());\n\t\t\t\t\tString pic = Utils.formatMessage(\"<img src='{0}' width='25'>\",\n\t\t\t\t\t\tescapeHtmlAttribute(avatarRepository.getLink(commentAuthor, AvatarFormat.Square25)));\n\t\t\t\t\tString postURL = CONF.serverUrl() + parentPost.getPostLink(false, false);\n\t\t\t\t\tString subject = Utils.formatMessage(lang.get(\"notification.comment.subject\"), name, parentPost.getTitle());\n\t\t\t\t\tmodel.put(\"subject\", escapeHtml(subject));\n\t\t\t\t\tmodel.put(\"logourl\", getSmallLogoUrl());\n\t\t\t\t\tmodel.put(\"heading\", Utils.formatMessage(lang.get(\"notification.comment.heading\"),\n\t\t\t\t\t\t\tUtils.formatMessage(\"<a href='{0}'>{1}</a>\", postURL, escapeHtml(parentPost.getTitle()))));\n\t\t\t\t\tmodel.put(\"body\", Utils.formatMessage(\"<h2>{0} {1}:</h2><div class='panel'>{2}</div>\", pic, escapeHtml(name), body));\n\t\t\t\t\temailer.sendEmail(Arrays.asList(((User) author).getEmail()), subject, compileEmailTemplate(model));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate String escapeHtmlAttribute(String value) {\n\t\treturn StringUtils.trimToEmpty(value)\n\t\t\t\t.replaceAll(\"'\", \"%27\")\n\t\t\t\t.replaceAll(\"\\\"\", \"%22\")\n\t\t\t\t.replaceAll(\"\\\\\\\\\", \"\");\n\t}\n\n\tprivate String escapeHtml(String value) {\n\t\treturn StringEscapeUtils.escapeHtml4(value);\n\t}\n\n\tpublic Profile readAuthUser(HttpServletRequest req) {\n\t\tProfile authUser = null;\n\t\tUser u = pc.me(HttpUtils.getStateParam(CONF.authCookie(), req));\n\t\tif (u != null && isEmailDomainApproved(u.getEmail())) {\n\t\t\treturn getOrCreateProfile(u, req);\n\t\t}\n\t\treturn authUser;\n\t}\n\n\tpublic Profile getAuthUser(HttpServletRequest req) {\n\t\treturn (Profile) req.getAttribute(AUTH_USER_ATTRIBUTE);\n\t}\n\n\tpublic boolean isAuthenticated(HttpServletRequest req) {\n\t\treturn getAuthUser(req) != null;\n\t}\n\n\tpublic boolean isFeedbackEnabled() {\n\t\treturn CONF.feedbackEnabled();\n\t}\n\n\tpublic boolean isNearMeFeatureEnabled() {\n\t\treturn CONF.postsNearMeEnabled();\n\t}\n\n\tpublic boolean isDefaultSpacePublic() {\n\t\treturn CONF.isDefaultSpacePublic();\n\t}\n\n\tpublic boolean isWebhooksEnabled() {\n\t\treturn CONF.webhooksEnabled();\n\t}\n\n\tpublic boolean isAnonymityEnabled() {\n\t\treturn CONF.profileAnonimityEnabled();\n\t}\n\n\tpublic boolean isApiEnabled() {\n\t\treturn CONF.apiEnabled();\n\t}\n\n\tpublic boolean isFooterLinksEnabled() {\n\t\treturn CONF.footerLinksEnabled();\n\t}\n\n\tpublic boolean isNotificationsAllowed() {\n\t\treturn CONF.notificationEmailsAllowed();\n\t}\n\n\tpublic boolean isNewPostNotificationAllowed() {\n\t\treturn isNotificationsAllowed() && CONF.emailsForNewPostsAllowed();\n\t}\n\n\tpublic boolean isFavTagsNotificationAllowed() {\n\t\treturn isNotificationsAllowed() && CONF.emailsForFavtagsAllowed();\n\t}\n\n\tpublic boolean isReplyNotificationAllowed() {\n\t\treturn isNotificationsAllowed() && CONF.emailsForRepliesAllowed();\n\t}\n\n\tpublic boolean isCommentNotificationAllowed() {\n\t\treturn isNotificationsAllowed() && CONF.emailsForCommentsAllowed();\n\t}\n\n\tpublic boolean isDarkModeEnabled() {\n\t\treturn CONF.darkModeEnabled();\n\t}\n\n\tpublic boolean isSlackAuthEnabled() {\n\t\treturn CONF.slackAuthEnabled();\n\t}\n\n\tpublic static boolean isGravatarEnabled() {\n\t\treturn CONF.gravatarsEnabled();\n\t}\n\n\tpublic static String gravatarPattern() {\n\t\treturn CONF.gravatarsPattern();\n\t}\n\n\tpublic static String getDefaultAvatar() {\n\t\treturn CONF.imagesLink() + \"/anon.svg\";\n\t}\n\n\tpublic static boolean isAvatarUploadsEnabled() {\n\t\treturn isImgurAvatarRepositoryEnabled();\n\t}\n\n\tpublic static boolean isImgurAvatarRepositoryEnabled() {\n\t\treturn !StringUtils.isBlank(CONF.imgurClientId()) && \"imgur\".equalsIgnoreCase(CONF.avatarRepository());\n\t}\n\n\tpublic String getFooterHTML() {\n\t\treturn CONF.footerHtml();\n\t}\n\n\tpublic boolean isNavbarLink1Enabled() {\n\t\treturn !StringUtils.isBlank(getNavbarLink1URL());\n\t}\n\n\tpublic String getNavbarLink1URL() {\n\t\treturn CONF.navbarCustomLink1Url();\n\t}\n\n\tpublic String getNavbarLink1Text() {\n\t\treturn CONF.navbarCustomLink1Text();\n\t}\n\n\tpublic boolean isNavbarLink2Enabled() {\n\t\treturn !StringUtils.isBlank(getNavbarLink2URL());\n\t}\n\n\tpublic String getNavbarLink2URL() {\n\t\treturn CONF.navbarCustomLink2Url();\n\t}\n\n\tpublic String getNavbarLink2Text() {\n\t\treturn CONF.navbarCustomLink2Text();\n\t}\n\n\tpublic boolean isNavbarMenuLink1Enabled() {\n\t\treturn !StringUtils.isBlank(getNavbarMenuLink1URL());\n\t}\n\n\tpublic String getNavbarMenuLink1URL() {\n\t\treturn CONF.navbarCustomMenuLink1Url();\n\t}\n\n\tpublic String getNavbarMenuLink1Text() {\n\t\treturn CONF.navbarCustomMenuLink1Text();\n\t}\n\n\tpublic boolean isNavbarMenuLink2Enabled() {\n\t\treturn !StringUtils.isBlank(getNavbarMenuLink2URL());\n\t}\n\n\tpublic String getNavbarMenuLink2URL() {\n\t\treturn CONF.navbarCustomMenuLink2Url();\n\t}\n\n\tpublic String getNavbarMenuLink2Text() {\n\t\treturn CONF.navbarCustomMenuLink2Text();\n\t}\n\n\tpublic boolean alwaysHideCommentForms() {\n\t\treturn CONF.alwaysHideCommentForms();\n\t}\n\n\tpublic Set<String> getCoreScooldTypes() {\n\t\treturn Collections.unmodifiableSet(CORE_TYPES);\n\t}\n\n\tpublic Set<String> getCustomHookEvents() {\n\t\treturn Collections.unmodifiableSet(HOOK_EVENTS);\n\t}\n\n\tpublic Pager getPager(String pageParamName, HttpServletRequest req) {\n\t\treturn pagerFromParams(pageParamName, req);\n\t}\n\n\tpublic Pager pagerFromParams(HttpServletRequest req) {\n\t\treturn pagerFromParams(\"page\", req);\n\t}\n\n\tpublic Pager pagerFromParams(String pageParamName, HttpServletRequest req) {\n\t\tPager p = new Pager(CONF.maxItemsPerPage());\n\t\tp.setPage(Math.min(NumberUtils.toLong(req.getParameter(pageParamName), 1), CONF.maxPages()));\n\t\tp.setLimit(NumberUtils.toInt(req.getParameter(\"limit\"), CONF.maxItemsPerPage()));\n\t\tString lastKey = req.getParameter(\"lastKey\");\n\t\tString sort = req.getParameter(\"sortby\");\n\t\tString desc = req.getParameter(\"desc\");\n\t\tif (!StringUtils.isBlank(desc)) {\n\t\t\tp.setDesc(Boolean.parseBoolean(desc));\n\t\t}\n\t\tif (!StringUtils.isBlank(lastKey)) {\n\t\t\tp.setLastKey(lastKey);\n\t\t}\n\t\tif (!StringUtils.isBlank(sort)) {\n\t\t\tp.setSortby(sort);\n\t\t}\n\t\treturn p;\n\t}\n\n\tpublic String getLanguageCode(HttpServletRequest req) {\n\t\tString langCodeFromConfig = CONF.defaultLanguageCode();\n\t\tString cookieLoc = getCookieValue(req, CONF.localeCookie());\n\t\tLocale fromReq = (req == null) ? Locale.getDefault() : req.getLocale();\n\t\tLocale requestLocale = langutils.getProperLocale(fromReq.toString());\n\t\treturn (cookieLoc != null) ? cookieLoc : (StringUtils.isBlank(langCodeFromConfig) ?\n\t\t\t\trequestLocale.getLanguage() : langutils.getProperLocale(langCodeFromConfig).getLanguage());\n\t}\n\n\tpublic Locale getCurrentLocale(String langname) {\n\t\tLocale currentLocale = langutils.getProperLocale(langname);\n\t\tif (currentLocale == null) {\n\t\t\tcurrentLocale = langutils.getProperLocale(langutils.getDefaultLanguageCode());\n\t\t}\n\t\treturn currentLocale;\n\t}\n\n\tpublic Map<String, String> getLang(HttpServletRequest req) {\n\t\treturn getLang(getCurrentLocale(getLanguageCode(req)));\n\t}\n\n\tpublic Map<String, String> getLang(Locale currentLocale) {\n\t\tMap<String, String> lang = langutils.readLanguage(currentLocale.toString());\n\t\tif (lang == null || lang.isEmpty()) {\n\t\t\tlang = langutils.getDefaultLanguage();\n\t\t}\n\t\treturn lang;\n\t}\n\n\tpublic boolean isLanguageRTL(String langCode) {\n\t\treturn StringUtils.equalsAnyIgnoreCase(langCode, \"ar\", \"he\", \"dv\", \"iw\", \"fa\", \"ps\", \"sd\", \"ug\", \"ur\", \"yi\");\n\t}\n\n\tpublic void fetchProfiles(List<? extends ParaObject> objects) {\n\t\tif (objects == null || objects.isEmpty()) {\n\t\t\treturn;\n\t\t}\n\t\tMap<String, String> authorids = new HashMap<String, String>(objects.size());\n\t\tMap<String, Profile> authors = new HashMap<String, Profile>(objects.size());\n\t\tfor (ParaObject obj : objects) {\n\t\t\tif (obj.getCreatorid() != null) {\n\t\t\t\tauthorids.put(obj.getId(), obj.getCreatorid());\n\t\t\t}\n\t\t}\n\t\tList<String> ids = new ArrayList<String>(new HashSet<String>(authorids.values()));\n\t\tif (ids.isEmpty()) {\n\t\t\treturn;\n\t\t}\n\t\t// read all post authors in batch\n\t\tfor (ParaObject author : pc.readAll(ids)) {\n\t\t\tauthors.put(author.getId(), (Profile) author);\n\t\t}\n\t\t// add system profile\n\t\tauthors.put(API_USER.getId(), API_USER);\n\t\t// set author object for each post\n\t\tfor (ParaObject obj : objects) {\n\t\t\tif (obj instanceof Post) {\n\t\t\t\t((Post) obj).setAuthor(authors.get(authorids.get(obj.getId())));\n\t\t\t} else if (obj instanceof Revision) {\n\t\t\t\t((Revision) obj).setAuthor(authors.get(authorids.get(obj.getId())));\n\t\t\t}\n\t\t}\n\t}\n\n\t//get the comments for each answer and the question\n\tpublic void getComments(List<Post> allPosts) {\n\t\tMap<String, List<Comment>> allComments = new HashMap<String, List<Comment>>();\n\t\tList<String> allCommentIds = new ArrayList<String>();\n\t\tList<Post> forUpdate = new ArrayList<Post>(allPosts.size());\n\t\t// get the comment ids of the first 5 comments for each post\n\t\tfor (Post post : allPosts) {\n\t\t\t// not set => read comments if any and embed ids in post object\n\t\t\tif (post.getCommentIds() == null) {\n\t\t\t\tforUpdate.add(reloadFirstPageOfComments(post));\n\t\t\t\tallComments.put(post.getId(), post.getComments());\n\t\t\t} else {\n\t\t\t\t// ids are set => add them to list for bulk read\n\t\t\t\tallCommentIds.addAll(post.getCommentIds());\n\t\t\t}\n\t\t}\n\t\tif (!allCommentIds.isEmpty()) {\n\t\t\t// read all comments for all posts on page in bulk\n\t\t\tfor (ParaObject comment : pc.readAll(allCommentIds)) {\n\t\t\t\tList<Comment> postComments = allComments.get(comment.getParentid());\n\t\t\t\tif (postComments == null) {\n\t\t\t\t\tallComments.put(comment.getParentid(), new ArrayList<Comment>());\n\t\t\t\t}\n\t\t\t\tallComments.get(comment.getParentid()).add((Comment) comment);\n\t\t\t}\n\t\t}\n\t\t// embed comments in each post for use within the view\n\t\tfor (Post post : allPosts) {\n\t\t\tList<Comment> cl = allComments.get(post.getId());\n\t\t\tlong clSize = (cl == null) ? 0 : cl.size();\n\t\t\tif (post.getCommentIds().size() != clSize) {\n\t\t\t\tforUpdate.add(reloadFirstPageOfComments(post));\n\t\t\t\tclSize = post.getComments().size();\n\t\t\t} else {\n\t\t\t\tpost.setComments(cl);\n\t\t\t\tif (clSize == post.getItemcount().getLimit() && pc.getCount(Utils.type(Comment.class),\n\t\t\t\t\t\tCollections.singletonMap(\"parentid\", post.getId())) > clSize) {\n\t\t\t\t\tclSize++; // hack to show the \"more\" button\n\t\t\t\t}\n\t\t\t}\n\t\t\tpost.getItemcount().setCount(clSize);\n\t\t}\n\t\tif (!forUpdate.isEmpty()) {\n\t\t\tpc.updateAll(allPosts);\n\t\t}\n\t}\n\n\tpublic Post reloadFirstPageOfComments(Post post) {\n\t\tList<Comment> commentz = pc.getChildren(post, Utils.type(Comment.class), post.getItemcount());\n\t\tArrayList<String> ids = new ArrayList<String>(commentz.size());\n\t\tfor (Comment comment : commentz) {\n\t\t\tids.add(comment.getId());\n\t\t}\n\t\tpost.setCommentIds(ids);\n\t\tpost.setComments(commentz);\n\t\treturn post;\n\t}\n\n\tpublic void updateViewCount(Post showPost, HttpServletRequest req, HttpServletResponse res) {\n\t\t//do not count views from author\n\t\tif (showPost != null && !isMine(showPost, getAuthUser(req))) {\n\t\t\tString postviews = StringUtils.trimToEmpty(HttpUtils.getStateParam(\"postviews\", req));\n\t\t\tif (!StringUtils.contains(postviews, showPost.getId())) {\n\t\t\t\tlong views = (showPost.getViewcount() == null) ? 0 : showPost.getViewcount();\n\t\t\t\tshowPost.setViewcount(views + 1); //increment count\n\t\t\t\tHttpUtils.setStateParam(\"postviews\", (postviews.isEmpty() ? \"\" : postviews + \".\") + showPost.getId(),\n\t\t\t\t\t\treq, res);\n\t\t\t\tpc.update(showPost);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic List<Post> getSimilarPosts(Post showPost, Pager pager) {\n\t\tList<Post> similarquestions = Collections.emptyList();\n\t\tif (!showPost.isReply()) {\n\t\t\tString likeTxt = Utils.stripAndTrim((showPost.getTitle() + \" \" + showPost.getBody()));\n\t\t\tif (likeTxt.length() > 1000) {\n\t\t\t\t// read object on the server to prevent \"URI too long\" errors\n\t\t\t\tsimilarquestions = pc.findSimilar(showPost.getType(), showPost.getId(),\n\t\t\t\t\t\tnew String[]{\"properties.title\", \"properties.body\", \"properties.tags\"},\n\t\t\t\t\t\t\"id:\" + showPost.getId(), pager);\n\t\t\t} else if (!StringUtils.isBlank(likeTxt)) {\n\t\t\t\tsimilarquestions = pc.findSimilar(showPost.getType(), showPost.getId(),\n\t\t\t\t\t\tnew String[]{\"properties.title\", \"properties.body\", \"properties.tags\"}, likeTxt, pager);\n\t\t\t}\n\t\t}\n\t\treturn similarquestions;\n\t}\n\n\tpublic String getFirstLinkInPost(String postBody) {\n\t\tpostBody = StringUtils.trimToEmpty(postBody);\n\t\tPattern p = Pattern.compile(\"^!?\\\\[.*\\\\]\\\\((.+)\\\\)\");\n\t\tMatcher m = p.matcher(postBody);\n\n\t\tif (m.find()) {\n\t\t\treturn m.group(1);\n\t\t}\n\t\treturn \"\";\n\t}\n\n\tpublic boolean param(HttpServletRequest req, String param) {\n\t\treturn req.getParameter(param) != null;\n\t}\n\n\tpublic boolean isAjaxRequest(HttpServletRequest req) {\n\t\treturn req.getHeader(\"X-Requested-With\") != null || req.getParameter(\"X-Requested-With\") != null;\n\t}\n\n\tpublic boolean isApiRequest(HttpServletRequest req) {\n\t\treturn req.getRequestURI().startsWith(CONF.serverContextPath() + \"/api/\") || req.getRequestURI().equals(CONF.serverContextPath() + \"/api\");\n\t}\n\n\tpublic boolean isAdmin(Profile authUser) {\n\t\treturn authUser != null && User.Groups.ADMINS.toString().equals(authUser.getGroups());\n\t}\n\n\tpublic boolean isMod(Profile authUser) {\n\t\treturn authUser != null && (isAdmin(authUser) || User.Groups.MODS.toString().equals(authUser.getGroups()));\n\t}\n\n\tpublic boolean isRecognizedAsAdmin(User u) {\n\t\treturn u.isAdmin() || ADMINS.contains(u.getIdentifier()) ||\n\t\t\t\tADMINS.stream().filter(s -> s.equalsIgnoreCase(u.getEmail())).findAny().isPresent();\n\t}\n\n\tpublic boolean canComment(Profile authUser, HttpServletRequest req) {\n\t\treturn isAuthenticated(req) && ((authUser.hasBadge(ENTHUSIAST) || CONF.newUsersCanComment() || isMod(authUser)));\n\t}\n\n\tpublic boolean postsNeedApproval() {\n\t\treturn CONF.postsNeedApproval();\n\t}\n\n\tpublic boolean postNeedsApproval(Profile authUser) {\n\t\treturn postsNeedApproval() && authUser.getVotes() < CONF.postsReputationThreshold() && !isMod(authUser);\n\t}\n\n\tpublic String getWelcomeMessage(Profile authUser) {\n\t\treturn authUser == null ? CONF.welcomeMessage() : \"\";\n\t}\n\n\tpublic String getWelcomeMessageOnLogin(Profile authUser) {\n\t\tif (authUser == null) {\n\t\t\treturn \"\";\n\t\t}\n\t\tString welcomeMsgOnlogin = CONF.welcomeMessageOnLogin();\n\t\tif (StringUtils.contains(welcomeMsgOnlogin, \"{{\")) {\n\t\t\twelcomeMsgOnlogin = Utils.compileMustache(Collections.singletonMap(\"user\",\n\t\t\t\t\tParaObjectUtils.getAnnotatedFields(authUser, false)), welcomeMsgOnlogin);\n\t\t}\n\t\treturn welcomeMsgOnlogin;\n\t}\n\n\tpublic boolean isDefaultSpace(String space) {\n\t\treturn DEFAULT_SPACE.equalsIgnoreCase(getSpaceId(space));\n\t}\n\n\tpublic String getDefaultSpace() {\n\t\treturn DEFAULT_SPACE;\n\t}\n\n\tpublic boolean isAllSpaces(String space) {\n\t\treturn ALL_MY_SPACES.equalsIgnoreCase(getSpaceId(space));\n\t}\n\n\tpublic List<Sysprop> getAllSpaces() {\n\t\tif (allSpaces == null) {\n\t\t\tallSpaces = new LinkedList<>(pc.findQuery(\"scooldspace\", \"*\", new Pager(Config.DEFAULT_LIMIT)));\n\t\t}\n\t\treturn allSpaces;\n\t}\n\n\tpublic boolean canAccessSpace(Profile authUser, String targetSpaceId) {\n\t\tif (authUser == null) {\n\t\t\treturn isDefaultSpacePublic() && isDefaultSpace(targetSpaceId);\n\t\t}\n\t\tif (isMod(authUser) || isAllSpaces(targetSpaceId)) {\n\t\t\treturn true;\n\t\t}\n\t\tif (StringUtils.isBlank(targetSpaceId) || targetSpaceId.length() < 2) {\n\t\t\treturn false;\n\t\t}\n\t\t// this is confusing - let admins control who is in the default space\n\t\t//if (isDefaultSpace(targetSpaceId)) {\n\t\t//\t// can user access the default space (blank)\n\t\t//\treturn isDefaultSpacePublic() || isMod(authUser) || !authUser.hasSpaces();\n\t\t//}\n\t\tboolean isMemberOfSpace = false;\n\t\tfor (String space : authUser.getSpaces()) {\n\t\t\tString spaceId = getSpaceId(targetSpaceId);\n\t\t\tif (StringUtils.startsWithIgnoreCase(space, spaceId + Para.getConfig().separator()) || space.equalsIgnoreCase(spaceId)) {\n\t\t\t\tisMemberOfSpace = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn isMemberOfSpace;\n\t}\n\n\tprivate boolean isIgnoredSpaceForNotifications(Profile profile, String space) {\n\t\treturn profile != null && !profile.getFavspaces().isEmpty() && !profile.getFavspaces().contains(getSpaceId(space));\n\t}\n\n\tpublic String getSpaceIdFromCookie(Profile authUser, HttpServletRequest req) {\n\t\tif (isAdmin(authUser) && req.getParameter(\"space\") != null) {\n\t\t\tSysprop s = pc.read(getSpaceId(req.getParameter(\"space\"))); // API override\n\t\t\tif (s != null) {\n\t\t\t\treturn s.getId() + Para.getConfig().separator() + s.getName();\n\t\t\t}\n\t\t}\n\t\tString spaceAttr = (String) req.getAttribute(CONF.spaceCookie());\n\t\tString spaceValue = StringUtils.isBlank(spaceAttr) ? Utils.base64dec(getCookieValue(req, CONF.spaceCookie())) : spaceAttr;\n\t\tString space = getValidSpaceId(authUser, spaceValue);\n\t\treturn (isAllSpaces(space) && isMod(authUser)) ? DEFAULT_SPACE : verifyExistingSpace(authUser, space);\n\t}\n\n\tpublic void storeSpaceIdInCookie(String space, HttpServletRequest req, HttpServletResponse res) {\n\t\t// directly set the space on the requests, overriding the cookie value\n\t\t// used for setting the space from a direct URL to a particular space\n\t\treq.setAttribute(CONF.spaceCookie(), space);\n\t\tHttpUtils.setRawCookie(CONF.spaceCookie(), Utils.base64encURL(space.getBytes()),\n\t\t\t\treq, res, true, \"Strict\", StringUtils.isBlank(space) ? 0 : 365 * 24 * 60 * 60);\n\t}\n\n\tpublic String verifyExistingSpace(Profile authUser, String space) {\n\t\tif (!isDefaultSpace(space) && !isAllSpaces(space)) {\n\t\t\tSysprop s = pc.read(getSpaceId(space));\n\t\t\tif (s == null) {\n\t\t\t\tif (authUser != null) {\n\t\t\t\t\tauthUser.removeSpace(space);\n\t\t\t\t\tpc.update(authUser);\n\t\t\t\t}\n\t\t\t\treturn DEFAULT_SPACE;\n\t\t\t} else {\n\t\t\t\treturn s.getId() + Para.getConfig().separator() + s.getName(); // updates current space name in case it was renamed\n\t\t\t}\n\t\t}\n\t\treturn space;\n\t}\n\n\tpublic String getValidSpaceIdExcludingAll(Profile authUser, String space, HttpServletRequest req) {\n\t\tString s = StringUtils.isBlank(space) ? getSpaceIdFromCookie(authUser, req) : space;\n\t\treturn isAllSpaces(s) ? DEFAULT_SPACE : s;\n\t}\n\n\tprivate String getValidSpaceId(Profile authUser, String space) {\n\t\tif (authUser == null) {\n\t\t\treturn DEFAULT_SPACE;\n\t\t}\n\t\tString defaultSpace = authUser.hasSpaces() ? ALL_MY_SPACES : DEFAULT_SPACE;\n\t\tString s = canAccessSpace(authUser, space) ? space : defaultSpace;\n\t\treturn StringUtils.isBlank(s) ? DEFAULT_SPACE : s;\n\t}\n\n\tpublic String getSpaceName(String space) {\n\t\tif (DEFAULT_SPACE.equalsIgnoreCase(space)) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn RegExUtils.replaceAll(space, \"^scooldspace:[^:]+:\", \"\");\n\t}\n\n\tpublic String getSpaceId(String space) {\n\t\tif (StringUtils.isBlank(space)) {\n\t\t\treturn DEFAULT_SPACE;\n\t\t}\n\t\tString s = StringUtils.contains(space, Para.getConfig().separator()) ?\n\t\t\t\tStringUtils.substring(space, 0, space.lastIndexOf(Para.getConfig().separator())) : \"scooldspace:\" + space;\n\t\treturn \"scooldspace\".equals(s) ? space : s;\n\t}\n\n\tpublic String getSpaceFilteredQuery(Profile authUser, String currentSpace) {\n\t\treturn canAccessSpace(authUser, currentSpace) ? getSpaceFilter(authUser, currentSpace) : \"\";\n\t}\n\n\tpublic String getSpaceFilteredQuery(HttpServletRequest req) {\n\t\tProfile authUser = getAuthUser(req);\n\t\tString currentSpace = getSpaceIdFromCookie(authUser, req);\n\t\treturn getSpaceFilteredQuery(authUser, currentSpace);\n\t}\n\n\tpublic String getSpaceFilteredQuery(HttpServletRequest req, boolean isSpaceFiltered, String spaceFilter, String defaultQuery) {\n\t\tProfile authUser = getAuthUser(req);\n\t\tString currentSpace = getSpaceIdFromCookie(authUser, req);\n\t\tif (isSpaceFiltered) {\n\t\t\treturn StringUtils.isBlank(spaceFilter) ? getSpaceFilter(authUser, currentSpace) : spaceFilter;\n\t\t}\n\t\treturn canAccessSpace(authUser, currentSpace) ? defaultQuery : \"\";\n\t}\n\n\tpublic String getSpaceFilter(Profile authUser, String spaceId) {\n\t\tif (isAllSpaces(spaceId)) {\n\t\t\tif (authUser != null && authUser.hasSpaces()) {\n\t\t\t\treturn \"(\" + authUser.getSpaces().stream().map(s -> \"properties.space:\\\"\" + s + \"\\\"\").\n\t\t\t\t\t\tcollect(Collectors.joining(\" OR \")) + \")\";\n\t\t\t} else {\n\t\t\t\treturn \"properties.space:\\\"\" + DEFAULT_SPACE + \"\\\"\";\n\t\t\t}\n\t\t} else if (isDefaultSpace(spaceId) && isMod(authUser)) { // DO NOT MODIFY!\n\t\t\treturn \"*\";\n\t\t} else {\n\t\t\treturn \"properties.space:\\\"\" + spaceId + \"\\\"\";\n\t\t}\n\t}\n\n\tpublic Sysprop buildSpaceObject(String space) {\n\t\tspace = Utils.abbreviate(space, 255);\n\t\tspace = space.replaceAll(Para.getConfig().separator(), \"\");\n\t\tString spaceId = getSpaceId(Utils.noSpaces(Utils.stripAndTrim(space, \" \"), \"-\"));\n\t\tSysprop s = new Sysprop(spaceId);\n\t\ts.setType(\"scooldspace\");\n\t\ts.setName(space);\n\t\treturn s;\n\t}\n\n\tpublic String sanitizeQueryString(String query, HttpServletRequest req) {\n\t\tString qf = getSpaceFilteredQuery(req);\n\t\tString defaultQuery = \"*\";\n\t\tString q = StringUtils.trimToEmpty(query);\n\t\tif (qf.isEmpty() || qf.length() > 1) {\n\t\t\tq = q.replaceAll(\"[\\\\?<>]\", \"\").trim();\n\t\t\tq = q.replaceAll(\"$[\\\\*]*\", \"\");\n\t\t\tq = RegExUtils.removeAll(q, \"AND\");\n\t\t\tq = RegExUtils.removeAll(q, \"OR\");\n\t\t\tq = RegExUtils.removeAll(q, \"NOT\");\n\t\t\tq = q.trim();\n\t\t\tdefaultQuery = \"\";\n\t\t}\n\t\tif (qf.isEmpty()) {\n\t\t\treturn defaultQuery;\n\t\t} else if (\"*\".equals(qf)) {\n\t\t\treturn q;\n\t\t} else if (\"*\".equals(q)) {\n\t\t\treturn qf;\n\t\t} else {\n\t\t\tif (q.isEmpty()) {\n\t\t\t\treturn qf;\n\t\t\t} else {\n\t\t\t\treturn qf + \" AND \" + q;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic String getUsersSearchQuery(String qs, String spaceFilter) {\n\t\tqs = Utils.stripAndTrim(qs).toLowerCase();\n\t\tif (!StringUtils.isBlank(qs)) {\n\t\t\tString wildcardLower = qs.matches(\"[\\\\p{IsAlphabetic}]*\") ? qs + \"*\" : qs;\n\t\t\tString wildcardUpper = StringUtils.capitalize(wildcardLower);\n\t\t\tString template = \"(name:({1}) OR name:({2} OR {3}) OR properties.location:({0}) OR \"\n\t\t\t\t\t+ \"properties.aboutme:({0}) OR properties.groups:({0}))\";\n\t\t\tqs = (StringUtils.isBlank(spaceFilter) ? \"\" : spaceFilter + \" AND \") +\n\t\t\t\t\tUtils.formatMessage(template, qs, StringUtils.capitalize(qs), wildcardLower, wildcardUpper);\n\t\t} else {\n\t\t\tqs = StringUtils.isBlank(spaceFilter) ? \"*\" : spaceFilter;\n\t\t}\n\t\treturn qs;\n\t}\n\n\tpublic List<Post> fullQuestionsSearch(String query, Pager... pager) {\n\t\tString typeFilter = Config._TYPE + \":(\" + String.join(\" OR \",\n\t\t\t\t\t\tUtils.type(Question.class), Utils.type(Reply.class), Utils.type(Comment.class)) + \")\";\n\t\tString qs = StringUtils.isBlank(query) || query.startsWith(\"*\") ? typeFilter : query + \" AND \" + typeFilter;\n\t\tList<ParaObject> mixedResults = pc.findQuery(\"\", qs, pager);\n\t\tPredicate<ParaObject> isQuestion = obj -> obj.getType().equals(Utils.type(Question.class));\n\n\t\tMap<String, ParaObject> idsToQuestions = new HashMap<>(mixedResults.stream().filter(isQuestion).\n\t\t\t\tcollect(Collectors.toMap(q -> q.getId(), q -> q)));\n\t\tSet<String> toRead = new LinkedHashSet<>();\n\t\tmixedResults.stream().filter(isQuestion.negate()).forEach(obj -> {\n\t\t\tif (!idsToQuestions.containsKey(obj.getParentid())) {\n\t\t\t\ttoRead.add(obj.getParentid());\n\t\t\t}\n\t\t});\n\t\t// find all parent posts but this excludes parents of parents - i.e. won't work for comments in answers\n\t\tList<Post> parentPostsLevel1 = pc.readAll(new ArrayList<>(toRead));\n\t\tparentPostsLevel1.stream().filter(isQuestion).forEach(q -> idsToQuestions.put(q.getId(), q));\n\n\t\ttoRead.clear();\n\n\t\t// read parents of parents if any\n\t\tparentPostsLevel1.stream().filter(isQuestion.negate()).forEach(obj -> {\n\t\t\tif (!idsToQuestions.containsKey(obj.getParentid())) {\n\t\t\t\ttoRead.add(obj.getParentid());\n\t\t\t}\n\t\t});\n\t\tList<Post> parentPostsLevel2 = pc.readAll(new ArrayList<>(toRead));\n\t\tparentPostsLevel2.stream().forEach(q -> idsToQuestions.put(q.getId(), q));\n\n\t\tArrayList<Post> results = new ArrayList<Post>(idsToQuestions.size());\n\t\tfor (ParaObject result : idsToQuestions.values()) {\n\t\t\tif (result instanceof Post) {\n\t\t\t\tresults.add((Post) result);\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\tpublic String getMacroCode(String key) {\n\t\treturn WHITELISTED_MACROS.getOrDefault(key, \"\");\n\t}\n\n\tpublic boolean isMine(Post showPost, Profile authUser) {\n\t\t// author can edit, mods can edit & ppl with rep > 100 can edit\n\t\treturn showPost != null && authUser != null ? authUser.getId().equals(showPost.getCreatorid()) : false;\n\t}\n\n\tpublic boolean canEdit(Post showPost, Profile authUser) {\n\t\treturn authUser != null ? (authUser.hasBadge(TEACHER) || isMod(authUser) || isMine(showPost, authUser)) : false;\n\t}\n\n\tpublic boolean canDelete(Post showPost, Profile authUser) {\n\t\treturn canDelete(showPost, authUser, null);\n\t}\n\n\tpublic boolean canDelete(Post showPost, Profile authUser, String approvedAnswerId) {\n\t\tif (authUser == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (CONF.deleteProtectionEnabled()) {\n\t\t\tif (showPost.isReply()) {\n\t\t\t\treturn isMine(showPost, authUser) && !StringUtils.equals(approvedAnswerId, showPost.getId());\n\t\t\t} else {\n\t\t\t\treturn isMine(showPost, authUser) && showPost.getAnswercount() == 0;\n\t\t\t}\n\t\t}\n\t\treturn isMine(showPost, authUser);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <P extends ParaObject> P populate(HttpServletRequest req, P pobj, String... paramName) {\n\t\tif (pobj == null || paramName == null) {\n\t\t\treturn pobj;\n\t\t}\n\t\tMap<String, Object> data = new LinkedHashMap<String, Object>();\n\t\tif (isApiRequest(req)) {\n\t\t\ttry {\n\t\t\t\tdata = (Map<String, Object>) req.getAttribute(REST_ENTITY_ATTRIBUTE);\n\t\t\t\tif (data == null) {\n\t\t\t\t\tdata = ParaObjectUtils.getJsonReader(Map.class).readValue(req.getInputStream());\n\t\t\t\t}\n\t\t\t} catch (IOException ex) {\n\t\t\t\tlogger.error(null, ex);\n\t\t\t\tdata = Collections.emptyMap();\n\t\t\t}\n\t\t} else {\n\t\t\tfor (String param : paramName) {\n\t\t\t\tString[] values;\n\t\t\t\tif (param.matches(\".+?\\\\|.$\")) {\n\t\t\t\t\t// convert comma-separated value to list of strings\n\t\t\t\t\tString cleanParam = param.substring(0, param.length() - 2);\n\t\t\t\t\tvalues = req.getParameterValues(cleanParam);\n\t\t\t\t\tString firstValue = (values != null && values.length > 0) ? values[0] : null;\n\t\t\t\t\tString separator = param.substring(param.length() - 1);\n\t\t\t\t\tif (!StringUtils.isBlank(firstValue)) {\n\t\t\t\t\t\tdata.put(cleanParam, Arrays.asList(firstValue.split(separator)));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvalues = req.getParameterValues(param);\n\t\t\t\t\tif (values != null && values.length > 0) {\n\t\t\t\t\t\tdata.put(param, values.length > 1 ? Arrays.asList(values) :\n\t\t\t\t\t\t\t\tArrays.asList(values).iterator().next());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!data.isEmpty()) {\n\t\t\tParaObjectUtils.setAnnotatedFields(pobj, data, null);\n\t\t}\n\t\treturn pobj;\n\t}\n\n\tpublic <P extends ParaObject> Map<String, String> validate(P pobj) {\n\t\tHashMap<String, String> error = new HashMap<String, String>();\n\t\tif (pobj != null) {\n\t\t\tSet<ConstraintViolation<P>> errors = ValidationUtils.getValidator().validate(pobj);\n\t\t\tfor (ConstraintViolation<P> err : errors) {\n\t\t\t\terror.put(err.getPropertyPath().toString(), err.getMessage());\n\t\t\t}\n\t\t}\n\t\treturn error;\n\t}\n\n\tpublic String getFullAvatarURL(Profile profile, AvatarFormat format) {\n\t\treturn avatarRepository.getLink(profile, format);\n\t}\n\n\tpublic void clearSession(HttpServletRequest req, HttpServletResponse res) {\n\t\tif (req != null) {\n\t\t\tString jwt = HttpUtils.getStateParam(CONF.authCookie(), req);\n\t\t\tif (!StringUtils.isBlank(jwt)) {\n\t\t\t\tif (CONF.oneSessionPerUser()) {\n\t\t\t\t\tsynchronized (pc) {\n\t\t\t\t\t\tpc.setAccessToken(jwt);\n\t\t\t\t\t\tpc.revokeAllTokens();\n\t\t\t\t\t\tpc.signOut();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tHttpUtils.removeStateParam(CONF.authCookie(), req, res);\n\t\t\t}\n\t\t\tHttpUtils.removeStateParam(\"dark-mode\", req, res);\n\t\t}\n\t}\n\n\tpublic boolean addBadgeOnce(Profile authUser, Profile.Badge b, boolean condition) {\n\t\treturn addBadge(authUser, b, condition && !authUser.hasBadge(b), false);\n\t}\n\n\tpublic boolean addBadgeOnceAndUpdate(Profile authUser, Profile.Badge b, boolean condition) {\n\t\treturn addBadgeAndUpdate(authUser, b, condition && authUser != null && !authUser.hasBadge(b));\n\t}\n\n\tpublic boolean addBadgeAndUpdate(Profile authUser, Profile.Badge b, boolean condition) {\n\t\treturn addBadge(authUser, b, condition, true);\n\t}\n\n\tpublic boolean addBadge(Profile user, Profile.Badge b, boolean condition, boolean update) {\n\t\tif (user != null && condition) {\n\t\t\tString newb = StringUtils.isBlank(user.getNewbadges()) ? \"\" : user.getNewbadges().concat(\",\");\n\t\t\tnewb = newb.concat(b.toString());\n\n\t\t\tuser.addBadge(b);\n\t\t\tuser.setNewbadges(newb);\n\t\t\tif (update) {\n\t\t\t\tuser.update();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic List<String> checkForBadges(Profile authUser, HttpServletRequest req) {\n\t\tList<String> badgelist = new ArrayList<String>();\n\t\tif (authUser != null && !isAjaxRequest(req)) {\n\t\t\tlong oneYear = authUser.getTimestamp() + (365 * 24 * 60 * 60 * 1000);\n\t\t\taddBadgeOnce(authUser, Profile.Badge.ENTHUSIAST, authUser.getVotes() >= CONF.enthusiastIfHasRep());\n\t\t\taddBadgeOnce(authUser, Profile.Badge.FRESHMAN, authUser.getVotes() >= CONF.freshmanIfHasRep());\n\t\t\taddBadgeOnce(authUser, Profile.Badge.SCHOLAR, authUser.getVotes() >= CONF.scholarIfHasRep());\n\t\t\taddBadgeOnce(authUser, Profile.Badge.TEACHER, authUser.getVotes() >= CONF.teacherIfHasRep());\n\t\t\taddBadgeOnce(authUser, Profile.Badge.PROFESSOR, authUser.getVotes() >= CONF.professorIfHasRep());\n\t\t\taddBadgeOnce(authUser, Profile.Badge.GEEK, authUser.getVotes() >= CONF.geekIfHasRep());\n\t\t\taddBadgeOnce(authUser, Profile.Badge.SENIOR, (System.currentTimeMillis() - authUser.getTimestamp()) >= oneYear);\n\n\t\t\tif (!StringUtils.isBlank(authUser.getNewbadges())) {\n\t\t\t\tbadgelist.addAll(Arrays.asList(authUser.getNewbadges().split(\",\")));\n\t\t\t\tauthUser.setNewbadges(null);\n\t\t\t\tauthUser.update();\n\t\t\t}\n\t\t}\n\t\treturn badgelist;\n\t}\n\n\tprivate String loadEmailTemplate(String name) {\n\t\treturn loadResource(\"emails/\" + name + \".html\");\n\t}\n\n\tpublic String loadResource(String filePath) {\n\t\tif (filePath == null) {\n\t\t\treturn \"\";\n\t\t}\n\t\tif (FILE_CACHE.containsKey(filePath)) {\n\t\t\treturn FILE_CACHE.get(filePath);\n\t\t}\n\t\tString template = \"\";\n\t\ttry (InputStream in = getClass().getClassLoader().getResourceAsStream(filePath)) {\n\t\t\ttry (Scanner s = new Scanner(in).useDelimiter(\"\\\\A\")) {\n\t\t\t\ttemplate = s.hasNext() ? s.next() : \"\";\n\t\t\t\tif (!StringUtils.isBlank(template)) {\n\t\t\t\t\tFILE_CACHE.put(filePath, template);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception ex) {\n\t\t\tlogger.info(\"Couldn't load resource '{}'.\", filePath);\n\t\t}\n\t\treturn template;\n\t}\n\n\tpublic String compileEmailTemplate(Map<String, Object> model) {\n\t\tmodel.put(\"footerhtml\", CONF.emailsFooterHtml());\n\t\tString fqdn = CONF.rewriteInboundLinksWithFQDN();\n\t\tif (!StringUtils.isBlank(fqdn)) {\n\t\t\tmodel.entrySet().stream().filter(e -> (e.getValue() instanceof String)).forEachOrdered(e -> {\n\t\t\t\tmodel.put(e.getKey(), StringUtils.replace((String) e.getValue(), CONF.serverUrl(), fqdn));\n\t\t\t});\n\t\t}\n\t\treturn Utils.compileMustache(model, loadEmailTemplate(\"notify\"));\n\t}\n\n\tpublic boolean isValidJWToken(String jwt) {\n\t\tString appSecretKey = CONF.appSecretKey();\n\t\tString masterSecretKey = CONF.paraSecretKey();\n\t\treturn isValidJWToken(appSecretKey, jwt) || isValidJWToken(masterSecretKey, jwt);\n\t}\n\n\tboolean isValidJWToken(String secret, String jwt) {\n\t\ttry {\n\t\t\tif (secret != null && jwt != null) {\n\t\t\t\tJWSVerifier verifier = new MACVerifier(secret);\n\t\t\t\tSignedJWT sjwt = SignedJWT.parse(jwt);\n\t\t\t\tif (sjwt.verify(verifier)) {\n\t\t\t\t\tDate referenceTime = new Date();\n\t\t\t\t\tJWTClaimsSet claims = sjwt.getJWTClaimsSet();\n\n\t\t\t\t\tDate expirationTime = claims.getExpirationTime();\n\t\t\t\t\tDate notBeforeTime = claims.getNotBeforeTime();\n\t\t\t\t\tString jti = claims.getJWTID();\n\t\t\t\t\tboolean expired = expirationTime != null && expirationTime.before(referenceTime);\n\t\t\t\t\tboolean notYetValid = notBeforeTime != null && notBeforeTime.after(referenceTime);\n\t\t\t\t\tboolean jtiRevoked = isApiKeyRevoked(jti, expired);\n\t\t\t\t\treturn !(expired || notYetValid || jtiRevoked);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (JOSEException e) {\n\t\t\tlogger.warn(null, e);\n\t\t} catch (ParseException ex) {\n\t\t\tlogger.warn(null, ex);\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic SignedJWT generateJWToken(Map<String, Object> claims) {\n\t\treturn generateJWToken(claims, CONF.jwtExpiresAfterSec());\n\t}\n\n\tpublic SignedJWT generateJWToken(Map<String, Object> claims, long validitySeconds) {\n\t\tString secret = CONF.appSecretKey();\n\t\tif (!StringUtils.isBlank(secret)) {\n\t\t\ttry {\n\t\t\t\tDate now = new Date();\n\t\t\t\tJWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();\n\t\t\t\tclaimsSet.issueTime(now);\n\t\t\t\tif (validitySeconds > 0) {\n\t\t\t\t\tclaimsSet.expirationTime(new Date(now.getTime() + (validitySeconds * 1000)));\n\t\t\t\t}\n\t\t\t\tclaimsSet.notBeforeTime(now);\n\t\t\t\tclaimsSet.claim(Config._APPID, CONF.paraAccessKey());\n\t\t\t\tclaims.entrySet().forEach((claim) -> claimsSet.claim(claim.getKey(), claim.getValue()));\n\t\t\t\tJWSSigner signer = new MACSigner(secret);\n\t\t\t\tSignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build());\n\t\t\t\tsignedJWT.sign(signer);\n\t\t\t\treturn signedJWT;\n\t\t\t} catch (JOSEException e) {\n\t\t\t\tlogger.warn(\"Unable to sign JWT: {}.\", e.getMessage());\n\t\t\t}\n\t\t}\n\t\tlogger.error(\"Failed to generate JWT token - app_secret_key is blank.\");\n\t\treturn null;\n\t}\n\n\tpublic boolean isApiKeyRevoked(String jti, boolean expired) {\n\t\tif (StringUtils.isBlank(jti)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (API_KEYS.isEmpty()) {\n\t\t\tSysprop s = pc.read(\"api_keys\");\n\t\t\tif (s != null) {\n\t\t\t\tAPI_KEYS.putAll(s.getProperties());\n\t\t\t}\n\t\t}\n\t\tif (API_KEYS.containsKey(jti) && expired) {\n\t\t\trevokeApiKey(jti);\n\t\t}\n\t\treturn !API_KEYS.containsKey(jti);\n\t}\n\n\tpublic void registerApiKey(String jti, String jwt) {\n\t\tif (StringUtils.isBlank(jti) || StringUtils.isBlank(jwt)) {\n\t\t\treturn;\n\t\t}\n\t\tAPI_KEYS.put(jti, jwt);\n\t\tsaveApiKeysObject();\n\t}\n\n\tpublic void revokeApiKey(String jti) {\n\t\tAPI_KEYS.remove(jti);\n\t\tsaveApiKeysObject();\n\t}\n\n\tpublic Map<String, Object> getApiKeys() {\n\t\treturn Collections.unmodifiableMap(API_KEYS);\n\t}\n\n\tpublic Map<String, Long> getApiKeysExpirations() {\n\t\treturn API_KEYS.keySet().stream().collect(Collectors.toMap(k -> k, k -> {\n\t\t\ttry {\n\t\t\t\tDate exp = SignedJWT.parse((String) API_KEYS.get(k)).getJWTClaimsSet().getExpirationTime();\n\t\t\t\tif (exp != null) {\n\t\t\t\t\treturn exp.getTime();\n\t\t\t\t}\n\t\t\t} catch (ParseException ex) {\n\t\t\t\tlogger.error(null, ex);\n\t\t\t}\n\t\t\treturn 0L;\n\t\t}));\n\t}\n\n\tprivate void saveApiKeysObject() {\n\t\tSysprop s = new Sysprop(\"api_keys\");\n\t\ts.setProperties(API_KEYS);\n\t\tpc.create(s);\n\t}\n\n\tpublic Profile getSystemUser() {\n\t\treturn API_USER;\n\t}\n\n\tpublic void triggerHookEvent(String eventName, Object payload) {\n\t\tif (isWebhooksEnabled() && HOOK_EVENTS.contains(eventName)) {\n\t\t\tPara.asyncExecute(() -> {\n\t\t\t\tWebhook trigger = new Webhook();\n\t\t\t\ttrigger.setTriggeredEvent(eventName);\n\t\t\t\ttrigger.setCustomPayload(payload);\n\t\t\t\tpc.create(trigger);\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic void setSecurityHeaders(String nonce, HttpServletRequest request, HttpServletResponse response) {\n\t\t// CSP Header\n\t\tif (CONF.cspHeaderEnabled()) {\n\t\t\tresponse.setHeader(\"Content-Security-Policy\",\n\t\t\t\t\t(request.isSecure() ? \"upgrade-insecure-requests; \" : \"\") + CONF.cspHeader(nonce));\n\t\t}\n\t\t// HSTS Header\n\t\tif (CONF.hstsHeaderEnabled()) {\n\t\t\tresponse.setHeader(\"Strict-Transport-Security\", \"max-age=31536000; includeSubDomains\");\n\t\t}\n\t\t// Frame Options Header\n\t\tif (CONF.framingHeaderEnabled()) {\n\t\t\tresponse.setHeader(\"X-Frame-Options\", \"SAMEORIGIN\");\n\t\t}\n\t\t// XSS Header\n\t\tif (CONF.xssHeaderEnabled()) {\n\t\t\tresponse.setHeader(\"X-XSS-Protection\", \"1; mode=block\");\n\t\t}\n\t\t// Content Type Header\n\t\tif (CONF.contentTypeHeaderEnabled()) {\n\t\t\tresponse.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n\t\t}\n\t\t// Referrer Header\n\t\tif (CONF.referrerHeaderEnabled()) {\n\t\t\tresponse.setHeader(\"Referrer-Policy\", \"strict-origin\");\n\t\t}\n\t\t// Permissions Policy Header\n\t\tif (CONF.permissionsHeaderEnabled()) {\n\t\t\tresponse.setHeader(\"Permissions-Policy\", \"geolocation=()\");\n\t\t}\n\t}\n\n\tpublic boolean cookieConsentGiven(HttpServletRequest request) {\n\t\treturn !CONF.cookieConsentRequired() || \"allow\".equals(HttpUtils.getCookieValue(request, \"cookieconsent_status\"));\n\t}\n\n\tpublic String base64DecodeScript(String encodedScript) {\n\t\tif (StringUtils.isBlank(encodedScript)) {\n\t\t\treturn \"\";\n\t\t}\n\t\ttry {\n\t\t\tString decodedScript = Base64.isBase64(encodedScript) ? Utils.base64dec(encodedScript) : \"\";\n\t\t\treturn StringUtils.isBlank(decodedScript) ? encodedScript : decodedScript;\n\t\t} catch (Exception e) {\n\t\t\treturn encodedScript;\n\t\t}\n\t}\n\n\tpublic Map<String, Object> getExternalScripts() {\n\t\treturn CONF.externalScripts();\n\t}\n\n\tpublic List<String> getExternalStyles() {\n\t\tString extStyles = CONF.externalStyles();\n\t\tif (!StringUtils.isBlank(extStyles)) {\n\t\t\tString[] styles = extStyles.split(\"\\\\s*,\\\\s*\");\n\t\t\tif (!StringUtils.isBlank(extStyles) && styles != null && styles.length > 0) {\n\t\t\t\tArrayList<String> list = new ArrayList<String>();\n\t\t\t\tfor (String style : styles) {\n\t\t\t\t\tif (!StringUtils.isBlank(style)) {\n\t\t\t\t\t\tlist.add(style);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn list;\n\t\t\t}\n\t\t}\n\t\treturn Collections.emptyList();\n\t}\n\n\tpublic String getInlineCSS() {\n\t\ttry {\n\t\t\tSysprop custom = getCustomTheme();\n\t\t\tString themeName = custom.getName();\n\t\t\tString inline = CONF.inlineCSS();\n\t\t\tString loadedTheme;\n\t\t\tif (\"default\".equalsIgnoreCase(themeName) || StringUtils.isBlank(themeName)) {\n\t\t\t\treturn inline;\n\t\t\t} else if (\"custom\".equalsIgnoreCase(themeName)) {\n\t\t\t\tloadedTheme = (String) custom.getProperty(\"theme\");\n\t\t\t} else {\n\t\t\t\tloadedTheme = loadResource(getThemeKey(themeName));\n\t\t\t\tif (StringUtils.isBlank(loadedTheme)) {\n\t\t\t\t\tFILE_CACHE.put(\"theme\", \"default\");\n\t\t\t\t\tcustom.setName(\"default\");\n\t\t\t\t\tcustomTheme = pc.update(custom);\n\t\t\t\t\treturn inline;\n\t\t\t\t} else {\n\t\t\t\t\tFILE_CACHE.put(\"theme\", themeName);\n\t\t\t\t}\n\t\t\t}\n\t\t\tloadedTheme = StringUtils.replaceEachRepeatedly(loadedTheme,\n\t\t\t\t\tnew String[] {\"<\", \"</\", \"<script\", \"<SCRIPT\"}, new String[] {\"\", \"\", \"\", \"\"});\n\t\t\treturn loadedTheme + \"\\n/*** END OF THEME CSS ***/\\n\" + inline;\n\t\t} catch (Exception e) {\n\t\t\tlogger.debug(\"Failed to load inline CSS.\");\n\t\t}\n\t\treturn \"\";\n\t}\n\n\tpublic void setCustomTheme(String themeName, String themeCSS) {\n\t\tString id = \"theme\" + Para.getConfig().separator() + \"custom\";\n\t\tboolean isCustom = \"custom\".equalsIgnoreCase(themeName);\n\t\tString css = isCustom ? themeCSS : \"\";\n\t\tSysprop custom = new Sysprop(id);\n\t\tcustom.setName(StringUtils.isBlank(css) && isCustom ? \"default\" : themeName);\n\t\tcustom.addProperty(\"theme\", css);\n\t\tcustomTheme = pc.create(custom);\n\t\tFILE_CACHE.put(\"theme\", themeName);\n\t\tFILE_CACHE.put(getThemeKey(themeName), isCustom ? css : loadResource(getThemeKey(themeName)));\n\t}\n\n\tpublic Sysprop getCustomTheme() {\n\t\tString id = \"theme\" + Para.getConfig().separator() + \"custom\";\n\t\tif (customTheme == null) {\n\t\t\tcustomTheme = (Sysprop) Optional.ofNullable(pc.read(id)).orElseGet(this::getDefaultThemeObject);\n\t\t}\n\t\treturn customTheme;\n\t}\n\n\tprivate Sysprop getDefaultThemeObject() {\n\t\tString themeName = \"default\";\n\t\tSysprop s = new Sysprop(\"theme\" + Para.getConfig().separator() + \"custom\");\n\t\ts.setName(themeName);\n\t\ts.addProperty(\"theme\", \"\");\n\t\tFILE_CACHE.put(\"theme\", themeName);\n\t\tFILE_CACHE.put(getThemeKey(themeName), loadResource(getThemeKey(themeName)));\n\t\treturn s;\n\t}\n\n\tprivate String getThemeKey(String themeName) {\n\t\treturn \"themes/\" + themeName + \".css\";\n\t}\n\n\tpublic String getDefaultTheme() {\n\t\treturn loadResource(\"themes/default.css\");\n\t}\n\n\tpublic String getSmallLogoUrl() {\n\t\tString defaultLogo = CONF.serverUrl() + CONF.imagesLink() + \"/logowhite.png\";\n\t\tString logoUrl = CONF.logoSmallUrl();\n\t\tString defaultMainLogoUrl = CONF.imagesLink() + \"/logo.svg\";\n\t\tString mainLogoUrl = CONF.logoUrl();\n\t\tif (!defaultLogo.equals(logoUrl)) {\n\t\t\treturn logoUrl;\n\t\t} else if (!mainLogoUrl.equals(defaultMainLogoUrl)) {\n\t\t\treturn mainLogoUrl;\n\t\t}\n\t\treturn logoUrl;\n\t}\n\n\tpublic String getCSPNonce() {\n\t\treturn Utils.generateSecurityToken(16);\n\t}\n\n\tpublic String getFacebookLoginURL() {\n\t\treturn \"https://www.facebook.com/dialog/oauth?client_id=\" + CONF.facebookAppId() +\n\t\t\t\t\"&response_type=code&scope=email&redirect_uri=\" + getParaEndpoint() +\n\t\t\t\t\"/facebook_auth&state=\" + getParaAppId();\n\t}\n\n\tpublic String getGoogleLoginURL() {\n\t\treturn \"https://accounts.google.com/o/oauth2/v2/auth?\" +\n\t\t\t\t\"client_id=\" + CONF.googleAppId() + \"&response_type=code&scope=openid%20profile%20email&redirect_uri=\"\n\t\t\t\t+ getParaEndpoint() + \"/google_auth&state=\" + getParaAppId();\n\t}\n\n\tpublic String getGitHubLoginURL() {\n\t\treturn \"https://github.com/login/oauth/authorize?response_type=code&client_id=\" + CONF.githubAppId() +\n\t\t\t\t\"&scope=user%3Aemail&state=\" + getParaAppId() +\n\t\t\t\t\"&redirect_uri=\" + getParaEndpoint() + \"/github_auth\";\n\t}\n\n\tpublic String getLinkedInLoginURL() {\n\t\treturn \"https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=\" + CONF.linkedinAppId() +\n\t\t\t\t\"&scope=r_liteprofile%20r_emailaddress&state=\" + getParaAppId() +\n\t\t\t\t\"&redirect_uri=\" + getParaEndpoint() + \"/linkedin_auth\";\n\t}\n\n\tpublic String getTwitterLoginURL() {\n\t\treturn getParaEndpoint() + \"/twitter_auth?state=\" + getParaAppId();\n\t}\n\n\tpublic String getMicrosoftLoginURL() {\n\t\treturn \"https://login.microsoftonline.com/\" + CONF.microsoftTenantId() +\n\t\t\t\t\"/oauth2/v2.0/authorize?response_type=code&client_id=\" + CONF.microsoftAppId() +\n\t\t\t\t\"&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&state=\" + getParaAppId() +\n\t\t\t\t\"&redirect_uri=\" + getParaEndpoint() + \"/microsoft_auth\";\n\t}\n\n\tpublic String getSlackLoginURL() {\n\t\treturn \"https://slack.com/oauth/v2/authorize?response_type=code&client_id=\" + CONF.slackAppId() +\n\t\t\t\t\"&user_scope=identity.basic%20identity.email%20identity.team%20identity.avatar&state=\" + getParaAppId() +\n\t\t\t\t\"&redirect_uri=\" + getParaEndpoint() + \"/slack_auth\";\n\t}\n\n\tpublic String getAmazonLoginURL() {\n\t\treturn \"https://www.amazon.com/ap/oa?response_type=code&client_id=\" + CONF.amazonAppId() +\n\t\t\t\t\"&scope=profile&state=\" + getParaAppId() +\n\t\t\t\t\"&redirect_uri=\" + getParaEndpoint() + \"/amazon_auth\";\n\t}\n\n\tpublic String getOAuth2LoginURL() {\n\t\treturn CONF.oauthAuthorizationUrl(\"\") + \"?\" +\n\t\t\t\t\"response_type=code&client_id=\" + CONF.oauthAppId(\"\") +\n\t\t\t\t\"&scope=\" + CONF.oauthScope(\"\") + \"&state=\" + getParaAppId() +\n\t\t\t\t\"&redirect_uri=\" + getParaEndpoint() + \"/oauth2_auth\";\n\t}\n\n\tpublic String getOAuth2SecondLoginURL() {\n\t\treturn CONF.oauthAuthorizationUrl(\"second\") + \"?\" +\n\t\t\t\t\"response_type=code&client_id=\" + CONF.oauthAppId(\"second\") +\n\t\t\t\t\"&scope=\" + CONF.oauthScope(\"second\") + \"&state=\" + getParaAppId() +\n\t\t\t\t\"&redirect_uri=\" + getParaEndpoint() + \"/oauth2_auth\";\n\t}\n\n\tpublic String getOAuth2ThirdLoginURL() {\n\t\treturn CONF.oauthAuthorizationUrl(\"third\") + \"?\" +\n\t\t\t\t\"response_type=code&client_id=\" + CONF.oauthAppId(\"third\") +\n\t\t\t\t\"&scope=\" + CONF.oauthScope(\"third\") + \"&state=\" + getParaAppId() +\n\t\t\t\t\"&redirect_uri=\" + getParaEndpoint() + \"/oauth2_auth\";\n\t}\n\n\tpublic String getParaEndpoint() {\n\t\treturn CONF.redirectUri();\n\t}\n\n\tpublic String getParaAppId() {\n\t\treturn StringUtils.removeStart(CONF.paraAccessKey(), \"app:\");\n\t}\n\n\tpublic String getFirstConfiguredLoginURL() {\n\t\tif (!CONF.facebookAppId().isEmpty()) {\n\t\t\treturn getFacebookLoginURL();\n\t\t}\n\t\tif (!CONF.googleAppId().isEmpty()) {\n\t\t\treturn getGoogleLoginURL();\n\t\t}\n\t\tif (!CONF.githubAppId().isEmpty()) {\n\t\t\treturn getGitHubLoginURL();\n\t\t}\n\t\tif (!CONF.linkedinAppId().isEmpty()) {\n\t\t\treturn getLinkedInLoginURL();\n\t\t}\n\t\tif (!CONF.twitterAppId().isEmpty()) {\n\t\t\treturn getTwitterLoginURL();\n\t\t}\n\t\tif (!CONF.microsoftAppId().isEmpty()) {\n\t\t\treturn getMicrosoftLoginURL();\n\t\t}\n\t\tif (isSlackAuthEnabled()) {\n\t\t\treturn getSlackLoginURL();\n\t\t}\n\t\tif (!CONF.amazonAppId().isEmpty()) {\n\t\t\treturn getAmazonLoginURL();\n\t\t}\n\t\tif (!CONF.oauthAppId(\"\").isEmpty()) {\n\t\t\treturn getOAuth2LoginURL();\n\t\t}\n\t\tif (!CONF.oauthAppId(\"second\").isEmpty()) {\n\t\t\treturn getOAuth2SecondLoginURL();\n\t\t}\n\t\tif (!CONF.oauthAppId(\"third\").isEmpty()) {\n\t\t\treturn getOAuth2ThirdLoginURL();\n\t\t}\n\t\treturn SIGNINLINK + \"?code=3&error=true\";\n\t}\n}" ]
import com.erudika.para.client.ParaClient; import com.erudika.para.core.utils.Config; import com.erudika.para.core.utils.Pager; import com.erudika.para.core.utils.ParaObjectUtils; import com.erudika.para.core.utils.Utils; import com.erudika.scoold.ScooldConfig; import static com.erudika.scoold.ScooldServer.REPORTSLINK; import static com.erudika.scoold.ScooldServer.SIGNINLINK; import com.erudika.scoold.core.Profile; import static com.erudika.scoold.core.Profile.Badge.REPORTER; import com.erudika.scoold.core.Report; import com.erudika.scoold.utils.ScooldUtils; import java.io.IOException; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam;
/* * Copyright 2013-2022 Erudika. https://erudika.com * * 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. * * For issues and patches go to: https://github.com/erudika */ package com.erudika.scoold.controllers; /** * * @author Alex Bogdanovski [[email protected]] */ @Controller @RequestMapping("/reports") public class ReportsController { private static final ScooldConfig CONF = ScooldUtils.getConfig(); private final ScooldUtils utils; private final ParaClient pc; @Inject public ReportsController(ScooldUtils utils) { this.utils = utils; this.pc = utils.getParaClient(); } @GetMapping public String get(@RequestParam(required = false, defaultValue = Config._TIMESTAMP) String sortby, HttpServletRequest req, Model model) { if (utils.isAuthenticated(req) && !utils.isMod(utils.getAuthUser(req))) { return "redirect:" + REPORTSLINK; } else if (!utils.isAuthenticated(req)) {
return "redirect:" + SIGNINLINK + "?returnto=" + REPORTSLINK;
2
novucs/factions-top
core/src/main/java/net/novucs/ftop/listener/WorthListener.java
[ "public final class FactionsTopPlugin extends JavaPlugin {\n\n private final ChunkWorthTask chunkWorthTask = new ChunkWorthTask(this);\n private final GuiManager guiManager = new GuiManager(this);\n private final PersistenceTask persistenceTask = new PersistenceTask(this);\n private final RecalculateTask recalculateTask = new RecalculateTask(this);\n private final Settings settings = new Settings(this);\n private final SignManager signManager = new SignManager(this);\n private final WorthManager worthManager = new WorthManager(this);\n private final Set<PluginService> services = new HashSet<>(Arrays.asList(\n signManager,\n worthManager,\n new GuiCommand(this),\n new RecalculateCommand(this),\n new ReloadCommand(this),\n new TextCommand(this),\n new VersionCommand(this),\n new ChatListener(this),\n new CommandListener(this),\n new GuiListener(this),\n new WorthListener(this)\n ));\n\n private boolean active;\n private CraftbukkitHook craftbukkitHook;\n private EconomyHook economyHook;\n private FactionsHook factionsHook;\n private Set<PlaceholderHook> placeholderHooks;\n private SpawnerStackerHook spawnerStackerHook;\n private DatabaseManager databaseManager;\n\n public ChunkWorthTask getChunkWorthTask() {\n return chunkWorthTask;\n }\n\n public GuiManager getGuiManager() {\n return guiManager;\n }\n\n public PersistenceTask getPersistenceTask() {\n return persistenceTask;\n }\n\n public RecalculateTask getRecalculateTask() {\n return recalculateTask;\n }\n\n public Settings getSettings() {\n return settings;\n }\n\n public WorthManager getWorthManager() {\n return worthManager;\n }\n\n public CraftbukkitHook getCraftbukkitHook() {\n return craftbukkitHook;\n }\n\n public EconomyHook getEconomyHook() {\n return economyHook;\n }\n\n public FactionsHook getFactionsHook() {\n return factionsHook;\n }\n\n public SpawnerStackerHook getSpawnerStackerHook() {\n return spawnerStackerHook;\n }\n\n public DatabaseManager getDatabaseManager() {\n return databaseManager;\n }\n\n public void setDatabaseManager(DatabaseManager databaseManager) {\n this.databaseManager = databaseManager;\n }\n\n @Override\n public void onEnable() {\n if (!loadFactionsHook()) {\n getLogger().severe(\"No valid version of factions was found!\");\n getLogger().severe(\"Disabling FactionsTop . . .\");\n getServer().getPluginManager().disablePlugin(this);\n return;\n }\n\n loadCraftbukkitHook();\n loadSpawnerStackerHook();\n\n if (loadEconomyHook()) {\n services.add(economyHook);\n }\n\n setupSlf4j();\n services.add(factionsHook);\n loadSettings();\n boolean newDatabase = loadDatabase();\n chunkWorthTask.start();\n persistenceTask.start();\n\n if (newDatabase && !recalculateTask.isRunning()) {\n getLogger().info(\"----- IMPORTANT -----\");\n getLogger().info(\"Detected a fresh database\");\n getLogger().info(\"Starting chunk resynchronization\");\n getLogger().info(\"To cancel, type: /ftoprec cancel\");\n getLogger().info(\"----- IMPORTANT -----\");\n recalculateTask.initialize();\n }\n }\n\n @Override\n public void onDisable() {\n getLogger().info(\"Preparing shutdown...\");\n guiManager.closeInventories();\n\n if (recalculateTask.isRunning()) {\n recalculateTask.terminate();\n }\n\n getLogger().info(\"Shutting down chunk worth task...\");\n chunkWorthTask.interrupt();\n try {\n chunkWorthTask.join();\n } catch (InterruptedException ignore) {\n }\n\n getLogger().info(\"Saving everything to database...\");\n persistenceTask.interrupt();\n try {\n persistenceTask.join();\n } catch (InterruptedException ignore) {\n }\n\n getLogger().info(\"Terminating plugin services...\");\n databaseManager.close();\n services.forEach(PluginService::terminate);\n active = false;\n }\n\n private boolean loadDatabase() {\n boolean usingH2 = settings.getHikariConfig().getJdbcUrl().startsWith(\"jdbc:h2\");\n\n if (usingH2) {\n setupH2();\n }\n\n Map<ChunkPos, ChunkWorth> loadedChunks;\n Multimap<Integer, BlockPos> loadedSigns;\n try {\n databaseManager = DatabaseManager.create(settings.getHikariConfig());\n DatabaseManager.DataDump dataDump = databaseManager.load();\n loadedChunks = dataDump.getChunks();\n loadedSigns = dataDump.getSigns();\n } catch (SQLException e) {\n getLogger().log(Level.SEVERE, \"Failed to initialize the database\");\n getLogger().log(Level.SEVERE, \"Are the database credentials in the config correct?\");\n getLogger().log(Level.SEVERE, \"Stack trace: \", e);\n getLogger().log(Level.SEVERE, \"Disabling FactionsTop . . .\");\n getServer().getPluginManager().disablePlugin(this);\n return false;\n }\n\n worthManager.loadChunks(loadedChunks);\n getServer().getScheduler().runTask(this, worthManager::updateAllFactions);\n signManager.setSigns(loadedSigns);\n return loadedChunks.isEmpty();\n }\n\n private void setupSlf4j() {\n try {\n loadLibrary(\"https://repo.maven.apache.org/maven2/org/slf4j/slf4j-api/1.7.9/slf4j-api-1.7.9.jar\");\n loadLibrary(\"https://repo.maven.apache.org/maven2/org/slf4j/slf4j-nop/1.7.9/slf4j-nop-1.7.9.jar\");\n } catch (Exception ignore) {\n }\n }\n\n private void setupH2() {\n try {\n Class.forName(\"org.h2.Driver\");\n getLogger().info(\"H2 successfully loaded via classpath.\");\n return;\n } catch (ClassNotFoundException ignore) {\n }\n\n try {\n loadLibrary(\"https://repo.maven.apache.org/maven2/com/h2database/h2/1.4.192/h2-1.4.192.jar\");\n getLogger().info(\"H2 forcefully loaded, a reboot may be required.\");\n } catch (Exception e) {\n getLogger().severe(\"H2 was unable to be loaded.\");\n getLogger().log(Level.SEVERE, \"The errors are as follows:\", e);\n getLogger().severe(\"Disabling FactionsTop . . .\");\n getServer().getPluginManager().disablePlugin(this);\n }\n }\n\n private void loadLibrary(String url) throws Exception {\n // Get the library file.\n String fileName = url.substring(url.lastIndexOf('/') + 1);\n String pathName = \"lib\" + File.separator + fileName;\n File library = new File(pathName);\n\n // Download the library from maven into the libs folder if none already exists.\n if (!library.exists()) {\n getLogger().info(\"Downloading \" + fileName + \" dependency . . .\");\n library.getParentFile().mkdirs();\n library.createNewFile();\n URL repo = new URL(url);\n ReadableByteChannel rbc = Channels.newChannel(repo.openStream());\n FileOutputStream fos = new FileOutputStream(pathName);\n fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);\n getLogger().info(fileName + \" successfully downloaded!\");\n }\n\n // Load library to JVM.\n Method method = URLClassLoader.class.getDeclaredMethod(\"addURL\", URL.class);\n method.setAccessible(true);\n method.invoke(ClassLoader.getSystemClassLoader(), library.toURI().toURL());\n }\n\n private void loadCraftbukkitHook() {\n String version = getServer().getClass().getPackage().getName().split(\"\\\\.\")[3];\n\n if (version.compareTo(\"v1_7_R4\") <= 0 && version.split(\"_\")[1].length() == 1) {\n craftbukkitHook = new Craftbukkit17R4();\n } else if (version.equals(\"v1_8_R1\")) {\n craftbukkitHook = new Craftbukkit18R1();\n } else if (version.equals(\"v1_8_R2\")) {\n craftbukkitHook = new Craftbukkit18R2();\n } else {\n craftbukkitHook = new Craftbukkit18R3();\n }\n }\n\n private void loadSpawnerStackerHook() {\n Plugin epicSpawnersPlugin = getServer().getPluginManager().getPlugin(\"EpicSpawners\");\n\n if (epicSpawnersPlugin != null) {\n spawnerStackerHook = new EpicSpawnersHook(this, craftbukkitHook);\n } else {\n spawnerStackerHook = new VanillaSpawnerStackerHook(craftbukkitHook);\n }\n\n spawnerStackerHook.initialize();\n }\n\n private boolean loadEconomyHook() {\n Plugin essentials = getServer().getPluginManager().getPlugin(\"Essentials\");\n if (essentials != null) {\n economyHook = new EssentialsEconomyHook(this, factionsHook);\n getLogger().info(\"Essentials found, using as economy backend.\");\n return true;\n }\n\n Plugin vault = getServer().getPluginManager().getPlugin(\"Vault\");\n if (vault != null) {\n economyHook = new VaultEconomyHook(this, worthManager.getFactionIds());\n getLogger().info(\"Vault found, using as economy backend.\");\n return true;\n }\n return false;\n }\n\n private boolean loadFactionsHook() {\n Plugin factions = getServer().getPluginManager().getPlugin(\"Factions\");\n if (factions == null) {\n factions = getServer().getPluginManager().getPlugin(\"LegacyFactions\");\n\n if (factions == null) {\n return false;\n }\n\n factionsHook = new LegacyFactions0103(this);\n return true;\n }\n\n // Attempt to find a valid hook for the factions version.\n String[] components = factions.getDescription().getVersion().split(\"\\\\.\");\n String version = components.length < 2 ? \"\" : components[0] + \".\" + components[1];\n\n switch (version) {\n case \"1.6\":\n factionsHook = new Factions0106(this);\n return true;\n case \"1.8\":\n factionsHook = new Factions0108(this);\n return true;\n case \"2.7\":\n case \"2.8\":\n case \"2.9\":\n case \"2.10\":\n factionsHook = new Factions0207(this);\n return true;\n case \"2.11\":\n factionsHook = new Factions0211(this);\n return true;\n default:\n factionsHook = new Factions0212(this);\n return true;\n }\n }\n\n private void loadPlaceholderHook() {\n placeholderHooks = new HashSet<>();\n \n PlayerReplacer playerReplacer = new PlayerReplacer(this);\n RankReplacer rankReplacer = new RankReplacer(this);\n LastReplacer lastReplacer = new LastReplacer(this);\n \n Plugin mvdwPlaceholderApi = getServer().getPluginManager().getPlugin(\"MVdWPlaceholderAPI\");\n if (mvdwPlaceholderApi != null && mvdwPlaceholderApi.isEnabled()) {\n PlaceholderHook placeholderHook = new MVdWPlaceholderAPIHook(this, playerReplacer, rankReplacer, lastReplacer);\n boolean updated = placeholderHook.initialize(getSettings().getPlaceholdersEnabledRanks());\n \n placeholderHooks.add(placeholderHook);\n if (updated) {\n getLogger().info(\"MVdWPlaceholderAPI found, added placeholders.\");\n }\n }\n \n Plugin clipPlaceholderApi = getServer().getPluginManager().getPlugin(\"PlaceholderAPI\");\n if (clipPlaceholderApi != null && clipPlaceholderApi.isEnabled()) {\n PlaceholderHook placeholderHook = new ClipPlaceholderAPIHook(this, playerReplacer, rankReplacer, lastReplacer);\n boolean updated = placeholderHook.initialize(getSettings().getPlaceholdersEnabledRanks());\n \n placeholderHooks.add(placeholderHook);\n if (updated) {\n getLogger().info(\"PlaceholderAPI found, added placeholders.\");\n }\n }\n }\n\n /**\n * Attempts to load plugin settings from disk. In the event of an error,\n * the plugin will disable all services until the settings have been\n * corrected.\n */\n public void loadSettings() {\n guiManager.closeInventories();\n\n try {\n // Attempt to load the plugin settings.\n settings.load();\n\n // Re-enable all plugin modules if currently inactive.\n if (!active) {\n services.forEach(PluginService::initialize);\n }\n\n // Update the plugin state to active.\n active = true;\n\n // Load all placeholders.\n loadPlaceholderHook();\n return;\n } catch (InvalidConfigurationException e) {\n getLogger().severe(\"Unable to load settings from config.yml\");\n getLogger().severe(\"The configuration you have provided has invalid syntax.\");\n getLogger().severe(\"Please correct your errors, then loadSettings the plugin.\");\n getLogger().log(Level.SEVERE, \"The errors are as follows:\", e);\n } catch (IOException e) {\n getLogger().severe(\"Unable to load settings from config.yml\");\n getLogger().severe(\"An I/O exception has occurred.\");\n getLogger().log(Level.SEVERE, \"The errors are as follows:\", e);\n }\n\n // Disable all services and update the plugin state.\n services.forEach(PluginService::terminate);\n active = false;\n }\n}", "public interface PluginService {\n\n /**\n * Initializes the service.\n */\n void initialize();\n\n /**\n * Terminates the service.\n */\n void terminate();\n\n}", "public enum RecalculateReason {\n\n COMMAND,\n UNLOAD,\n CLAIM,\n BREAK,\n PLACE,\n EXPLODE,\n CHEST\n\n}", "public enum WorthType {\n\n CHEST,\n PLAYER_BALANCE,\n FACTION_BALANCE,\n SPAWNER,\n BLOCK;\n\n private static final WorthType[] PLACED = {CHEST, SPAWNER, BLOCK};\n\n public static WorthType[] getPlaced() {\n return PLACED;\n }\n\n public static boolean isPlaced(WorthType worthType) {\n switch (worthType) {\n case PLAYER_BALANCE:\n case FACTION_BALANCE:\n return false;\n }\n return true;\n }\n}", "public class BlockPos {\n\n private final String world;\n private final int x;\n private final int y;\n private final int z;\n\n public static BlockPos of(Block block) {\n return new BlockPos(block.getWorld().getName(), block.getX(), block.getY(), block.getZ());\n }\n\n public static BlockPos of(String world, int x, int y, int z) {\n return new BlockPos(world, x, y, z);\n }\n\n private BlockPos(String world, int x, int y, int z) {\n this.world = world;\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n public String getWorld() {\n return world;\n }\n\n public int getX() {\n return x;\n }\n\n public int getY() {\n return y;\n }\n\n public int getZ() {\n return z;\n }\n\n public Block getBlock(Server server) {\n if (server.getWorld(world) == null) return null;\n return server.getWorld(world).getBlockAt(x, y, z);\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 BlockPos blockPos = (BlockPos) o;\n return x == blockPos.x &&\n Double.compare(blockPos.y, y) == 0 &&\n Double.compare(blockPos.z, z) == 0 &&\n Objects.equals(world, blockPos.world);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(world, x, y, z);\n }\n\n @Override\n public String toString() {\n return \"BlockPos{\" +\n \"world='\" + world + '\\'' +\n \", x=\" + x +\n \", y=\" + y +\n \", z=\" + z +\n '}';\n }\n}", "public class ChestWorth {\n\n private final double totalWorth;\n private final Map<Material, Integer> materials;\n private final Map<EntityType, Integer> spawners;\n\n public ChestWorth(double totalWorth, Map<Material, Integer> materials, Map<EntityType, Integer> spawners) {\n this.totalWorth = totalWorth;\n this.materials = materials;\n this.spawners = spawners;\n }\n\n public double getTotalWorth() {\n return totalWorth;\n }\n\n public Map<Material, Integer> getMaterials() {\n return materials;\n }\n\n public Map<EntityType, Integer> getSpawners() {\n return spawners;\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 ChestWorth that = (ChestWorth) o;\n return Double.compare(that.totalWorth, totalWorth) == 0 &&\n Objects.equals(materials, that.materials) &&\n Objects.equals(spawners, that.spawners);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(totalWorth, materials, spawners);\n }\n\n @Override\n public String toString() {\n return \"ChestWorth{\" +\n \"totalWorth=\" + totalWorth +\n \", materials=\" + materials +\n \", spawners=\" + spawners +\n '}';\n }\n}" ]
import com.google.common.collect.ImmutableMap; import net.novucs.ftop.FactionsTopPlugin; import net.novucs.ftop.PluginService; import net.novucs.ftop.RecalculateReason; import net.novucs.ftop.WorthType; import net.novucs.ftop.entity.BlockPos; import net.novucs.ftop.entity.ChestWorth; import net.novucs.ftop.hook.event.*; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Chest; import org.bukkit.block.CreatureSpawner; import org.bukkit.block.DoubleChest; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set;
package net.novucs.ftop.listener; public class WorthListener extends BukkitRunnable implements Listener, PluginService { private final FactionsTopPlugin plugin; private final Map<BlockPos, ChestWorth> chests = new HashMap<>(); private final Set<String> recentDisbands = new HashSet<>(); public WorthListener(FactionsTopPlugin plugin) { this.plugin = plugin; } @Override public void initialize() { plugin.getServer().getPluginManager().registerEvents(this, plugin); runTaskTimer(plugin, 1, 1); } @Override public void terminate() { HandlerList.unregisterAll(this); cancel(); } @Override public void run() { recentDisbands.clear(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void updateWorth(BlockPlaceEvent event) {
updateWorth(event.getBlock(), RecalculateReason.PLACE, false);
2
Gocnak/Botnak
src/main/java/face/Icons.java
[ "public class ChatPane implements DocumentListener {\n\n private JFrame poppedOutPane = null;\n\n // The timestamp of when we decided to wait to scroll back down\n private long scrollbarTimestamp = -1;\n\n public void setPoppedOutPane(JFrame pane) {\n poppedOutPane = pane;\n }\n\n public JFrame getPoppedOutPane() {\n return poppedOutPane;\n }\n\n public void createPopOut() {\n if (poppedOutPane == null) {\n JFrame frame = new JFrame(getPoppedOutTitle());\n frame.addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosed(WindowEvent e) {\n getScrollPane().setViewportView(scrollablePanel);\n scrollToBottom();\n setPoppedOutPane(null);\n }\n });\n JScrollPane pane = new JScrollPane();\n frame.setIconImage(new ImageIcon(getClass().getResource(\"/image/icon.png\")).getImage());\n pane.setViewportView(scrollablePanel);\n pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\n pane.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));\n frame.add(pane);\n frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n frame.pack();\n frame.setSize(750, 420);\n frame.setVisible(true);\n setPoppedOutPane(frame);\n }\n }\n\n /**\n * Keeps track of how many subs this channel gets.\n * TODO: make this a statistic that the user can output to a file (\"yesterday sub #\")\n */\n private int subCount = 0;\n\n private int viewerCount = -1;\n private int viewerPeak = 0;\n\n public void setViewerCount(int newCount) {\n if (newCount > viewerPeak) viewerPeak = newCount;\n viewerCount = newCount;\n if (getPoppedOutPane() != null) poppedOutPane.setTitle(getPoppedOutTitle());\n if (GUIMain.channelPane.getSelectedIndex() == index) GUIMain.updateTitle(getViewerCountString());\n }\n\n public String getPoppedOutTitle() {\n return chan + \" | \" + getViewerCountString();\n }\n\n public String getViewerCountString() {\n if (chan.equalsIgnoreCase(\"system logs\")) return null;\n if (viewerCount == -1) return \"Viewer count: Offline\";\n return String.format(\"Viewer count: %s (%s)\",\n NumberFormat.getInstance().format(viewerCount),\n NumberFormat.getInstance().format(viewerPeak));\n }\n\n /**\n * This is the main boolean to check to see if this tab should pulse.\n * <p>\n * This boolean checks to see if the tab wasn't toggled, if it's visible (not in a combined tab),\n * and if it's not selected.\n * <p>\n * The global setting will override this.\n *\n * @return True if this tab should pulse, else false.\n */\n public boolean shouldPulse() {\n boolean shouldPulseLocal = (this instanceof CombinedChatPane) ?\n ((CombinedChatPane) this).getActiveChatPane().shouldPulseLoc() : shouldPulseLoc;\n return Settings.showTabPulses.getValue() && shouldPulseLocal && isTabVisible() &&\n GUIMain.channelPane.getSelectedIndex() != index && index != 0;\n }\n\n private boolean shouldPulseLoc = true;\n\n /**\n * Determines if this tab should pulse.\n *\n * @return True if this tab is not toggled off, else false. (\"Tab Pulsing OFF\")\n */\n public boolean shouldPulseLoc() {\n return shouldPulseLoc;\n }\n\n /**\n * Sets the value for if this tab should pulse or not.\n *\n * @param newBool True (default) if tab pulsing should happen, else false if you wish to\n * toggle tab pulsing off.\n */\n public void setShouldPulse(boolean newBool) {\n shouldPulseLoc = newBool;\n }\n\n\n /**\n * Sets the pulsing boolean if this tab is starting to pulse.\n * <p>\n * Used by the TabPulse class.\n *\n * @param isPulsing True if the tab is starting to pulse, else false to stop pulsing.\n */\n public void setPulsing(boolean isPulsing) {\n this.isPulsing = isPulsing;\n }\n\n /**\n * Used by the TabPulse class.\n *\n * @return true if the chat pane is currently pulsing, else false.\n */\n public boolean isPulsing() {\n return isPulsing;\n }\n\n private boolean isPulsing = false;\n\n //credit to http://stackoverflow.com/a/4047794 for the below\n public boolean isScrollBarFullyExtended(JScrollBar vScrollBar) {\n BoundedRangeModel model = vScrollBar.getModel();\n return (model.getExtent() + model.getValue()) == model.getMaximum();\n }\n\n public void doScrollToBottom() {\n if (textPane.isVisible()) {\n Rectangle visibleRect = textPane.getVisibleRect();\n visibleRect.y = textPane.getHeight() - visibleRect.height;\n textPane.scrollRectToVisible(visibleRect);\n } else {\n textPane.setCaretPosition(textPane.getDocument().getLength());\n }\n }\n\n private boolean messageOut = false;\n\n @Override\n public void insertUpdate(DocumentEvent e) {\n maybeScrollToBottom();\n if (Settings.cleanupChat.getValue()) {\n try {\n if (e.getDocument().getText(e.getOffset(), e.getLength()).contains(\"\\n\")) {\n cleanupCounter++;\n }\n } catch (Exception ignored) {\n }\n if (cleanupCounter > Settings.chatMax.getValue()) {\n /* cleanup every n messages */\n if (!messageOut) {\n MessageQueue.addMessage(new Message().setType(Message.MessageType.CLEAR_TEXT).setExtra(this));\n messageOut = true;\n }\n }\n }\n }\n\n @Override\n public void removeUpdate(DocumentEvent e) {\n maybeScrollToBottom();\n }\n\n @Override\n public void changedUpdate(DocumentEvent e) {\n maybeScrollToBottom();\n }\n\n /**\n * Used to queue a scrollToBottom only if the scroll bar is already at the bottom\n * OR\n * It's been more than 10 seconds since we've been scrolled up and have been receiving messages\n */\n private void maybeScrollToBottom() {\n JScrollBar scrollBar = scrollPane.getVerticalScrollBar();\n boolean scrollBarAtBottom = isScrollBarFullyExtended(scrollBar);\n if (scrollBarAtBottom) {\n // We're back at the bottom, reset timer\n scrollbarTimestamp = -1;\n scrollToBottom();\n } else if (scrollbarTimestamp != -1) {\n if (System.currentTimeMillis() - scrollbarTimestamp >= 10 * 1000L) {\n // If the time difference is more than 10 seconds, scroll to bottom anyway after resetting time\n scrollbarTimestamp = -1;\n scrollToBottom();\n }\n } else {\n scrollbarTimestamp = System.currentTimeMillis();\n }\n }\n\n public void scrollToBottom() {\n // Push the call to \"scrollToBottom\" back TWO PLACES on the\n // AWT-EDT queue so that it runs *after* Swing has had an\n // opportunity to \"react\" to the appending of new text:\n // this ensures that we \"scrollToBottom\" only after a new\n // bottom has been recalculated during the natural\n // revalidation of the GUI that occurs after having\n // appending new text to the JTextArea.\n EventQueue.invokeLater(() -> EventQueue.invokeLater(this::doScrollToBottom));\n }\n\n private String chan;\n\n public String getChannel() {\n return chan;\n }\n\n private int index;\n\n public void setIndex(int newIndex) {\n index = newIndex;\n }\n\n public int getIndex() {\n return index;\n }\n\n private ScrollablePanel scrollablePanel;\n\n private JTextPane textPane;\n\n public JTextPane getTextPane() {\n return textPane;\n }\n\n private JScrollPane scrollPane;\n\n public JScrollPane getScrollPane() {\n return scrollPane;\n }\n\n public void setScrollPane(JScrollPane pane) {\n scrollPane = pane;\n }\n\n private boolean isTabVisible = true;\n\n public boolean isTabVisible() {\n return isTabVisible;\n }\n\n public void setTabVisible(boolean newBool) {\n isTabVisible = newBool;\n }\n\n private int cleanupCounter = 0;\n\n public void resetCleanupCounter() {\n cleanupCounter = 0;\n }\n\n //TODO make this be in 24 hour if they want\n final SimpleDateFormat format = new SimpleDateFormat(\"[h:mm a]\", Locale.getDefault());\n\n public String getTime() {\n return format.format(new Date(System.currentTimeMillis()));\n }\n\n /**\n * You initialize this class with the channel it's for and the text pane you'll be editing.\n *\n * @param channel The channel (\"name\") of this chat pane. Ex: \"System Logs\" or \"#gocnak\"\n * @param scrollPane The scroll pane for the tab.\n * @param pane The text pane that shows the messages for the given channel.\n * @param index The index of the pane in the main GUI.\n */\n public ChatPane(String channel, JScrollPane scrollPane, JTextPane pane, ScrollablePanel panel, int index) {\n chan = channel;\n textPane = pane;\n ((DefaultCaret) textPane.getCaret()).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);\n this.index = index;\n this.scrollPane = scrollPane;\n this.scrollablePanel = panel;\n textPane.getDocument().addDocumentListener(this);\n }\n\n public ChatPane() {\n //Used by the CombinedChatPane class, which calls its super anyways.\n }\n\n /**\n * This is the main message method when somebody sends a message to the channel.\n *\n * @param m The message from the chat.\n */\n public void onMessage(MessageWrapper m, boolean showChannel) {\n if (textPane == null) return;\n Message message = m.getLocal();\n long senderID = message.getSenderID();\n String channel = message.getChannel();\n String mess = message.getContent();\n boolean isMe = (message.getType() == Message.MessageType.ACTION_MESSAGE);\n try {\n print(m, \"\\n\" + getTime(), GUIMain.norm);\n User senderUser = Settings.channelManager.getUser(senderID, true);\n String sender = senderUser.getLowerNick();\n SimpleAttributeSet user = getUserSet(senderUser);\n if (channel.substring(1).equals(sender)) {\n insertIcon(m, IconEnum.BROADCASTER, null);\n }\n if (senderUser.isOp(channel))\n {\n if (!channel.substring(1).equals(sender) && !senderUser.isStaff() && !senderUser.isAdmin() && !senderUser.isGlobalMod())\n {//not the broadcaster again\n insertIcon(m, IconEnum.MOD, null);\n }\n }\n if (senderUser.isGlobalMod())\n {\n insertIcon(m, IconEnum.GLOBAL_MOD, null);\n }\n if (senderUser.isStaff())\n {\n insertIcon(m, IconEnum.STAFF, null);\n }\n if (senderUser.isAdmin())\n {\n insertIcon(m, IconEnum.ADMIN, null);\n }\n boolean isSubscriber = senderUser.isSubscriber(channel);\n if (isSubscriber) {\n insertIcon(m, IconEnum.SUBSCRIBER, channel);\n } else {\n if (Utils.isMainChannel(channel)) {\n Optional<Subscriber> sub = Settings.subscriberManager.getSubscriber(senderID);\n if (sub.isPresent() && !sub.get().isActive()) {\n insertIcon(m, IconEnum.EX_SUBSCRIBER, channel);\n }\n }\n }\n if (senderUser.isTurbo())\n {\n insertIcon(m, IconEnum.TURBO, null);\n }\n\n if (senderUser.isPrime())\n insertIcon(m, IconEnum.PRIME, null);\n\n if (senderUser.isVerified())\n insertIcon(m, IconEnum.VERIFIED, null);\n\n //Cheering\n int cheerTotal = senderUser.getCheer(channel);\n if (cheerTotal > 0)\n {\n insertIcon(m, Donor.getCheerStatus(cheerTotal), null);\n }\n\n // Third party donor\n if (Settings.showDonorIcons.getValue())\n {\n if (senderUser.isDonor())\n {\n insertIcon(m, senderUser.getDonationStatus(), null);\n }\n }\n\n //name stuff\n print(m, \" \", GUIMain.norm);\n SimpleAttributeSet userColor = new SimpleAttributeSet(user);\n FaceManager.handleNameFaces(senderID, user);\n print(m, senderUser.getDisplayName(), user);\n if (showChannel) {\n print(m, \" (\" + channel.substring(1) + \")\" + (isMe ? \" \" : \": \"), GUIMain.norm);\n } else {\n print(m, (!isMe ? \": \" : \" \"), userColor);\n }\n //keyword?\n SimpleAttributeSet set;\n if (Utils.mentionsKeyword(mess)) {\n set = Utils.getSetForKeyword(mess);\n } else {\n set = (isMe ? userColor : GUIMain.norm);\n }\n //URL, Faces, rest of message\n printMessage(m, mess, set, senderUser);\n\n if (BotnakTrayIcon.shouldDisplayMentions() && !Utils.isTabSelected(index)) {\n if (mess.toLowerCase().contains(Settings.accountManager.getUserAccount().getName().toLowerCase())) {\n GUIMain.getSystemTrayIcon().displayMention(m.getLocal());\n }\n }\n\n if (Utils.isMainChannel(channel))\n //check status of the sub, has it been a month?\n Settings.subscriberManager.updateSubscriber(senderUser, channel, isSubscriber);\n if (shouldPulse())\n GUIMain.instance.pulseTab(this);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n\n /**\n * Credit: TDuva\n * <p>\n * Cycles through message data, tagging things like Faces and URLs.\n *\n * @param text The message\n * @param style The default message style to use.\n */\n protected void printMessage(MessageWrapper m, String text, SimpleAttributeSet style, User u) {\n // Where stuff was found\n TreeMap<Integer, Integer> ranges = new TreeMap<>();\n // The style of the stuff (basically metadata)\n HashMap<Integer, SimpleAttributeSet> rangesStyle = new HashMap<>();\n\n findLinks(text, ranges, rangesStyle);\n findEmoticons(text, ranges, rangesStyle, u, m.getLocal().getChannel());\n\n // Actually print everything\n int lastPrintedPos = 0;\n for (Map.Entry<Integer, Integer> range : ranges.entrySet()) {\n int start = range.getKey();\n int end = range.getValue();\n if (start > lastPrintedPos) {\n // If there is anything between the special stuff, print that\n // first as regular text\n print(m, text.substring(lastPrintedPos, start), style);\n }\n print(m, text.substring(start, end + 1), rangesStyle.get(start));\n lastPrintedPos = end + 1;\n }\n // If anything is left, print that as well as regular text\n if (lastPrintedPos < text.length()) {\n print(m, text.substring(lastPrintedPos), style);\n }\n }\n\n private void findLinks(String text, Map<Integer, Integer> ranges, Map<Integer, SimpleAttributeSet> rangesStyle) {\n // Find links\n Constants.urlMatcher.reset(text);\n while (Constants.urlMatcher.find()) {\n int start = Constants.urlMatcher.start();\n int end = Constants.urlMatcher.end() - 1;\n if (!Utils.inRanges(start, ranges) && !Utils.inRanges(end, ranges)) {\n String foundUrl = Constants.urlMatcher.group();\n if (Utils.checkURL(foundUrl)) {\n ranges.put(start, end);\n rangesStyle.put(start, Utils.URLStyle(foundUrl));\n }\n }\n }\n }\n\n private void findEmoticons(String text, Map<Integer, Integer> ranges, Map<Integer, SimpleAttributeSet> rangesStyle, User u, String channel) {\n FaceManager.handleFaces(ranges, rangesStyle, text, FaceManager.FACE_TYPE.NORMAL_FACE, null, null);\n if (u != null && u.getEmotes() != null) {\n FaceManager.handleFaces(ranges, rangesStyle, text, FaceManager.FACE_TYPE.TWITCH_FACE, null, u.getEmotes());\n }\n if (Settings.ffzFacesEnable.getValue() && channel != null) {\n channel = channel.replaceAll(\"#\", \"\");\n FaceManager.handleFaces(ranges, rangesStyle, text, FaceManager.FACE_TYPE.FRANKER_FACE, channel, null);\n }\n }\n\n protected void print(MessageWrapper wrapper, String string, SimpleAttributeSet set) {\n if (textPane == null) return;\n Runnable r = () -> {\n try {\n textPane.getStyledDocument().insertString(textPane.getStyledDocument().getLength(), string, set);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n };\n wrapper.addPrint(r);\n }\n\n /**\n * Handles inserting icons before and after the message.\n *\n * @param m The message itself.\n * @param status IconEnum.Subscriber for sub message, else pass Donor#getDonationStatus(d#getAmount())\n */\n public void onIconMessage(MessageWrapper m, IconEnum status) {\n try {\n Message message = m.getLocal();\n print(m, \"\\n\", GUIMain.norm);\n for (int i = 0; i < 3; i++) {\n insertIcon(m, status, (status == IconEnum.SUBSCRIBER ? message.getChannel() : null));\n }\n print(m, \" \" + message.getContent() + (status == IconEnum.SUBSCRIBER ? (\" (\" + (subCount + 1) + \") \") : \" \"), GUIMain.norm);\n for (int i = 0; i < 3; i++) {\n insertIcon(m, status, (status == IconEnum.SUBSCRIBER ? message.getChannel() : null));\n }\n } catch (Exception e) {\n GUIMain.log(e);\n }\n boolean shouldIncrement = ((status == IconEnum.SUBSCRIBER) && (m.getLocal().getExtra() == null));//checking for repeat messages\n if (shouldIncrement) subCount++;\n }\n\n public void onSub(MessageWrapper m) {\n onIconMessage(m, IconEnum.SUBSCRIBER);\n }\n\n public void onWhisper(MessageWrapper m) {\n SimpleAttributeSet senderSet, receiverSet;\n\n long sender = m.getLocal().getSenderID();\n String receiver = (String) m.getLocal().getExtra();\n print(m, \"\\n\" + getTime(), GUIMain.norm);\n User senderUser = Settings.channelManager.getUser(sender, true);\n User receiverUser = Settings.channelManager.getUser(receiver, true);\n senderSet = getUserSet(senderUser);\n receiverSet = getUserSet(receiverUser);\n\n //name stuff\n print(m, \" \", GUIMain.norm);\n FaceManager.handleNameFaces(senderUser.getUserID(), senderSet);\n FaceManager.handleNameFaces(receiverUser.getUserID(), receiverSet);\n print(m, senderUser.getDisplayName(), senderSet);\n print(m, \" (whisper)-> \", GUIMain.norm);\n print(m, receiverUser.getDisplayName(), receiverSet);\n print(m, \": \", GUIMain.norm);\n\n printMessage(m, m.getLocal().getContent(), GUIMain.norm, senderUser);\n }\n\n private SimpleAttributeSet getUserSet(User u) {\n SimpleAttributeSet user = new SimpleAttributeSet();\n StyleConstants.setFontFamily(user, Settings.font.getValue().getFamily());\n StyleConstants.setFontSize(user, Settings.font.getValue().getSize());\n StyleConstants.setForeground(user, Utils.getColorFromUser(u));\n user.addAttribute(HTML.Attribute.NAME, u.getDisplayName());\n return user;\n }\n\n public void onDonation(MessageWrapper m) {\n Donation d = (Donation) m.getLocal().getExtra();\n onIconMessage(m, Donor.getDonationStatus(d.getAmount()));\n }\n\n public void onCheer(MessageWrapper m)\n {\n int bitsAmount = (int) m.getLocal().getExtra();\n String bitString = \"\" + bitsAmount + \" bit\" + (bitsAmount > 1 ? \"s\" : \"\") + \"!\";\n String cheerMessage = m.getLocal().getSenderName() + \" just cheered \" + bitString;\n String originalMessage = m.getLocal().getContent().replaceAll(\"(^|\\\\s?)cheer\\\\d+(\\\\s?|$)\", \" \").trim().replaceAll(\"\\\\s+\", \" \");\n\n //We're first going to send a \"hey they cheered\" message, then immediately follow it with their message\n // This requires overriding the content to be the cheer message first (for the icons), then replacing it back\n m.getLocal().setContent(cheerMessage);\n onIconMessage(m, Donor.getCheerAmountStatus(bitsAmount));\n\n //Let's get this message out there too, if they have one.\n if (originalMessage.length() > 0)\n {\n m.getLocal().setContent(originalMessage);\n onMessage(m, false);\n }\n }\n\n public void insertIcon(MessageWrapper m, IconEnum type, String channel) {\n SimpleAttributeSet attrs = new SimpleAttributeSet();\n Icons.BotnakIcon icon = Icons.getIcon(type, channel);\n StyleConstants.setIcon(attrs, icon.getImage());\n try {\n print(m, \" \", null);\n print(m, icon.getType().type, attrs);\n } catch (Exception e) {\n GUIMain.log(\"Exception in insertIcon: \");\n GUIMain.log(e);\n }\n }\n\n public String getText() {\n return (textPane != null && textPane.getText() != null) ? textPane.getText() : \"\";\n }\n\n // Source: http://stackoverflow.com/a/4628879\n // by http://stackoverflow.com/users/131872/camickr & Community\n public void cleanupChat() {\n if (scrollablePanel == null || scrollablePanel.getParent() == null) return;\n if (!(scrollablePanel.getParent() instanceof JViewport)) return;\n JViewport viewport = ((JViewport) scrollablePanel.getParent());\n Point startPoint = viewport.getViewPosition();\n // we are not deleting right before the visible area, but one screen behind\n // for convenience, otherwise flickering.\n if (startPoint == null) return;\n\n final int start = textPane.viewToModel(startPoint);\n if (start > 0) // not equal zero, because then we don't have to delete anything\n {\n final StyledDocument doc = textPane.getStyledDocument();\n try {\n if (Settings.logChat.getValue() && chan != null) {\n String[] toRemove = doc.getText(0, start).split(\"\\\\n\");\n Utils.logChat(toRemove, chan, 1);\n }\n doc.remove(0, start);\n resetCleanupCounter();\n } catch (Exception e) {\n GUIMain.log(\"Failed clearing chat: \");\n GUIMain.log(e);\n }\n }\n messageOut = false;\n }\n\n /**\n * Creates a pane of the given channel.\n *\n * @param channel The channel, also used as the key for the hashmap.\n * @return The created ChatPane.\n */\n public static ChatPane createPane(String channel) {\n JScrollPane scrollPane = new JScrollPane();\n scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\n JTextPane pane = new JTextPane();\n pane.setContentType(\"text/html; charset=UTF-8\");\n pane.setEditorKit(Constants.wrapEditorKit);\n pane.setEditable(false);\n pane.setFocusable(false);\n pane.setMargin(new Insets(0, 0, 0, 0));\n pane.setBackground(Color.black);\n pane.setFont(Settings.font.getValue());\n pane.addMouseListener(Constants.listenerURL);\n pane.addMouseListener(Constants.listenerName);\n pane.addMouseListener(Constants.listenerFace);\n ScrollablePanel sp = new ScrollablePanel();\n sp.add(pane, BorderLayout.SOUTH);\n scrollPane.setViewportView(sp);\n return new ChatPane(channel, scrollPane, pane, sp, GUIMain.channelPane.getTabCount() - 1);\n }\n\n /**\n * Deletes the pane and removes the tab from the tabbed pane.\n */\n public void deletePane() {\n if (Settings.logChat.getValue()) {\n Utils.logChat(getText().split(\"\\\\n\"), chan, 2);\n }\n GUIViewerList list = GUIMain.viewerLists.get(chan);\n if (list != null) {\n list.dispose();\n }\n if (getPoppedOutPane() != null) {\n getPoppedOutPane().dispose();\n }\n GUIMain.channelPane.removeTabAt(index);\n GUIMain.channelPane.setSelectedIndex(index - 1);\n }\n\n /**\n * Logs a message to this chat pane.\n *\n * @param message The message itself.\n * @param isSystem Whether the message is a system log message or not.\n */\n public void log(MessageWrapper message, boolean isSystem) {\n print(message, \"\\n\" + getTime(), GUIMain.norm);\n print(message, \" \" + (isSystem ? \"SYS: \" : \"\") + message.getLocal().getContent(), GUIMain.norm);\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof ChatPane && ((ChatPane) obj).index == this.index &&\n ((ChatPane) obj).getChannel().equals(this.getChannel());\n }\n}", "public class GUIMain extends JFrame {\n\n public static Map<Long, Color> userColMap;\n public static Map<String, Color> keywordMap;\n public static Set<Command> commandSet;\n public static Set<ConsoleCommand> conCommands;\n public static Set<String> channelSet;\n public static Map<String, ChatPane> chatPanes;\n public static Set<CombinedChatPane> combinedChatPanes;\n public static Set<TabPulse> tabPulses;\n public static Map<String, GUIViewerList> viewerLists;\n\n public static int userResponsesIndex = 0;\n public static ArrayList<String> userResponses;\n\n public static IRCBot bot;\n public static IRCViewer viewer;\n public static GUISettings settings = null;\n public static GUIStreams streams = null;\n public static GUIAbout aboutGUI = null;\n public static GUIStatus statusGUI = null;\n public static GUIRaffle raffleGUI = null;\n public static GUIVote voteGUI = null;\n\n public static boolean shutDown = false;\n\n public static SimpleAttributeSet norm = new SimpleAttributeSet();\n\n public static GUIMain instance;\n\n private static BotnakTrayIcon systemTrayIcon;\n\n public static Heartbeat heartbeat;\n\n private static ChatPane systemLogsPane;\n\n public GUIMain() {\n new MessageQueue();\n instance = this;\n channelSet = new CopyOnWriteArraySet<>();\n userColMap = new ConcurrentHashMap<>();\n commandSet = new CopyOnWriteArraySet<>();\n conCommands = new CopyOnWriteArraySet<>();\n keywordMap = new ConcurrentHashMap<>();\n tabPulses = new CopyOnWriteArraySet<>();\n combinedChatPanes = new CopyOnWriteArraySet<>();\n viewerLists = new ConcurrentHashMap<>();\n userResponses = new ArrayList<>();\n chatPanes = new ConcurrentHashMap<>();\n ThreadEngine.init();\n FaceManager.init();\n SoundEngine.init();\n StyleConstants.setForeground(norm, Color.white);\n StyleConstants.setFontFamily(norm, Settings.font.getValue().getFamily());\n StyleConstants.setFontSize(norm, Settings.font.getValue().getSize());\n StyleConstants.setBold(norm, Settings.font.getValue().isBold());\n StyleConstants.setItalic(norm, Settings.font.getValue().isItalic());\n initComponents();\n systemLogsPane = new ChatPane(\"System Logs\", allChatsScroll, allChats, null, 0);\n chatPanes.put(\"System Logs\", systemLogsPane);\n Settings.init();\n ThreadEngine.submit(() -> {\n Settings.load();\n if (Settings.stUseSystemTray.getValue()) getSystemTrayIcon();\n heartbeat = new Heartbeat();\n });\n }\n\n public static boolean loadedSettingsUser() {\n return Settings.accountManager != null && Settings.accountManager.getUserAccount() != null;\n }\n\n public static boolean loadedSettingsBot() {\n return Settings.accountManager != null && Settings.accountManager.getBotAccount() != null;\n }\n\n public static boolean loadedCommands() {\n return !commandSet.isEmpty();\n }\n\n public void chatButtonActionPerformed() {\n userResponsesIndex = 0;\n String channel = channelPane.getTitleAt(channelPane.getSelectedIndex());\n if (Settings.accountManager.getViewer() == null) {\n logCurrent(\"Failed to send message, there is no viewer account! Please set one up!\");\n return;\n }\n if (!Settings.accountManager.getViewer().isConnected()) {\n logCurrent(\"Failed to send message, currently trying to (re)connect!\");\n return;\n }\n String userInput = Utils.checkText(userChat.getText().replaceAll(\"\\n\", \"\"));\n if (channel != null && !channel.equalsIgnoreCase(\"system logs\") && !\"\".equals(userInput)) {\n CombinedChatPane ccp = Utils.getCombinedChatPane(channelPane.getSelectedIndex());\n boolean comboExists = ccp != null;\n if (comboExists) {\n List<String> channels = ccp.getActiveChannel().equalsIgnoreCase(\"All\") ?\n ccp.getChannels() : Collections.singletonList(ccp.getActiveChannel());\n\n for (String c : channels)\n Settings.accountManager.getViewer().sendMessage(\"#\" + c, userInput);\n\n if (!userResponses.contains(userInput))\n userResponses.add(userInput);\n }\n else\n {\n Settings.accountManager.getViewer().sendMessage(\"#\" + channel, userInput);\n if (!userResponses.contains(userInput))\n userResponses.add(userInput);\n }\n userChat.setText(\"\");\n }\n }\n\n /**\n * Wrapper for ensuring no null chat pane is produced due to hash tags.\n *\n * @param channel The channel, either inclusive of the hash tag or not.\n * @return The chat pane if existent, otherwise to System Logs to prevent null pointers.\n * (Botnak will just print out to System Logs the message that was eaten)\n */\n public static ChatPane getChatPane(String channel) {\n ChatPane toReturn = chatPanes.get(channel.replaceAll(\"#\", \"\"));\n return toReturn == null ? getSystemLogsPane() : toReturn;\n }\n\n /**\n * @return The System Logs chat pane.\n */\n public static ChatPane getSystemLogsPane() {\n return systemLogsPane;\n }\n\n /**\n * Logs a message to the current chat pane.\n *\n * @param message The message to log.\n */\n public static void logCurrent(Object message) {\n ChatPane current = getCurrentPane();\n if (message != null && chatPanes != null && !chatPanes.isEmpty() && current != null)\n MessageQueue.addMessage(new Message().setType(Message.MessageType.LOG_MESSAGE)\n .setContent(message.toString()).setExtra(current));\n }\n\n public static ChatPane getCurrentPane() {\n ChatPane toReturn;\n int index = channelPane.getSelectedIndex();\n if (index == 0) return getSystemLogsPane();\n toReturn = Utils.getChatPane(index);\n if (toReturn == null) {\n toReturn = Utils.getCombinedChatPane(index);\n }\n return toReturn == null ? getSystemLogsPane() : toReturn;\n }\n\n /**\n * Logs a message to the chat console under all white, SYS username.\n * This should only be used for serious reports, like exception reporting and\n * other status updates.\n *\n * @param message The message to log.\n */\n public static void log(Object message) {\n if (message == null) return;\n String toPrint;\n Message.MessageType type = Message.MessageType.LOG_MESSAGE; // Moved here to allow for changing message type to something like error for throwables\n if (message instanceof Throwable) {\n Throwable t = (Throwable) message;\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n t.printStackTrace(pw);\n toPrint = sw.toString(); // stack trace as a string\n pw.close();\n } else {\n // Not a throwable.. Darn strings\n toPrint = message.toString();\n }\n if (chatPanes == null || chatPanes.isEmpty()) {//allowing for errors to at least go somewhere\n System.out.println(toPrint == null ? \"Null toPrint!\" : toPrint);\n } else {\n MessageQueue.addMessage(new Message(toPrint, type));\n }\n }\n\n public static void updateTitle(String viewerCount) {\n StringBuilder stanSB = new StringBuilder();\n stanSB.append(\"Botnak \");\n if (viewerCount != null) {\n stanSB.append(\"| \");\n stanSB.append(viewerCount);\n stanSB.append(\" \");\n }\n if (Settings.accountManager != null) {\n if (Settings.accountManager.getUserAccount() != null) {\n stanSB.append(\"| User: \");\n stanSB.append(Settings.accountManager.getUserAccount().getName());\n }\n if (Settings.accountManager.getBotAccount() != null) {\n stanSB.append(\" | Bot: \");\n stanSB.append(Settings.accountManager.getBotAccount().getName());\n }\n }\n instance.setTitle(stanSB.toString());\n }\n\n public void exitButtonActionPerformed() {\n shutDown = true;\n if (viewer != null) {\n viewer.close(false);\n }\n if (bot != null) {\n bot.close(false);\n }\n if (!tabPulses.isEmpty()) {\n tabPulses.forEach(TabPulse::interrupt);\n tabPulses.clear();\n }\n if (systemTrayIcon != null) systemTrayIcon.close();\n SoundEngine.getEngine().close();\n Settings.save();\n heartbeat.interrupt();\n ThreadEngine.close();\n Set<Map.Entry<String, ChatPane>> entries = chatPanes.entrySet();\n for (Map.Entry<String, ChatPane> entry : entries)\n {\n String channel = entry.getKey();\n ChatPane pane = entry.getValue();\n if (Settings.logChat.getValue())\n {\n Utils.logChat(pane.getText().split(\"\\\\n\"), channel, 2);\n }\n }\n System.gc();\n dispose();\n System.exit(0);\n }\n\n\n public synchronized void pulseTab(ChatPane cp) {\n if (shutDown) return;\n if (cp.isPulsing()) return;\n TabPulse tp = new TabPulse(cp);\n tp.start();\n tabPulses.add(tp);\n }\n\n public static BotnakTrayIcon getSystemTrayIcon() {\n if (systemTrayIcon == null) systemTrayIcon = new BotnakTrayIcon();\n return systemTrayIcon;\n }\n\n\n private void openBotnakFolderOptionActionPerformed() {\n Utils.openWebPage(Settings.defaultDir.toURI().toString());\n }\n\n private void openLogViewerOptionActionPerformed() {\n // TODO add your code here\n }\n\n private void openSoundsOptionActionPerformed() {\n Utils.openWebPage(new File(Settings.defaultSoundDir.getValue()).toURI().toString());\n }\n\n private void autoReconnectToggleItemStateChanged(ItemEvent e) {\n Settings.autoReconnectAccounts.setValue(e.getStateChange() == ItemEvent.SELECTED);\n if (e.getStateChange() == ItemEvent.SELECTED) {\n if (viewer != null && viewer.getViewer() != null) {\n if (!viewer.getViewer().getConnection().isConnected())\n Settings.accountManager.createReconnectThread(viewer.getViewer().getConnection());\n }\n if (bot != null && bot.getBot() != null) {\n if (!bot.getBot().isConnected())\n Settings.accountManager.createReconnectThread(bot.getBot().getConnection());\n }\n }\n }\n\n private void alwaysOnTopToggleItemStateChanged(ItemEvent e) {\n Settings.alwaysOnTop.setValue(e.getStateChange() == ItemEvent.SELECTED);\n }\n\n public void updateAlwaysOnTopStatus(boolean newBool) {\n if (alwaysOnTopToggle.isSelected() != newBool) {\n alwaysOnTopToggle.setSelected(newBool);\n //this is going to be called from the setting load,\n //which will probably, in turn, fire another\n //change event, setting the setting to the same setting it is,\n //but since no change happens, this void is not called again,\n //and we can continue on in the original call\n }\n Window[] windows = getWindows();\n for (Window w : windows) {\n w.setAlwaysOnTop(newBool);\n }\n }\n\n private void settingsOptionActionPerformed() {\n if (settings == null) {\n settings = new GUISettings();\n }\n if (!settings.isVisible()) {\n settings.setVisible(true);\n }\n }\n\n private void startRaffleOptionActionPerformed() {\n if (raffleGUI == null)\n raffleGUI = new GUIRaffle();\n if (!raffleGUI.isVisible())\n raffleGUI.setVisible(true);\n else\n raffleGUI.toFront();\n }\n\n private void startVoteOptionActionPerformed() {\n if (voteGUI == null)\n voteGUI = new GUIVote();\n if (!voteGUI.isVisible())\n voteGUI.setVisible(true);\n else\n voteGUI.toFront();\n }\n\n private void soundsToggleItemStateChanged() {\n Response r = SoundEngine.getEngine().toggleSound(null, false);\n if (r.isSuccessful()) {\n if (bot != null && bot.getBot() != null) {\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n }\n }\n\n private void manageTextCommandsOptionActionPerformed() {\n // TODO add your code here\n }\n\n private void updateStatusOptionActionPerformed() {\n if (statusGUI == null) {\n statusGUI = new GUIStatus();\n }\n if (!statusGUI.isVisible()) {\n statusGUI.setVisible(true);\n }\n }\n\n private void subOnlyToggleItemStateChanged() {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n subOnlyToggle.isSelected() ? \"/subscribers\" : \"/subscribersoff\");\n }\n }\n\n private void projectGithubOptionActionPerformed() {\n Utils.openWebPage(\"https://github.com/Gocnak/Botnak/\");\n }\n\n private void projectWikiOptionActionPerformed() {\n Utils.openWebPage(\"https://github.com/Gocnak/Botnak/wiki\");\n }\n\n private void projectDetailsOptionActionPerformed() {\n if (aboutGUI == null) {\n aboutGUI = new GUIAbout();\n }\n if (!aboutGUI.isVisible())\n aboutGUI.setVisible(true);\n }\n\n public void updateSoundDelay(int secDelay) {\n if (secDelay > 1000)\n secDelay /= 1000;\n switch (secDelay) {\n case 0:\n soundDelayOffOption.setSelected(true);\n break;\n case 5:\n soundDelay5secOption.setSelected(true);\n break;\n case 10:\n soundDelay10secOption.setSelected(true);\n break;\n case 20:\n soundDelay20secOption.setSelected(true);\n break;\n default:\n soundDelayCustomOption.setSelected(true);\n soundDelayCustomOption.setText(String.format(\"Custom: %d seconds\", secDelay));\n break;\n }\n if (!soundDelayCustomOption.isSelected()) soundDelayCustomOption.setText(\"Custom (use chat)\");\n }\n\n public void updateSoundPermission(int permission) {\n switch (permission) {\n case 0:\n soundPermEveryoneOption.setSelected(true);\n break;\n case 1:\n soundPermSDMBOption.setSelected(true);\n break;\n case 2:\n soundPermDMBOption.setSelected(true);\n break;\n case 3:\n soundPermModAndBroadOption.setSelected(true);\n break;\n case 4:\n soundPermBroadOption.setSelected(true);\n break;\n default:\n break;\n }\n }\n\n public void updateSoundToggle(boolean newBool) {\n soundsToggle.setSelected(newBool);\n }\n\n public void updateSubsOnly(String num) {\n subOnlyToggle.setSelected(\"1\".equals(num));\n }\n\n public void updateSlowMode(String slowModeAmount) {\n switch (slowModeAmount) {\n case \"0\":\n slowModeOffOption.setSelected(true);\n break;\n case \"5\":\n slowMode5secOption.setSelected(true);\n break;\n case \"10\":\n slowMode10secOption.setSelected(true);\n break;\n case \"15\":\n slowMode15secOption.setSelected(true);\n break;\n case \"30\":\n slowMode30secOption.setSelected(true);\n break;\n default:\n slowModeCustomOption.setSelected(true);\n slowModeCustomOption.setText(\"Custom: \" + slowModeAmount + \" seconds\");\n break;\n }\n if (!slowModeCustomOption.isSelected()) slowModeCustomOption.setText(\"Custom (use chat)\");\n }\n\n public void updateBotReplyPerm(int perm) {\n switch (perm) {\n case 2:\n botReplyAll.setSelected(true);\n break;\n case 1:\n botReplyJustYou.setSelected(true);\n break;\n case 0:\n botReplyNobody.setSelected(true);\n break;\n default:\n break;\n }\n }\n\n private void initComponents() {\n // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents\n // Generated using JFormDesigner Evaluation license - Nick K\n menuBar1 = new JMenuBar();\n fileMenu = new JMenu();\n openBotnakFolderOption = new JMenuItem();\n openLogViewerOption = new JMenuItem();\n openSoundsOption = new JMenuItem();\n exitOption = new JMenuItem();\n preferencesMenu = new JMenu();\n botReplyMenu = new JMenu();\n botReplyAll = new JRadioButtonMenuItem();\n botReplyJustYou = new JRadioButtonMenuItem();\n botReplyNobody = new JRadioButtonMenuItem();\n autoReconnectToggle = new JCheckBoxMenuItem();\n alwaysOnTopToggle = new JCheckBoxMenuItem();\n settingsOption = new JMenuItem();\n toolsMenu = new JMenu();\n startRaffleOption = new JMenuItem();\n startVoteOption = new JMenuItem();\n soundsToggle = new JCheckBoxMenuItem();\n soundDelayMenu = new JMenu();\n soundDelayOffOption = new JRadioButtonMenuItem();\n soundDelay5secOption = new JRadioButtonMenuItem();\n soundDelay10secOption = new JRadioButtonMenuItem();\n soundDelay20secOption = new JRadioButtonMenuItem();\n soundDelayCustomOption = new JRadioButtonMenuItem();\n soundDelayCustomOption.setToolTipText(\"Set a custom sound delay with \\\"!setsound (time)\\\" in chat\");\n soundPermissionMenu = new JMenu();\n soundPermEveryoneOption = new JRadioButtonMenuItem();\n soundPermSDMBOption = new JRadioButtonMenuItem();\n soundPermDMBOption = new JRadioButtonMenuItem();\n soundPermModAndBroadOption = new JRadioButtonMenuItem();\n soundPermBroadOption = new JRadioButtonMenuItem();\n manageTextCommandsOption = new JMenuItem();\n runAdMenu = new JMenu();\n timeOption30sec = new JMenuItem();\n timeOption60sec = new JMenuItem();\n timeOption90sec = new JMenuItem();\n timeOption120sec = new JMenuItem();\n timeOption150sec = new JMenuItem();\n timeOption180sec = new JMenuItem();\n updateStatusOption = new JMenuItem();\n subOnlyToggle = new JCheckBoxMenuItem();\n slowModeMenu = new JMenu();\n slowModeOffOption = new JRadioButtonMenuItem();\n slowMode5secOption = new JRadioButtonMenuItem();\n slowMode10secOption = new JRadioButtonMenuItem();\n slowMode15secOption = new JRadioButtonMenuItem();\n slowMode30secOption = new JRadioButtonMenuItem();\n slowModeCustomOption = new JRadioButtonMenuItem();\n slowModeCustomOption.setToolTipText(\"Set a custom slow mode time with \\\"/slow (time in seconds)\\\" in chat\");\n helpMenu = new JMenu();\n projectGithubOption = new JMenuItem();\n projectWikiOption = new JMenuItem();\n projectDetailsOption = new JMenuItem();\n channelPane = new DraggableTabbedPane();\n allChatsScroll = new JScrollPane();\n allChats = new JTextPane();\n dankLabel = new JLabel();\n scrollPane1 = new JScrollPane();\n userChat = new JTextArea();\n\n //======== Botnak ========\n {\n setMinimumSize(new Dimension(640, 404));\n setName(\"Botnak Control Panel\");\n setTitle(\"Botnak | Please go to Preferences->Settings!\");\n setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n setIconImage(new ImageIcon(getClass().getResource(\"/image/icon.png\")).getImage());\n Container BotnakContentPane = getContentPane();\n\n //======== menuBar1 ========\n {\n\n //======== fileMenu ========\n {\n fileMenu.setText(\"File\");\n\n //---- openBotnakFolderOption ----\n openBotnakFolderOption.setText(\"Open Botnak Folder\");\n openBotnakFolderOption.addActionListener(e -> openBotnakFolderOptionActionPerformed());\n fileMenu.add(openBotnakFolderOption);\n\n //---- openLogViewerOption ----\n openLogViewerOption.setText(\"Open Log Viewer\");\n openLogViewerOption.addActionListener(e -> openLogViewerOptionActionPerformed());\n openLogViewerOption.setEnabled(false);//TODO\n fileMenu.add(openLogViewerOption);\n\n //---- openSoundsOption ----\n openSoundsOption.setText(\"Open Sound Directory\");\n openSoundsOption.addActionListener(e -> openSoundsOptionActionPerformed());\n fileMenu.add(openSoundsOption);\n fileMenu.addSeparator();\n\n //---- exitOption ----\n exitOption.setText(\"Save and Exit\");\n exitOption.addActionListener(e -> exitButtonActionPerformed());\n fileMenu.add(exitOption);\n }\n menuBar1.add(fileMenu);\n\n //======== preferencesMenu ========\n {\n preferencesMenu.setText(\"Preferences\");\n\n //======== botReplyMenu ========\n {\n botReplyMenu.setText(\"Bot Reply\");\n\n //---- botReplyAll ----\n botReplyAll.setText(\"Reply to all\");\n botReplyAll.addActionListener(e -> {\n if (bot != null) {\n Response r = bot.parseReplyType(\"2\", Settings.accountManager.getUserAccount().getName());\n logCurrent(r.getResponseText());\n }\n });\n botReplyMenu.add(botReplyAll);\n\n //---- botReplyJustYou ----\n botReplyJustYou.setText(\"Reply to you\");\n botReplyJustYou.addActionListener(e -> {\n if (bot != null) {\n Response r = bot.parseReplyType(\"1\", Settings.accountManager.getUserAccount().getName());\n logCurrent(r.getResponseText());\n }\n });\n botReplyMenu.add(botReplyJustYou);\n\n //---- botReplyNobody ----\n botReplyNobody.setText(\"Reply to none\");\n botReplyNobody.addActionListener(e -> {\n if (bot != null) {\n Response r = bot.parseReplyType(\"0\", Settings.accountManager.getUserAccount().getName());\n logCurrent(r.getResponseText());\n }\n });\n botReplyNobody.setSelected(true);\n botReplyMenu.add(botReplyNobody);\n }\n preferencesMenu.add(botReplyMenu);\n\n //---- autoReconnectToggle ----\n autoReconnectToggle.setText(\"Auto-Reconnect\");\n autoReconnectToggle.setSelected(true);\n autoReconnectToggle.addItemListener(this::autoReconnectToggleItemStateChanged);\n preferencesMenu.add(autoReconnectToggle);\n\n //---- alwaysOnTopToggle ----\n alwaysOnTopToggle.setText(\"Always On Top\");\n alwaysOnTopToggle.setSelected(false);\n alwaysOnTopToggle.addItemListener(this::alwaysOnTopToggleItemStateChanged);\n preferencesMenu.add(alwaysOnTopToggle);\n preferencesMenu.addSeparator();\n\n //---- settingsOption ----\n settingsOption.setText(\"Settings...\");\n settingsOption.addActionListener(e -> settingsOptionActionPerformed());\n preferencesMenu.add(settingsOption);\n }\n menuBar1.add(preferencesMenu);\n\n //======== toolsMenu ========\n {\n toolsMenu.setText(\"Tools\");\n\n //---- startRaffleOption ----\n startRaffleOption.setText(\"Create Raffle...\");\n startRaffleOption.addActionListener(e -> startRaffleOptionActionPerformed());\n toolsMenu.add(startRaffleOption);\n\n //---- startVoteOption ----\n startVoteOption.setText(\"Create Vote...\");\n startVoteOption.addActionListener(e -> startVoteOptionActionPerformed());\n toolsMenu.add(startVoteOption);\n\n //---- soundsToggle ----\n soundsToggle.setText(\"Enable Sounds\");\n soundsToggle.setSelected(true);\n soundsToggle.addActionListener(e -> soundsToggleItemStateChanged());\n toolsMenu.add(soundsToggle);\n\n //======== soundDelayMenu ========\n {\n soundDelayMenu.setText(\"Sound Delay\");\n\n //---- soundDelayOffOption ----\n soundDelayOffOption.setText(\"None (Off)\");\n soundDelayOffOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null && Settings.soundEngineDelay.getValue() != 0)\n {\n Response r = SoundEngine.getEngine().setSoundDelay(\"0\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundDelayMenu.add(soundDelayOffOption);\n\n //---- soundDelay5secOption ----\n soundDelay5secOption.setText(\"5 seconds\");\n soundDelay5secOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null && Settings.soundEngineDelay.getValue() != 5000)\n {\n Response r = SoundEngine.getEngine().setSoundDelay(\"5\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundDelayMenu.add(soundDelay5secOption);\n\n //---- soundDelay10secOption ----\n soundDelay10secOption.setText(\"10 seconds\");\n soundDelay10secOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null && Settings.soundEngineDelay.getValue() != 10000)\n {\n Response r = SoundEngine.getEngine().setSoundDelay(\"10\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundDelay10secOption.setSelected(true);\n soundDelayMenu.add(soundDelay10secOption);\n\n //---- soundDelay20secOption ----\n soundDelay20secOption.setText(\"20 seconds\");\n soundDelay20secOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null && Settings.soundEngineDelay.getValue() != 20000)\n {\n Response r = SoundEngine.getEngine().setSoundDelay(\"20\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundDelayMenu.add(soundDelay20secOption);\n\n //---- soundDelayCustomOption ----\n soundDelayCustomOption.setText(\"Custom (Use chat)\");\n soundDelayCustomOption.setEnabled(false);\n soundDelayMenu.add(soundDelayCustomOption);\n }\n toolsMenu.add(soundDelayMenu);\n\n //======== soundPermissionMenu ========\n {\n soundPermissionMenu.setText(\"Sound Permission\");\n\n //---- soundPermEveryoneOption ----\n soundPermEveryoneOption.setText(\"Everyone\");\n soundPermEveryoneOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = SoundEngine.getEngine().setSoundPermission(\"0\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundPermissionMenu.add(soundPermEveryoneOption);\n\n //---- soundPermSDMBOption ----\n soundPermSDMBOption.setText(\"Subs, Donors, Mods, Broadcaster\");\n soundPermSDMBOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = SoundEngine.getEngine().setSoundPermission(\"1\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundPermSDMBOption.setSelected(true);\n soundPermissionMenu.add(soundPermSDMBOption);\n\n //---- soundPermDMBOption ----\n soundPermDMBOption.setText(\"Donors, Mods, Broadcaster\");\n soundPermDMBOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = SoundEngine.getEngine().setSoundPermission(\"2\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundPermissionMenu.add(soundPermDMBOption);\n\n //---- soundPermModAndBroadOption ----\n soundPermModAndBroadOption.setText(\"Mods and Broadcaster Only\");\n soundPermModAndBroadOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = SoundEngine.getEngine().setSoundPermission(\"3\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundPermissionMenu.add(soundPermModAndBroadOption);\n\n //---- soundPermBroadOption ----\n soundPermBroadOption.setText(\"Broadcaster Only\");\n soundPermBroadOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = SoundEngine.getEngine().setSoundPermission(\"4\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundPermissionMenu.add(soundPermBroadOption);\n }\n toolsMenu.add(soundPermissionMenu);\n\n //---- manageTextCommandsOption ----\n manageTextCommandsOption.setText(\"Manage Text Commands...\");\n manageTextCommandsOption.setEnabled(false);//TODO\n manageTextCommandsOption.addActionListener(e -> manageTextCommandsOptionActionPerformed());\n toolsMenu.add(manageTextCommandsOption);\n toolsMenu.addSeparator();\n\n //======== runAdMenu ========\n {\n runAdMenu.setText(\"Run Ad\");\n\n //---- timeOption30sec ----\n timeOption30sec.setText(\"30 sec\");\n timeOption30sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"30\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(30000);\n logCurrent(\"The 30-second advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption30sec);\n\n //---- timeOption60sec ----\n timeOption60sec.setText(\"1 min\");\n timeOption60sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"1m\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(60000);\n logCurrent(\"The 1-minute advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption60sec);\n\n //---- timeOption90sec ----\n timeOption90sec.setText(\"1 min 30 sec\");\n timeOption90sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"1m30s\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(90000);\n logCurrent(\"The 1-minute 30-second advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption90sec);\n\n //---- timeOption120sec ----\n timeOption120sec.setText(\"2 min\");\n timeOption120sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"2m\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(120000);\n logCurrent(\"The 2 minute advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption120sec);\n\n //---- timeOption150sec ----\n timeOption150sec.setText(\"2 min 30 sec\");\n timeOption150sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"2m30s\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(150000);\n logCurrent(\"The 2 minute 30 second advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption150sec);\n\n //---- timeOption180sec ----\n timeOption180sec.setText(\"3 min\");\n timeOption180sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"3m\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(180000);\n logCurrent(\"The 3 minute advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption180sec);\n }\n toolsMenu.add(runAdMenu);\n\n //---- updateStatusOption ----\n updateStatusOption.setText(\"Update Status...\");\n updateStatusOption.addActionListener(e -> updateStatusOptionActionPerformed());\n toolsMenu.add(updateStatusOption);\n\n //---- subOnlyToggle ----\n subOnlyToggle.setText(\"Sub-only Chat\");\n subOnlyToggle.addActionListener(e -> subOnlyToggleItemStateChanged());\n toolsMenu.add(subOnlyToggle);\n\n //======== slowModeMenu ========\n {\n slowModeMenu.setText(\"Slow Mode\");\n\n //---- slowModeOffOption ----\n slowModeOffOption.setText(\"Off\");\n slowModeOffOption.addActionListener(e -> {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n \"/slowoff\");\n }\n });\n slowModeOffOption.setSelected(true);\n slowModeMenu.add(slowModeOffOption);\n\n //---- slowMode5secOption ----\n slowMode5secOption.setText(\"5 seconds\");\n slowMode5secOption.addActionListener(e -> {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n \"/slow 5\");\n }\n });\n slowModeMenu.add(slowMode5secOption);\n\n //---- slowMode10secOption ----\n slowMode10secOption.setText(\"10 seconds\");\n slowMode10secOption.addActionListener(e -> {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n \"/slow 10\");\n }\n });\n slowModeMenu.add(slowMode10secOption);\n\n //---- slowMode15secOption ----\n slowMode15secOption.setText(\"15 seconds\");\n slowMode15secOption.addActionListener(e -> {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n \"/slow 15\");\n }\n });\n slowModeMenu.add(slowMode15secOption);\n\n //---- slowMode30secOption ----\n slowMode30secOption.setText(\"30 seconds\");\n slowMode30secOption.addActionListener(e -> {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n \"/slow 30\");\n }\n });\n slowModeMenu.add(slowMode30secOption);\n\n //---- slowModeCustomOption ----\n slowModeCustomOption.setText(\"Custom (use chat)\");\n slowModeCustomOption.setEnabled(false);\n slowModeMenu.add(slowModeCustomOption);\n }\n toolsMenu.add(slowModeMenu);\n }\n menuBar1.add(toolsMenu);\n\n //======== helpMenu ========\n {\n helpMenu.setText(\"Help\");\n\n //---- projectGithubOption ----\n projectGithubOption.setText(\"Botnak Github\");\n projectGithubOption.addActionListener(e -> projectGithubOptionActionPerformed());\n helpMenu.add(projectGithubOption);\n\n //---- projectWikiOption ----\n projectWikiOption.setText(\"Botnak Wiki\");\n projectWikiOption.addActionListener(e -> projectWikiOptionActionPerformed());\n helpMenu.add(projectWikiOption);\n JMenuItem bugReport = new JMenuItem(\"Report an Issue\");\n bugReport.addActionListener(e -> Utils.openWebPage(\"https://github.com/Gocnak/Botnak/issues/new\"));\n helpMenu.add(bugReport);\n helpMenu.addSeparator();\n\n //---- projectDetailsOption ----\n projectDetailsOption.setText(\"About...\");\n projectDetailsOption.addActionListener(e -> projectDetailsOptionActionPerformed());\n helpMenu.add(projectDetailsOption);\n }\n menuBar1.add(helpMenu);\n }\n setJMenuBar(menuBar1);\n\n //======== channelPane ========\n {\n channelPane.setFocusable(false);\n channelPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);\n channelPane.setAutoscrolls(true);\n channelPane.addChangeListener(Constants.tabListener);\n channelPane.addMouseListener(Constants.tabListener);\n\n //======== allChatsScroll ========\n {\n allChatsScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\n\n //---- allChats ----\n allChats.setEditable(false);\n allChats.setForeground(Color.white);\n allChats.setBackground(Color.black);\n allChats.setFont(new Font(\"Calibri\", Font.PLAIN, 16));\n allChats.setMargin(new Insets(0, 0, 0, 0));\n allChats.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);\n allChats.addMouseListener(Constants.listenerURL);\n allChats.addMouseListener(Constants.listenerName);\n allChats.setEditorKit(Constants.wrapEditorKit);\n allChatsScroll.setViewportView(allChats);\n }\n channelPane.addTab(\"System Logs\", allChatsScroll);\n\n //---- dankLabel ----\n dankLabel.setText(\"Dank memes\");\n channelPane.addTab(\"+\", dankLabel);\n channelPane.setEnabledAt(channelPane.getTabCount() - 1, false);\n channelPane.addMouseListener(new NewTabListener());\n }\n\n //======== scrollPane1 ========\n {\n scrollPane1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\n\n //---- userChat ----\n userChat.setFont(new Font(\"Consolas\", Font.PLAIN, 12));\n userChat.setLineWrap(true);\n userChat.setWrapStyleWord(true);\n userChat.addKeyListener(new ListenerUserChat(userChat));\n scrollPane1.setViewportView(userChat);\n }\n\n GroupLayout BotnakContentPaneLayout = new GroupLayout(BotnakContentPane);\n BotnakContentPane.setLayout(BotnakContentPaneLayout);\n BotnakContentPaneLayout.setHorizontalGroup(\n BotnakContentPaneLayout.createParallelGroup()\n .addComponent(channelPane, GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE)\n .addComponent(scrollPane1)\n );\n BotnakContentPaneLayout.setVerticalGroup(\n BotnakContentPaneLayout.createParallelGroup()\n .addGroup(BotnakContentPaneLayout.createSequentialGroup()\n .addComponent(channelPane, GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)\n .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE))\n );\n addComponentListener(new ComponentAdapter() {\n @Override\n public void componentResized(ComponentEvent e) {\n if (channelPane != null) {\n channelPane.scrollDownPanes();\n }\n }\n });\n addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosing(WindowEvent e) {\n exitButtonActionPerformed();\n }\n });\n pack();\n setLocationRelativeTo(getOwner());\n }\n\n //---- botReplyGroup ----\n ButtonGroup botReplyGroup = new ButtonGroup();\n botReplyGroup.add(botReplyAll);\n botReplyGroup.add(botReplyJustYou);\n botReplyGroup.add(botReplyNobody);\n\n //---- soundDelayGroup ----\n ButtonGroup soundDelayGroup = new ButtonGroup();\n soundDelayGroup.add(soundDelayOffOption);\n soundDelayGroup.add(soundDelay5secOption);\n soundDelayGroup.add(soundDelay10secOption);\n soundDelayGroup.add(soundDelay20secOption);\n soundDelayGroup.add(soundDelayCustomOption);\n\n //---- soundPermissionGroup ----\n ButtonGroup soundPermissionGroup = new ButtonGroup();\n soundPermissionGroup.add(soundPermEveryoneOption);\n soundPermissionGroup.add(soundPermSDMBOption);\n soundPermissionGroup.add(soundPermDMBOption);\n soundPermissionGroup.add(soundPermModAndBroadOption);\n soundPermissionGroup.add(soundPermBroadOption);\n\n //---- slowModeGroup ----\n ButtonGroup slowModeGroup = new ButtonGroup();\n slowModeGroup.add(slowModeOffOption);\n slowModeGroup.add(slowMode5secOption);\n slowModeGroup.add(slowMode10secOption);\n slowModeGroup.add(slowMode15secOption);\n slowModeGroup.add(slowMode30secOption);\n slowModeGroup.add(slowModeCustomOption);\n // JFormDesigner - End of component initialization //GEN-END:initComponents\n }\n\n // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables\n // Generated using JFormDesigner Evaluation license - Nick K\n private JMenuBar menuBar1;\n private JMenu fileMenu;\n private JMenuItem openBotnakFolderOption;\n private JMenuItem openLogViewerOption;\n private JMenuItem openSoundsOption;\n private JMenuItem exitOption;\n private JMenu preferencesMenu;\n private JMenu botReplyMenu;\n private JRadioButtonMenuItem botReplyAll;\n private JRadioButtonMenuItem botReplyJustYou;\n private JRadioButtonMenuItem botReplyNobody;\n private JCheckBoxMenuItem autoReconnectToggle;\n public JCheckBoxMenuItem alwaysOnTopToggle;\n private JMenuItem settingsOption;\n private JMenu toolsMenu;\n private JMenuItem startRaffleOption;\n private JMenuItem startVoteOption;\n private JCheckBoxMenuItem soundsToggle;\n private JMenu soundDelayMenu;\n private JRadioButtonMenuItem soundDelayOffOption;\n private JRadioButtonMenuItem soundDelay5secOption;\n private JRadioButtonMenuItem soundDelay10secOption;\n private JRadioButtonMenuItem soundDelay20secOption;\n private JRadioButtonMenuItem soundDelayCustomOption;\n private JMenu soundPermissionMenu;\n private JRadioButtonMenuItem soundPermEveryoneOption;\n private JRadioButtonMenuItem soundPermSDMBOption;\n private JRadioButtonMenuItem soundPermDMBOption;\n private JRadioButtonMenuItem soundPermModAndBroadOption;\n private JRadioButtonMenuItem soundPermBroadOption;\n private JMenuItem manageTextCommandsOption;\n public JMenu runAdMenu;\n private JMenuItem timeOption30sec;\n private JMenuItem timeOption60sec;\n private JMenuItem timeOption90sec;\n private JMenuItem timeOption120sec;\n private JMenuItem timeOption150sec;\n private JMenuItem timeOption180sec;\n public JMenuItem updateStatusOption;\n private JCheckBoxMenuItem subOnlyToggle;\n private JMenu slowModeMenu;\n private JRadioButtonMenuItem slowModeOffOption;\n private JRadioButtonMenuItem slowMode5secOption;\n private JRadioButtonMenuItem slowMode10secOption;\n private JRadioButtonMenuItem slowMode15secOption;\n private JRadioButtonMenuItem slowMode30secOption;\n private JRadioButtonMenuItem slowModeCustomOption;\n private JMenu helpMenu;\n private JMenuItem projectGithubOption;\n private JMenuItem projectWikiOption;\n private JMenuItem projectDetailsOption;\n public static DraggableTabbedPane channelPane;\n private JScrollPane allChatsScroll;\n private JTextPane allChats;\n private JLabel dankLabel;\n private JScrollPane scrollPane1;\n public static JTextArea userChat;\n}", "@SuppressWarnings(\"unused\")\npublic class Scalr {\n /**\n * System property name used to define the debug boolean flag.\n * <p>\n * Value is \"<code>imgscalr.debug</code>\".\n */\n public static final String DEBUG_PROPERTY_NAME = \"imgscalr.debug\";\n\n /**\n * System property name used to define a custom log prefix.\n * <p>\n * Value is \"<code>imgscalr.logPrefix</code>\".\n */\n public static final String LOG_PREFIX_PROPERTY_NAME = \"imgscalr.logPrefix\";\n\n /**\n * Flag used to indicate if debugging output has been enabled by setting the\n * \"<code>imgscalr.debug</code>\" system property to <code>true</code>. This\n * value will be <code>false</code> if the \"<code>imgscalr.debug</code>\"\n * system property is undefined or set to <code>false</code>.\n * <p>\n * This property can be set on startup with:<br/>\n * <code>\n * -Dimgscalr.debug=true\n * </code> or by calling {@link System#setProperty(String, String)} to set a\n * new property value for {@link #DEBUG_PROPERTY_NAME} before this class is\n * loaded.\n * <p>\n * Default value is <code>false</code>.\n */\n public static final boolean DEBUG = Boolean.getBoolean(DEBUG_PROPERTY_NAME);\n\n /**\n * Prefix to every log message this library logs. Using a well-defined\n * prefix helps make it easier both visually and programmatically to scan\n * log files for messages produced by this library.\n * <p>\n * This property can be set on startup with:<br/>\n * <code>\n * -Dimgscalr.logPrefix=&lt;YOUR PREFIX HERE&gt;\n * </code> or by calling {@link System#setProperty(String, String)} to set a\n * new property value for {@link #LOG_PREFIX_PROPERTY_NAME} before this\n * class is loaded.\n * <p>\n * Default value is \"<code>[imgscalr] </code>\" (including the space).\n */\n public static final String LOG_PREFIX = System.getProperty(\n LOG_PREFIX_PROPERTY_NAME, \"[imgscalr] \");\n\n /**\n * A {@link ConvolveOp} using a very light \"blur\" kernel that acts like an\n * anti-aliasing filter (softens the image a bit) when applied to an image.\n * <p>\n * A common request by users of the library was that they wished to \"soften\"\n * resulting images when scaling them down drastically. After quite a bit of\n * A/B testing, the kernel used by this Op was selected as the closest match\n * for the target which was the softer results from the deprecated\n * {@link AreaAveragingScaleFilter} (which is used internally by the\n * deprecated {@link Image#getScaledInstance(int, int, int)} method in the\n * JDK that imgscalr is meant to replace).\n * <p>\n * This ConvolveOp uses a 3x3 kernel with the values:\n * <table cellpadding=\"4\" border=\"1\">\n * <tr>\n * <td>.0f</td>\n * <td>.08f</td>\n * <td>.0f</td>\n * </tr>\n * <tr>\n * <td>.08f</td>\n * <td>.68f</td>\n * <td>.08f</td>\n * </tr>\n * <tr>\n * <td>.0f</td>\n * <td>.08f</td>\n * <td>.0f</td>\n * </tr>\n * </table>\n * <p>\n * For those that have worked with ConvolveOps before, this Op uses the\n * {@link ConvolveOp#EDGE_NO_OP} instruction to not process the pixels along\n * the very edge of the image (otherwise EDGE_ZERO_FILL would create a\n * black-border around the image). If you have not worked with a ConvolveOp\n * before, it just means this default OP will \"do the right thing\" and not\n * give you garbage results.\n * <p>\n * This ConvolveOp uses no {@link RenderingHints} values as internally the\n * {@link ConvolveOp} class only uses hints when doing a color conversion\n * between the source and destination {@link BufferedImage} targets.\n * imgscalr allows the {@link ConvolveOp} to create its own destination\n * image every time, so no color conversion is ever needed and thus no\n * hints.\n * <h3>Performance</h3>\n * Use of this (and other) {@link ConvolveOp}s are hardware accelerated when\n * possible. For more information on if your image op is hardware\n * accelerated or not, check the source code of the underlying JDK class\n * that actually executes the Op code, <a href=\n * \"http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html\"\n * >sun.awt.image.ImagingLib</a>.\n * <h3>Known Issues</h3>\n * In all versions of Java (tested up to Java 7 preview Build 131), running\n * this op against a GIF with transparency and attempting to save the\n * resulting image as a GIF results in a corrupted/empty file. The file must\n * be saved out as a PNG to maintain the transparency.\n *\n * @since 3.0\n */\n public static final ConvolveOp OP_ANTIALIAS = new ConvolveOp(\n new Kernel(3, 3, new float[]{.0f, .08f, .0f, .08f, .68f, .08f,\n .0f, .08f, .0f}), ConvolveOp.EDGE_NO_OP, null\n );\n\n /**\n * A {@link RescaleOp} used to make any input image 10% darker.\n * <p>\n * This operation can be applied multiple times in a row if greater than 10%\n * changes in brightness are desired.\n *\n * @since 4.0\n */\n public static final RescaleOp OP_DARKER = new RescaleOp(0.9f, 0, null);\n\n /**\n * A {@link RescaleOp} used to make any input image 10% brighter.\n * <p>\n * This operation can be applied multiple times in a row if greater than 10%\n * changes in brightness are desired.\n *\n * @since 4.0\n */\n public static final RescaleOp OP_BRIGHTER = new RescaleOp(1.1f, 0, null);\n\n /**\n * A {@link ColorConvertOp} used to convert any image to a grayscale color\n * palette.\n * <p>\n * Applying this op multiple times to the same image has no compounding\n * effects.\n *\n * @since 4.0\n */\n public static final ColorConvertOp OP_GRAYSCALE = new ColorConvertOp(\n ColorSpace.getInstance(ColorSpace.CS_GRAY), null);\n\n /**\n * Static initializer used to prepare some of the variables used by this\n * class.\n */\n static {\n log(0, \"Debug output ENABLED\");\n }\n\n /**\n * Used to define the different scaling hints that the algorithm can use.\n *\n * @author Riyad Kalla ([email protected])\n * @since 1.1\n */\n public enum Method {\n /**\n * Used to indicate that the scaling implementation should decide which\n * method to use in order to get the best looking scaled image in the\n * least amount of time.\n * <p>\n * The scaling algorithm will use the\n * {@link Scalr#THRESHOLD_QUALITY_BALANCED} or\n * {@link Scalr#THRESHOLD_BALANCED_SPEED} thresholds as cut-offs to\n * decide between selecting the <code>QUALITY</code>,\n * <code>BALANCED</code> or <code>SPEED</code> scaling algorithms.\n * <p>\n * By default the thresholds chosen will give nearly the best looking\n * result in the fastest amount of time. We intend this method to work\n * for 80% of people looking to scale an image quickly and get a good\n * looking result.\n */\n AUTOMATIC,\n /**\n * Used to indicate that the scaling implementation should scale as fast\n * as possible and return a result. For smaller images (800px in size)\n * this can result in noticeable aliasing but it can be a few magnitudes\n * times faster than using the QUALITY method.\n */\n SPEED,\n /**\n * Used to indicate that the scaling implementation should use a scaling\n * operation balanced between SPEED and QUALITY. Sometimes SPEED looks\n * too low quality to be useful (e.g. text can become unreadable when\n * scaled using SPEED) but using QUALITY mode will increase the\n * processing time too much. This mode provides a \"better than SPEED\"\n * quality in a \"less than QUALITY\" amount of time.\n */\n BALANCED,\n /**\n * Used to indicate that the scaling implementation should do everything\n * it can to create as nice of a result as possible. This approach is\n * most important for smaller pictures (800px or smaller) and less\n * important for larger pictures as the difference between this method\n * and the SPEED method become less and less noticeable as the\n * source-image size increases. Using the AUTOMATIC method will\n * automatically prefer the QUALITY method when scaling an image down\n * below 800px in size.\n */\n QUALITY,\n /**\n * Used to indicate that the scaling implementation should go above and\n * beyond the work done by {@link Method#QUALITY} to make the image look\n * exceptionally good at the cost of more processing time. This is\n * especially evident when generating thumbnails of images that look\n * jagged with some of the other {@link Method}s (even\n * {@link Method#QUALITY}).\n */\n ULTRA_QUALITY\n }\n\n /**\n * Used to define the different modes of resizing that the algorithm can\n * use.\n *\n * @author Riyad Kalla ([email protected])\n * @since 3.1\n */\n public enum Mode {\n /**\n * Used to indicate that the scaling implementation should calculate\n * dimensions for the resultant image by looking at the image's\n * orientation and generating proportional dimensions that best fit into\n * the target width and height given\n * <p>\n * See \"Image Proportions\" in the {@link Scalr} class description for\n * more detail.\n */\n AUTOMATIC,\n /**\n * Used to fit the image to the exact dimensions given regardless of the\n * image's proportions. If the dimensions are not proportionally\n * correct, this will introduce vertical or horizontal stretching to the\n * image.\n * <p>\n * It is recommended that you use one of the other <code>FIT_TO</code>\n * modes or {@link Mode#AUTOMATIC} if you want the image to look\n * correct, but if dimension-fitting is the #1 priority regardless of\n * how it makes the image look, that is what this mode is for.\n */\n FIT_EXACT,\n /**\n * Used to indicate that the scaling implementation should calculate\n * dimensions for the resultant image that best-fit within the given\n * width, regardless of the orientation of the image.\n */\n FIT_TO_WIDTH,\n /**\n * Used to indicate that the scaling implementation should calculate\n * dimensions for the resultant image that best-fit within the given\n * height, regardless of the orientation of the image.\n */\n FIT_TO_HEIGHT\n }\n\n /**\n * Used to define the different types of rotations that can be applied to an\n * image during a resize operation.\n *\n * @author Riyad Kalla ([email protected])\n * @since 3.2\n */\n public enum Rotation {\n /**\n * 90-degree, clockwise rotation (to the right). This is equivalent to a\n * quarter-turn of the image to the right; moving the picture on to its\n * right side.\n */\n CW_90,\n /**\n * 180-degree, clockwise rotation (to the right). This is equivalent to\n * 1 half-turn of the image to the right; rotating the picture around\n * until it is upside down from the original position.\n */\n CW_180,\n /**\n * 270-degree, clockwise rotation (to the right). This is equivalent to\n * a quarter-turn of the image to the left; moving the picture on to its\n * left side.\n */\n CW_270,\n /**\n * Flip the image horizontally by reflecting it around the y axis.\n * <p>\n * This is not a standard rotation around a center point, but instead\n * creates the mirrored reflection of the image horizontally.\n * <p>\n * More specifically, the vertical orientation of the image stays the\n * same (the top stays on top, and the bottom on bottom), but the right\n * and left sides flip. This is different than a standard rotation where\n * the top and bottom would also have been flipped.\n */\n FLIP_HORZ,\n /**\n * Flip the image vertically by reflecting it around the x axis.\n * <p>\n * This is not a standard rotation around a center point, but instead\n * creates the mirrored reflection of the image vertically.\n * <p>\n * More specifically, the horizontal orientation of the image stays the\n * same (the left stays on the left and the right stays on the right),\n * but the top and bottom sides flip. This is different than a standard\n * rotation where the left and right would also have been flipped.\n */\n FLIP_VERT\n }\n\n /**\n * Threshold (in pixels) at which point the scaling operation using the\n * {@link Method#AUTOMATIC} method will decide if a {@link Method#BALANCED}\n * method will be used (if smaller than or equal to threshold) or a\n * {@link Method#SPEED} method will be used (if larger than threshold).\n * <p>\n * The bigger the image is being scaled to, the less noticeable degradations\n * in the image becomes and the faster algorithms can be selected.\n * <p>\n * The value of this threshold (1600) was chosen after visual, by-hand, A/B\n * testing between different types of images scaled with this library; both\n * photographs and screenshots. It was determined that images below this\n * size need to use a {@link Method#BALANCED} scale method to look decent in\n * most all cases while using the faster {@link Method#SPEED} method for\n * images bigger than this threshold showed no noticeable degradation over a\n * <code>BALANCED</code> scale.\n */\n public static final int THRESHOLD_BALANCED_SPEED = 1600;\n\n /**\n * Threshold (in pixels) at which point the scaling operation using the\n * {@link Method#AUTOMATIC} method will decide if a {@link Method#QUALITY}\n * method will be used (if smaller than or equal to threshold) or a\n * {@link Method#BALANCED} method will be used (if larger than threshold).\n * <p>\n * The bigger the image is being scaled to, the less noticeable degradations\n * in the image becomes and the faster algorithms can be selected.\n * <p>\n * The value of this threshold (800) was chosen after visual, by-hand, A/B\n * testing between different types of images scaled with this library; both\n * photographs and screenshots. It was determined that images below this\n * size need to use a {@link Method#QUALITY} scale method to look decent in\n * most all cases while using the faster {@link Method#BALANCED} method for\n * images bigger than this threshold showed no noticeable degradation over a\n * <code>QUALITY</code> scale.\n */\n public static final int THRESHOLD_QUALITY_BALANCED = 800;\n\n /**\n * Used to apply, in the order given, 1 or more {@link BufferedImageOp}s to\n * a given {@link BufferedImage} and return the result.\n * <p>\n * <strong>Feature</strong>: This implementation works around <a\n * href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606\">a\n * decade-old JDK bug</a> that can cause a {@link RasterFormatException}\n * when applying a perfectly valid {@link BufferedImageOp}s to images.\n * <p>\n * <strong>Feature</strong>: This implementation also works around\n * {@link BufferedImageOp}s failing to apply and throwing\n * {@link ImagingOpException}s when run against a <code>src</code> image\n * type that is poorly supported. Unfortunately using {@link ImageIO} and\n * standard Java methods to load images provides no consistency in getting\n * images in well-supported formats. This method automatically accounts and\n * corrects for all those problems (if necessary).\n * <p>\n * It is recommended you always use this method to apply any\n * {@link BufferedImageOp}s instead of relying on directly using the\n * {@link BufferedImageOp#filter(BufferedImage, BufferedImage)} method.\n * <p>\n * <strong>Performance</strong>: Not all {@link BufferedImageOp}s are\n * hardware accelerated operations, but many of the most popular (like\n * {@link ConvolveOp}) are. For more information on if your image op is\n * hardware accelerated or not, check the source code of the underlying JDK\n * class that actually executes the Op code, <a href=\n * \"http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html\"\n * >sun.awt.image.ImagingLib</a>.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will have the ops applied to it.\n * @param ops <code>1</code> or more ops to apply to the image.\n * @return a new {@link BufferedImage} that represents the <code>src</code>\n * with all the given operations applied to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>ops</code> is <code>null</code> or empty.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage apply(BufferedImage src, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n long t = -1;\n if (DEBUG)\n t = System.currentTimeMillis();\n\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n if (ops == null || ops.length == 0)\n throw new IllegalArgumentException(\"ops cannot be null or empty\");\n\n int type = src.getType();\n\n\t\t/*\n * Ensure the src image is in the best supported image type before we\n\t\t * continue, otherwise it is possible our calls below to getBounds2D and\n\t\t * certainly filter(...) may fail if not.\n\t\t *\n\t\t * Java2D makes an attempt at applying most BufferedImageOps using\n\t\t * hardware acceleration via the ImagingLib internal library.\n\t\t *\n\t\t * Unfortunately may of the BufferedImageOp are written to simply fail\n\t\t * with an ImagingOpException if the operation cannot be applied with no\n\t\t * additional information about what went wrong or attempts at\n\t\t * re-applying it in different ways.\n\t\t *\n\t\t * This is assuming the failing BufferedImageOp even returns a null\n\t\t * image after failing to apply; some simply return a corrupted/black\n\t\t * image that result in no exception and it is up to the user to\n\t\t * discover this.\n\t\t *\n\t\t * In internal testing, EVERY failure I've ever seen was the result of\n\t\t * the source image being in a poorly-supported BufferedImage Type like\n\t\t * BGR or ABGR (even though it was loaded with ImageIO).\n\t\t *\n\t\t * To avoid this nasty/stupid surprise with BufferedImageOps, we always\n\t\t * ensure that the src image starts in an optimally supported format\n\t\t * before we try and apply the filter.\n\t\t */\n if (!(type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB))\n src = copyToOptimalImage(src);\n\n if (DEBUG)\n log(0, \"Applying %d BufferedImageOps...\", ops.length);\n\n boolean hasReassignedSrc = false;\n\n for (BufferedImageOp op1 : ops) {\n long subT = System.currentTimeMillis();\n\n // Skip null ops instead of throwing an exception.\n if (op1 == null)\n continue;\n\n if (DEBUG)\n log(1, \"Applying BufferedImageOp [class=%s, toString=%s]...\",\n op1.getClass(), op1.toString());\n\n\t\t\t/*\n * Must use op.getBounds instead of src.getWidth and src.getHeight\n\t\t\t * because we are trying to create an image big enough to hold the\n\t\t\t * result of this operation (which may be to scale the image\n\t\t\t * smaller), in that case the bounds reported by this op and the\n\t\t\t * bounds reported by the source image will be different.\n\t\t\t */\n Rectangle2D resultBounds = op1.getBounds2D(src);\n\n // Watch out for flaky/misbehaving ops that fail to work right.\n if (resultBounds == null)\n throw new ImagingOpException(\n \"BufferedImageOp [\"\n + op1.toString()\n + \"] getBounds2D(src) returned null bounds for the target image; this should not happen and indicates a problem with application of this type of op.\"\n );\n\n\t\t\t/*\n * We must manually create the target image; we cannot rely on the\n\t\t\t * null-destination filter() method to create a valid destination\n\t\t\t * for us thanks to this JDK bug that has been filed for almost a\n\t\t\t * decade:\n\t\t\t * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606\n\t\t\t */\n BufferedImage dest = createOptimalImage(src,\n (int) Math.round(resultBounds.getWidth()),\n (int) Math.round(resultBounds.getHeight()));\n\n // Perform the operation, update our result to return.\n BufferedImage result = op1.filter(src, dest);\n\n\t\t\t/*\n * Flush the 'src' image ONLY IF it is one of our interim temporary\n\t\t\t * images being used when applying 2 or more operations back to\n\t\t\t * back. We never want to flush the original image passed in.\n\t\t\t */\n if (hasReassignedSrc)\n src.flush();\n\n\t\t\t/*\n * Incase there are more operations to perform, update what we\n\t\t\t * consider the 'src' reference to our last result so on the next\n\t\t\t * iteration the next op is applied to this result and not back\n\t\t\t * against the original src passed in.\n\t\t\t */\n src = result;\n\n\t\t\t/*\n * Keep track of when we re-assign 'src' to an interim temporary\n\t\t\t * image, so we know when we can explicitly flush it and clean up\n\t\t\t * references on future iterations.\n\t\t\t */\n hasReassignedSrc = true;\n\n if (DEBUG)\n log(1,\n \"Applied BufferedImageOp in %d ms, result [width=%d, height=%d]\",\n System.currentTimeMillis() - subT, result.getWidth(),\n result.getHeight());\n }\n\n if (DEBUG)\n log(0, \"All %d BufferedImageOps applied in %d ms\", ops.length,\n System.currentTimeMillis() - t);\n\n return src;\n }\n\n /**\n * Used to crop the given <code>src</code> image from the top-left corner\n * and applying any optional {@link BufferedImageOp}s to the result before\n * returning it.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image to crop.\n * @param width The width of the bounding cropping box.\n * @param height The height of the bounding cropping box.\n * @param ops <code>0</code> or more ops to apply to the image. If\n * <code>null</code> or empty then <code>src</code> is return\n * unmodified.\n * @return a new {@link BufferedImage} representing the cropped region of\n * the <code>src</code> image with any optional operations applied\n * to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if any coordinates of the bounding crop box is invalid within\n * the bounds of the <code>src</code> image (e.g. negative or\n * too big).\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage crop(BufferedImage src, int width, int height,\n BufferedImageOp... ops) throws IllegalArgumentException,\n ImagingOpException {\n return crop(src, 0, 0, width, height, ops);\n }\n\n /**\n * Used to crop the given <code>src</code> image and apply any optional\n * {@link BufferedImageOp}s to it before returning the result.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image to crop.\n * @param x The x-coordinate of the top-left corner of the bounding box\n * used for cropping.\n * @param y The y-coordinate of the top-left corner of the bounding box\n * used for cropping.\n * @param width The width of the bounding cropping box.\n * @param height The height of the bounding cropping box.\n * @param ops <code>0</code> or more ops to apply to the image. If\n * <code>null</code> or empty then <code>src</code> is return\n * unmodified.\n * @return a new {@link BufferedImage} representing the cropped region of\n * the <code>src</code> image with any optional operations applied\n * to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if any coordinates of the bounding crop box is invalid within\n * the bounds of the <code>src</code> image (e.g. negative or\n * too big).\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage crop(BufferedImage src, int x, int y,\n int width, int height, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n long t = -1;\n if (DEBUG)\n t = System.currentTimeMillis();\n\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n if (x < 0 || y < 0 || width < 0 || height < 0)\n throw new IllegalArgumentException(\"Invalid crop bounds: x [\" + x\n + \"], y [\" + y + \"], width [\" + width + \"] and height [\"\n + height + \"] must all be >= 0\");\n\n int srcWidth = src.getWidth();\n int srcHeight = src.getHeight();\n\n if ((x + width) > srcWidth)\n throw new IllegalArgumentException(\n \"Invalid crop bounds: x + width [\" + (x + width)\n + \"] must be <= src.getWidth() [\" + srcWidth + \"]\"\n );\n if ((y + height) > srcHeight)\n throw new IllegalArgumentException(\n \"Invalid crop bounds: y + height [\" + (y + height)\n + \"] must be <= src.getHeight() [\" + srcHeight\n + \"]\"\n );\n\n if (DEBUG)\n log(0,\n \"Cropping Image [width=%d, height=%d] to [x=%d, y=%d, width=%d, height=%d]...\",\n srcWidth, srcHeight, x, y, width, height);\n\n // Create a target image of an optimal type to render into.\n BufferedImage result = createOptimalImage(src, width, height);\n Graphics g = result.getGraphics();\n\n\t\t/*\n * Render the region specified by our crop bounds from the src image\n\t\t * directly into our result image (which is the exact size of the crop\n\t\t * region).\n\t\t */\n g.drawImage(src, 0, 0, width, height, x, y, (x + width), (y + height),\n null);\n g.dispose();\n\n if (DEBUG)\n log(0, \"Cropped Image in %d ms\", System.currentTimeMillis() - t);\n\n // Apply any optional operations (if specified).\n if (ops != null && ops.length > 0)\n result = apply(result, ops);\n\n return result;\n }\n\n /**\n * Used to apply padding around the edges of an image using\n * {@link Color#BLACK} to fill the extra padded space and then return the\n * result.\n * <p>\n * The amount of <code>padding</code> specified is applied to all sides;\n * more specifically, a <code>padding</code> of <code>2</code> would add 2\n * extra pixels of space (filled by the given <code>color</code>) on the\n * top, bottom, left and right sides of the resulting image causing the\n * result to be 4 pixels wider and 4 pixels taller than the <code>src</code>\n * image.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image the padding will be added to.\n * @param padding The number of pixels of padding to add to each side in the\n * resulting image. If this value is <code>0</code> then\n * <code>src</code> is returned unmodified.\n * @param ops <code>0</code> or more ops to apply to the image. If\n * <code>null</code> or empty then <code>src</code> is return\n * unmodified.\n * @return a new {@link BufferedImage} representing <code>src</code> with\n * the given padding applied to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>padding</code> is &lt; <code>1</code>.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage pad(BufferedImage src, int padding,\n BufferedImageOp... ops) throws IllegalArgumentException,\n ImagingOpException {\n return pad(src, padding, Color.BLACK);\n }\n\n /**\n * Used to apply padding around the edges of an image using the given color\n * to fill the extra padded space and then return the result. {@link Color}s\n * using an alpha channel (i.e. transparency) are supported.\n * <p>\n * The amount of <code>padding</code> specified is applied to all sides;\n * more specifically, a <code>padding</code> of <code>2</code> would add 2\n * extra pixels of space (filled by the given <code>color</code>) on the\n * top, bottom, left and right sides of the resulting image causing the\n * result to be 4 pixels wider and 4 pixels taller than the <code>src</code>\n * image.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image the padding will be added to.\n * @param padding The number of pixels of padding to add to each side in the\n * resulting image. If this value is <code>0</code> then\n * <code>src</code> is returned unmodified.\n * @param color The color to fill the padded space with. {@link Color}s using\n * an alpha channel (i.e. transparency) are supported.\n * @param ops <code>0</code> or more ops to apply to the image. If\n * <code>null</code> or empty then <code>src</code> is return\n * unmodified.\n * @return a new {@link BufferedImage} representing <code>src</code> with\n * the given padding applied to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>padding</code> is &lt; <code>1</code>.\n * @throws IllegalArgumentException if <code>color</code> is <code>null</code>.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage pad(BufferedImage src, int padding,\n Color color, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n long t = -1;\n if (DEBUG)\n t = System.currentTimeMillis();\n\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n if (padding < 1)\n throw new IllegalArgumentException(\"padding [\" + padding\n + \"] must be > 0\");\n if (color == null)\n throw new IllegalArgumentException(\"color cannot be null\");\n\n int srcWidth = src.getWidth();\n int srcHeight = src.getHeight();\n\n\t\t/*\n * Double the padding to account for all sides of the image. More\n\t\t * specifically, if padding is \"1\" we add 2 pixels to width and 2 to\n\t\t * height, so we have 1 new pixel of padding all the way around our\n\t\t * image.\n\t\t */\n int sizeDiff = (padding * 2);\n int newWidth = srcWidth + sizeDiff;\n int newHeight = srcHeight + sizeDiff;\n\n if (DEBUG)\n log(0,\n \"Padding Image from [originalWidth=%d, originalHeight=%d, padding=%d] to [newWidth=%d, newHeight=%d]...\",\n srcWidth, srcHeight, padding, newWidth, newHeight);\n\n boolean colorHasAlpha = (color.getAlpha() != 255);\n boolean imageHasAlpha = (src.getTransparency() != BufferedImage.OPAQUE);\n\n BufferedImage result;\n\n\t\t/*\n\t\t * We need to make sure our resulting image that we render into contains\n\t\t * alpha if either our original image OR the padding color we are using\n\t\t * contain it.\n\t\t */\n if (colorHasAlpha || imageHasAlpha) {\n if (DEBUG)\n log(1,\n \"Transparency FOUND in source image or color, using ARGB image type...\");\n\n result = new BufferedImage(newWidth, newHeight,\n BufferedImage.TYPE_INT_ARGB);\n } else {\n if (DEBUG)\n log(1,\n \"Transparency NOT FOUND in source image or color, using RGB image type...\");\n\n result = new BufferedImage(newWidth, newHeight,\n BufferedImage.TYPE_INT_RGB);\n }\n\n Graphics g = result.getGraphics();\n\n // \"Clear\" the background of the new image with our padding color first.\n g.setColor(color);\n g.fillRect(0, 0, newWidth, newHeight);\n\n // Draw the image into the center of the new padded image.\n g.drawImage(src, padding, padding, null);\n g.dispose();\n\n if (DEBUG)\n log(0, \"Padding Applied in %d ms\", System.currentTimeMillis() - t);\n\n // Apply any optional operations (if specified).\n if (ops != null && ops.length > 0)\n result = apply(result, ops);\n\n return result;\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to a width and\n * height no bigger than <code>targetSize</code> and apply the given\n * {@link BufferedImageOp}s (if any) to the result before returning it.\n * <p>\n * A scaling method of {@link Method#AUTOMATIC} and mode of\n * {@link Mode#AUTOMATIC} are used.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param targetSize The target width and height (square) that you wish the image\n * to fit within.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetSize</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage resize(BufferedImage src, int targetSize,\n BufferedImageOp... ops) throws IllegalArgumentException,\n ImagingOpException {\n return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetSize,\n targetSize, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to a width and\n * height no bigger than <code>targetSize</code> using the given scaling\n * method and apply the given {@link BufferedImageOp}s (if any) to the\n * result before returning it.\n * <p>\n * A mode of {@link Mode#AUTOMATIC} is used.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param scalingMethod The method used for scaling the image; preferring speed to\n * quality or a balance of both.\n * @param targetSize The target width and height (square) that you wish the image\n * to fit within.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>scalingMethod</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetSize</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Method\n */\n public static BufferedImage resize(BufferedImage src, Method scalingMethod,\n int targetSize, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n return resize(src, scalingMethod, Mode.AUTOMATIC, targetSize,\n targetSize, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to a width and\n * height no bigger than <code>targetSize</code> (or fitting the image to\n * the given WIDTH or HEIGHT explicitly, depending on the {@link Mode}\n * specified) and apply the given {@link BufferedImageOp}s (if any) to the\n * result before returning it.\n * <p>\n * A scaling method of {@link Method#AUTOMATIC} is used.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param resizeMode Used to indicate how imgscalr should calculate the final\n * target size for the image, either fitting the image to the\n * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image\n * to the given height ({@link Mode#FIT_TO_HEIGHT}). If\n * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate\n * proportional dimensions for the scaled image based on its\n * orientation (landscape, square or portrait). Unless you have\n * very specific size requirements, most of the time you just\n * want to use {@link Mode#AUTOMATIC} to \"do the right thing\".\n * @param targetSize The target width and height (square) that you wish the image\n * to fit within.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>resizeMode</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetSize</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Mode\n */\n public static BufferedImage resize(BufferedImage src, Mode resizeMode,\n int targetSize, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n return resize(src, Method.AUTOMATIC, resizeMode, targetSize,\n targetSize, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to a width and\n * height no bigger than <code>targetSize</code> (or fitting the image to\n * the given WIDTH or HEIGHT explicitly, depending on the {@link Mode}\n * specified) using the given scaling method and apply the given\n * {@link BufferedImageOp}s (if any) to the result before returning it.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param scalingMethod The method used for scaling the image; preferring speed to\n * quality or a balance of both.\n * @param resizeMode Used to indicate how imgscalr should calculate the final\n * target size for the image, either fitting the image to the\n * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image\n * to the given height ({@link Mode#FIT_TO_HEIGHT}). If\n * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate\n * proportional dimensions for the scaled image based on its\n * orientation (landscape, square or portrait). Unless you have\n * very specific size requirements, most of the time you just\n * want to use {@link Mode#AUTOMATIC} to \"do the right thing\".\n * @param targetSize The target width and height (square) that you wish the image\n * to fit within.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>scalingMethod</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>resizeMode</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetSize</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Method\n * @see Mode\n */\n public static BufferedImage resize(BufferedImage src, Method scalingMethod,\n Mode resizeMode, int targetSize, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n return resize(src, scalingMethod, resizeMode, targetSize, targetSize,\n ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to the target\n * width and height and apply the given {@link BufferedImageOp}s (if any) to\n * the result before returning it.\n * <p>\n * A scaling method of {@link Method#AUTOMATIC} and mode of\n * {@link Mode#AUTOMATIC} are used.\n * <p>\n * <strong>TIP</strong>: See the class description to understand how this\n * class handles recalculation of the <code>targetWidth</code> or\n * <code>targetHeight</code> depending on the image's orientation in order\n * to maintain the original proportion.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param targetWidth The target width that you wish the image to have.\n * @param targetHeight The target height that you wish the image to have.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetWidth</code> is &lt; 0 or if\n * <code>targetHeight</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage resize(BufferedImage src, int targetWidth,\n int targetHeight, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetWidth,\n targetHeight, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to the target\n * width and height using the given scaling method and apply the given\n * {@link BufferedImageOp}s (if any) to the result before returning it.\n * <p>\n * A mode of {@link Mode#AUTOMATIC} is used.\n * <p>\n * <strong>TIP</strong>: See the class description to understand how this\n * class handles recalculation of the <code>targetWidth</code> or\n * <code>targetHeight</code> depending on the image's orientation in order\n * to maintain the original proportion.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param scalingMethod The method used for scaling the image; preferring speed to\n * quality or a balance of both.\n * @param targetWidth The target width that you wish the image to have.\n * @param targetHeight The target height that you wish the image to have.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>scalingMethod</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetWidth</code> is &lt; 0 or if\n * <code>targetHeight</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Method\n */\n public static BufferedImage resize(BufferedImage src, Method scalingMethod,\n int targetWidth, int targetHeight, BufferedImageOp... ops) {\n return resize(src, scalingMethod, Mode.AUTOMATIC, targetWidth,\n targetHeight, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to the target\n * width and height (or fitting the image to the given WIDTH or HEIGHT\n * explicitly, depending on the {@link Mode} specified) and apply the given\n * {@link BufferedImageOp}s (if any) to the result before returning it.\n * <p>\n * A scaling method of {@link Method#AUTOMATIC} is used.\n * <p>\n * <strong>TIP</strong>: See the class description to understand how this\n * class handles recalculation of the <code>targetWidth</code> or\n * <code>targetHeight</code> depending on the image's orientation in order\n * to maintain the original proportion.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param resizeMode Used to indicate how imgscalr should calculate the final\n * target size for the image, either fitting the image to the\n * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image\n * to the given height ({@link Mode#FIT_TO_HEIGHT}). If\n * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate\n * proportional dimensions for the scaled image based on its\n * orientation (landscape, square or portrait). Unless you have\n * very specific size requirements, most of the time you just\n * want to use {@link Mode#AUTOMATIC} to \"do the right thing\".\n * @param targetWidth The target width that you wish the image to have.\n * @param targetHeight The target height that you wish the image to have.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>resizeMode</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetWidth</code> is &lt; 0 or if\n * <code>targetHeight</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Mode\n */\n public static BufferedImage resize(BufferedImage src, Mode resizeMode,\n int targetWidth, int targetHeight, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n return resize(src, Method.AUTOMATIC, resizeMode, targetWidth,\n targetHeight, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to the target\n * width and height (or fitting the image to the given WIDTH or HEIGHT\n * explicitly, depending on the {@link Mode} specified) using the given\n * scaling method and apply the given {@link BufferedImageOp}s (if any) to\n * the result before returning it.\n * <p>\n * <strong>TIP</strong>: See the class description to understand how this\n * class handles recalculation of the <code>targetWidth</code> or\n * <code>targetHeight</code> depending on the image's orientation in order\n * to maintain the original proportion.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param scalingMethod The method used for scaling the image; preferring speed to\n * quality or a balance of both.\n * @param resizeMode Used to indicate how imgscalr should calculate the final\n * target size for the image, either fitting the image to the\n * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image\n * to the given height ({@link Mode#FIT_TO_HEIGHT}). If\n * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate\n * proportional dimensions for the scaled image based on its\n * orientation (landscape, square or portrait). Unless you have\n * very specific size requirements, most of the time you just\n * want to use {@link Mode#AUTOMATIC} to \"do the right thing\".\n * @param targetWidth The target width that you wish the image to have.\n * @param targetHeight The target height that you wish the image to have.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>scalingMethod</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>resizeMode</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetWidth</code> is &lt; 0 or if\n * <code>targetHeight</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Method\n * @see Mode\n */\n public static BufferedImage resize(BufferedImage src, Method scalingMethod,\n Mode resizeMode, int targetWidth, int targetHeight,\n BufferedImageOp... ops) throws IllegalArgumentException,\n ImagingOpException {\n long t = -1;\n if (DEBUG)\n t = System.currentTimeMillis();\n\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n if (targetWidth < 0)\n throw new IllegalArgumentException(\"targetWidth must be >= 0\");\n if (targetHeight < 0)\n throw new IllegalArgumentException(\"targetHeight must be >= 0\");\n if (scalingMethod == null)\n throw new IllegalArgumentException(\n \"scalingMethod cannot be null. A good default value is Method.AUTOMATIC.\");\n if (resizeMode == null)\n throw new IllegalArgumentException(\n \"resizeMode cannot be null. A good default value is Mode.AUTOMATIC.\");\n\n BufferedImage result = null;\n\n int currentWidth = src.getWidth();\n int currentHeight = src.getHeight();\n\n // <= 1 is a square or landscape-oriented image, > 1 is a portrait.\n float ratio = ((float) currentHeight / (float) currentWidth);\n\n if (DEBUG)\n log(0,\n \"Resizing Image [size=%dx%d, resizeMode=%s, orientation=%s, ratio(H/W)=%f] to [targetSize=%dx%d]\",\n currentWidth, currentHeight, resizeMode,\n (ratio <= 1 ? \"Landscape/Square\" : \"Portrait\"), ratio,\n targetWidth, targetHeight);\n\n\t\t/*\n\t\t * First determine if ANY size calculation needs to be done, in the case\n\t\t * of FIT_EXACT, ignore image proportions and orientation and just use\n\t\t * what the user sent in, otherwise the proportion of the picture must\n\t\t * be honored.\n\t\t *\n\t\t * The way that is done is to figure out if the image is in a\n\t\t * LANDSCAPE/SQUARE or PORTRAIT orientation and depending on its\n\t\t * orientation, use the primary dimension (width for LANDSCAPE/SQUARE\n\t\t * and height for PORTRAIT) to recalculate the alternative (height and\n\t\t * width respectively) value that adheres to the existing ratio.\n\t\t *\n\t\t * This helps make life easier for the caller as they don't need to\n\t\t * pre-compute proportional dimensions before calling the API, they can\n\t\t * just specify the dimensions they would like the image to roughly fit\n\t\t * within and it will do the right thing without mangling the result.\n\t\t */\n if (resizeMode != Mode.FIT_EXACT) {\n if ((ratio <= 1 && resizeMode == Mode.AUTOMATIC)\n || (resizeMode == Mode.FIT_TO_WIDTH)) {\n // First make sure we need to do any work in the first place\n if (targetWidth == src.getWidth())\n return src;\n\n // Save for detailed logging (this is cheap).\n int originalTargetHeight = targetHeight;\n\n\t\t\t\t/*\n\t\t\t\t * Landscape or Square Orientation: Ignore the given height and\n\t\t\t\t * re-calculate a proportionally correct value based on the\n\t\t\t\t * targetWidth.\n\t\t\t\t */\n targetHeight = Math.round((float) targetWidth * ratio);\n\n if (DEBUG && originalTargetHeight != targetHeight)\n log(1,\n \"Auto-Corrected targetHeight [from=%d to=%d] to honor image proportions.\",\n originalTargetHeight, targetHeight);\n } else {\n // First make sure we need to do any work in the first place\n if (targetHeight == src.getHeight())\n return src;\n\n // Save for detailed logging (this is cheap).\n int originalTargetWidth = targetWidth;\n\n\t\t\t\t/*\n\t\t\t\t * Portrait Orientation: Ignore the given width and re-calculate\n\t\t\t\t * a proportionally correct value based on the targetHeight.\n\t\t\t\t */\n targetWidth = Math.round((float) targetHeight / ratio);\n\n if (DEBUG && originalTargetWidth != targetWidth)\n log(1,\n \"Auto-Corrected targetWidth [from=%d to=%d] to honor image proportions.\",\n originalTargetWidth, targetWidth);\n }\n } else {\n if (DEBUG)\n log(1,\n \"Resize Mode FIT_EXACT used, no width/height checking or re-calculation will be done.\");\n }\n\n // If AUTOMATIC was specified, determine the real scaling method.\n if (scalingMethod == Scalr.Method.AUTOMATIC)\n scalingMethod = determineScalingMethod(targetWidth, targetHeight,\n ratio);\n\n if (DEBUG)\n log(1, \"Using Scaling Method: %s\", scalingMethod);\n\n // Now we scale the image\n if (scalingMethod == Scalr.Method.SPEED) {\n result = scaleImage(src, targetWidth, targetHeight,\n RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);\n } else if (scalingMethod == Scalr.Method.BALANCED) {\n result = scaleImage(src, targetWidth, targetHeight,\n RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n } else if (scalingMethod == Scalr.Method.QUALITY\n || scalingMethod == Scalr.Method.ULTRA_QUALITY) {\n\t\t\t/*\n\t\t\t * If we are scaling up (in either width or height - since we know\n\t\t\t * the image will stay proportional we just check if either are\n\t\t\t * being scaled up), directly using a single BICUBIC will give us\n\t\t\t * better results then using Chris Campbell's incremental scaling\n\t\t\t * operation (and take a lot less time).\n\t\t\t *\n\t\t\t * If we are scaling down, we must use the incremental scaling\n\t\t\t * algorithm for the best result.\n\t\t\t */\n if (targetWidth > currentWidth || targetHeight > currentHeight) {\n if (DEBUG)\n log(1,\n \"QUALITY scale-up, a single BICUBIC scale operation will be used...\");\n\n\t\t\t\t/*\n\t\t\t\t * BILINEAR and BICUBIC look similar the smaller the scale jump\n\t\t\t\t * upwards is, if the scale is larger BICUBIC looks sharper and\n\t\t\t\t * less fuzzy. But most importantly we have to use BICUBIC to\n\t\t\t\t * match the contract of the QUALITY rendering scalingMethod.\n\t\t\t\t * This note is just here for anyone reading the code and\n\t\t\t\t * wondering how they can speed their own calls up.\n\t\t\t\t */\n result = scaleImage(src, targetWidth, targetHeight,\n RenderingHints.VALUE_INTERPOLATION_BICUBIC);\n } else {\n if (DEBUG)\n log(1,\n \"QUALITY scale-down, incremental scaling will be used...\");\n\n\t\t\t\t/*\n\t\t\t\t * Originally we wanted to use BILINEAR interpolation here\n\t\t\t\t * because it takes 1/3rd the time that the BICUBIC\n\t\t\t\t * interpolation does, however, when scaling large images down\n\t\t\t\t * to most sizes bigger than a thumbnail we witnessed noticeable\n\t\t\t\t * \"softening\" in the resultant image with BILINEAR that would\n\t\t\t\t * be unexpectedly annoying to a user expecting a \"QUALITY\"\n\t\t\t\t * scale of their original image. Instead BICUBIC was chosen to\n\t\t\t\t * honor the contract of a QUALITY scale of the original image.\n\t\t\t\t */\n result = scaleImageIncrementally(src, targetWidth,\n targetHeight, scalingMethod,\n RenderingHints.VALUE_INTERPOLATION_BICUBIC);\n }\n }\n\n if (DEBUG)\n log(0, \"Resized Image in %d ms\", System.currentTimeMillis() - t);\n\n // Apply any optional operations (if specified).\n if (ops != null && ops.length > 0)\n result = apply(result, ops);\n\n return result;\n }\n\n /**\n * Used to apply a {@link Rotation} and then <code>0</code> or more\n * {@link BufferedImageOp}s to a given image and return the result.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will have the rotation applied to it.\n * @param rotation The rotation that will be applied to the image.\n * @param ops Zero or more optional image operations (e.g. sharpen, blur,\n * etc.) that can be applied to the final result before returning\n * the image.\n * @return a new {@link BufferedImage} representing <code>src</code> rotated\n * by the given amount and any optional ops applied to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>rotation</code> is <code>null</code>.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Rotation\n */\n public static BufferedImage rotate(BufferedImage src, Rotation rotation,\n BufferedImageOp... ops) throws IllegalArgumentException,\n ImagingOpException {\n long t = -1;\n if (DEBUG)\n t = System.currentTimeMillis();\n\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n if (rotation == null)\n throw new IllegalArgumentException(\"rotation cannot be null\");\n\n if (DEBUG)\n log(0, \"Rotating Image [%s]...\", rotation);\n\n\t\t/*\n\t\t * Setup the default width/height values from our image.\n\t\t *\n\t\t * In the case of a 90 or 270 (-90) degree rotation, these two values\n\t\t * flip-flop and we will correct those cases down below in the switch\n\t\t * statement.\n\t\t */\n int newWidth = src.getWidth();\n int newHeight = src.getHeight();\n\n\t\t/*\n\t\t * We create a transform per operation request as (oddly enough) it ends\n\t\t * up being faster for the VM to create, use and destroy these instances\n\t\t * than it is to re-use a single AffineTransform per-thread via the\n\t\t * AffineTransform.setTo(...) methods which was my first choice (less\n\t\t * object creation); after benchmarking this explicit case and looking\n\t\t * at just how much code gets run inside of setTo() I opted for a new AT\n\t\t * for every rotation.\n\t\t *\n\t\t * Besides the performance win, trying to safely reuse AffineTransforms\n\t\t * via setTo(...) would have required ThreadLocal instances to avoid\n\t\t * race conditions where two or more resize threads are manipulating the\n\t\t * same transform before applying it.\n\t\t *\n\t\t * Misusing ThreadLocals are one of the #1 reasons for memory leaks in\n\t\t * server applications and since we have no nice way to hook into the\n\t\t * init/destroy Servlet cycle or any other initialization cycle for this\n\t\t * library to automatically call ThreadLocal.remove() to avoid the\n\t\t * memory leak, it would have made using this library *safely* on the\n\t\t * server side much harder.\n\t\t *\n\t\t * So we opt for creating individual transforms per rotation op and let\n\t\t * the VM clean them up in a GC. I only clarify all this reasoning here\n\t\t * for anyone else reading this code and being tempted to reuse the AT\n\t\t * instances of performance gains; there aren't any AND you get a lot of\n\t\t * pain along with it.\n\t\t */\n AffineTransform tx = new AffineTransform();\n\n switch (rotation) {\n case CW_90:\n\t\t\t/*\n\t\t\t * A 90 or -90 degree rotation will cause the height and width to\n\t\t\t * flip-flop from the original image to the rotated one.\n\t\t\t */\n newWidth = src.getHeight();\n newHeight = src.getWidth();\n\n // Reminder: newWidth == result.getHeight() at this point\n tx.translate(newWidth, 0);\n tx.quadrantRotate(1);\n\n break;\n\n case CW_270:\n\t\t\t/*\n\t\t\t * A 90 or -90 degree rotation will cause the height and width to\n\t\t\t * flip-flop from the original image to the rotated one.\n\t\t\t */\n newWidth = src.getHeight();\n newHeight = src.getWidth();\n\n // Reminder: newHeight == result.getWidth() at this point\n tx.translate(0, newHeight);\n tx.quadrantRotate(3);\n break;\n\n case CW_180:\n tx.translate(newWidth, newHeight);\n tx.quadrantRotate(2);\n break;\n\n case FLIP_HORZ:\n tx.translate(newWidth, 0);\n tx.scale(-1.0, 1.0);\n break;\n\n case FLIP_VERT:\n tx.translate(0, newHeight);\n tx.scale(1.0, -1.0);\n break;\n }\n\n // Create our target image we will render the rotated result to.\n BufferedImage result = createOptimalImage(src, newWidth, newHeight);\n Graphics2D g2d = result.createGraphics();\n\n\t\t/*\n\t\t * Render the resultant image to our new rotatedImage buffer, applying\n\t\t * the AffineTransform that we calculated above during rendering so the\n\t\t * pixels from the old position are transposed to the new positions in\n\t\t * the resulting image correctly.\n\t\t */\n g2d.drawImage(src, tx, null);\n g2d.dispose();\n\n if (DEBUG)\n log(0, \"Rotation Applied in %d ms, result [width=%d, height=%d]\",\n System.currentTimeMillis() - t, result.getWidth(),\n result.getHeight());\n\n // Apply any optional operations (if specified).\n if (ops != null && ops.length > 0)\n result = apply(result, ops);\n\n return result;\n }\n\n /**\n * Used to write out a useful and well-formatted log message by any piece of\n * code inside of the imgscalr library.\n * <p>\n * If a message cannot be logged (logging is disabled) then this method\n * returns immediately.\n * <p>\n * <strong>NOTE</strong>: Because Java will auto-box primitive arguments\n * into Objects when building out the <code>params</code> array, care should\n * be taken not to call this method with primitive values unless\n * {@link Scalr#DEBUG} is <code>true</code>; otherwise the VM will be\n * spending time performing unnecessary auto-boxing calculations.\n *\n * @param depth The indentation level of the log message.\n * @param message The log message in <a href=\n * \"http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax\"\n * >format string syntax</a> that will be logged.\n * @param params The parameters that will be swapped into all the place holders\n * in the original messages before being logged.\n * @see Scalr#LOG_PREFIX\n * @see Scalr#LOG_PREFIX_PROPERTY_NAME\n */\n protected static void log(int depth, String message, Object... params) {\n if (Scalr.DEBUG) {\n System.out.print(Scalr.LOG_PREFIX);\n\n for (int i = 0; i < depth; i++)\n System.out.print(\"\\t\");\n\n System.out.printf(message, params);\n System.out.println();\n }\n }\n\n /**\n * Used to create a {@link BufferedImage} with the most optimal RGB TYPE (\n * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB}\n * ) capable of being rendered into from the given <code>src</code>. The\n * width and height of both images will be identical.\n * <p>\n * This does not perform a copy of the image data from <code>src</code> into\n * the result image; see {@link #copyToOptimalImage(BufferedImage)} for\n * that.\n * <p>\n * We force all rendering results into one of these two types, avoiding the\n * case where a source image is of an unsupported (or poorly supported)\n * format by Java2D causing the rendering result to end up looking terrible\n * (common with GIFs) or be totally corrupt (e.g. solid black image).\n * <p>\n * Originally reported by Magnus Kvalheim from Movellas when scaling certain\n * GIF and PNG images.\n *\n * @param src The source image that will be analyzed to determine the most\n * optimal image type it can be rendered into.\n * @return a new {@link BufferedImage} representing the most optimal target\n * image type that <code>src</code> can be rendered into.\n * @see <a\n * href=\"http://www.mail-archive.com/[email protected]/msg05621.html\">How\n * Java2D handles poorly supported image types</a>\n * @see <a\n * href=\"http://code.google.com/p/java-image-scaling/source/browse/trunk/src/main/java/com/mortennobel/imagescaling/MultiStepRescaleOp.java\">Thanks\n * to Morten Nobel for implementation hint</a>\n */\n protected static BufferedImage createOptimalImage(BufferedImage src) {\n return createOptimalImage(src, src.getWidth(), src.getHeight());\n }\n\n /**\n * Used to create a {@link BufferedImage} with the given dimensions and the\n * most optimal RGB TYPE ( {@link BufferedImage#TYPE_INT_RGB} or\n * {@link BufferedImage#TYPE_INT_ARGB} ) capable of being rendered into from\n * the given <code>src</code>.\n * <p>\n * This does not perform a copy of the image data from <code>src</code> into\n * the result image; see {@link #copyToOptimalImage(BufferedImage)} for\n * that.\n * <p>\n * We force all rendering results into one of these two types, avoiding the\n * case where a source image is of an unsupported (or poorly supported)\n * format by Java2D causing the rendering result to end up looking terrible\n * (common with GIFs) or be totally corrupt (e.g. solid black image).\n * <p>\n * Originally reported by Magnus Kvalheim from Movellas when scaling certain\n * GIF and PNG images.\n *\n * @param src The source image that will be analyzed to determine the most\n * optimal image type it can be rendered into.\n * @param width The width of the newly created resulting image.\n * @param height The height of the newly created resulting image.\n * @return a new {@link BufferedImage} representing the most optimal target\n * image type that <code>src</code> can be rendered into.\n * @throws IllegalArgumentException if <code>width</code> or <code>height</code> are &lt; 0.\n * @see <a\n * href=\"http://www.mail-archive.com/[email protected]/msg05621.html\">How\n * Java2D handles poorly supported image types</a>\n * @see <a\n * href=\"http://code.google.com/p/java-image-scaling/source/browse/trunk/src/main/java/com/mortennobel/imagescaling/MultiStepRescaleOp.java\">Thanks\n * to Morten Nobel for implementation hint</a>\n */\n protected static BufferedImage createOptimalImage(BufferedImage src,\n int width, int height) throws IllegalArgumentException {\n if (width < 0 || height < 0)\n throw new IllegalArgumentException(\"width [\" + width\n + \"] and height [\" + height + \"] must be >= 0\");\n\n return new BufferedImage(\n width,\n height,\n (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB\n : BufferedImage.TYPE_INT_ARGB)\n );\n }\n\n /**\n * Used to copy a {@link BufferedImage} from a non-optimal type into a new\n * {@link BufferedImage} instance of an optimal type (RGB or ARGB). If\n * <code>src</code> is already of an optimal type, then it is returned\n * unmodified.\n * <p>\n * This method is meant to be used by any calling code (imgscalr's or\n * otherwise) to convert any inbound image from a poorly supported image\n * type into the 2 most well-supported image types in Java2D (\n * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB}\n * ) in order to ensure all subsequent graphics operations are performed as\n * efficiently and correctly as possible.\n * <p>\n * When using Java2D to work with image types that are not well supported,\n * the results can be anything from exceptions bubbling up from the depths\n * of Java2D to images being completely corrupted and just returned as solid\n * black.\n *\n * @param src The image to copy (if necessary) into an optimally typed\n * {@link BufferedImage}.\n * @return a representation of the <code>src</code> image in an optimally\n * typed {@link BufferedImage}, otherwise <code>src</code> if it was\n * already of an optimal type.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n */\n protected static BufferedImage copyToOptimalImage(BufferedImage src)\n throws IllegalArgumentException {\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n\n // Calculate the type depending on the presence of alpha.\n int type = (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB\n : BufferedImage.TYPE_INT_ARGB);\n BufferedImage result = new BufferedImage(src.getWidth(),\n src.getHeight(), type);\n\n // Render the src image into our new optimal source.\n Graphics g = result.getGraphics();\n g.drawImage(src, 0, 0, null);\n g.dispose();\n\n return result;\n }\n\n /**\n * Used to determine the scaling {@link Method} that is best suited for\n * scaling the image to the targeted dimensions.\n * <p>\n * This method is intended to be used to select a specific scaling\n * {@link Method} when a {@link Method#AUTOMATIC} method is specified. This\n * method utilizes the {@link Scalr#THRESHOLD_QUALITY_BALANCED} and\n * {@link Scalr#THRESHOLD_BALANCED_SPEED} thresholds when selecting which\n * method should be used by comparing the primary dimension (width or\n * height) against the threshold and seeing where the image falls. The\n * primary dimension is determined by looking at the orientation of the\n * image: landscape or square images use their width and portrait-oriented\n * images use their height.\n *\n * @param targetWidth The target width for the scaled image.\n * @param targetHeight The target height for the scaled image.\n * @param ratio A height/width ratio used to determine the orientation of the\n * image so the primary dimension (width or height) can be\n * selected to test if it is greater than or less than a\n * particular threshold.\n * @return the fastest {@link Method} suited for scaling the image to the\n * specified dimensions while maintaining a good-looking result.\n */\n protected static Method determineScalingMethod(int targetWidth,\n int targetHeight, float ratio) {\n // Get the primary dimension based on the orientation of the image\n int length = (ratio <= 1 ? targetWidth : targetHeight);\n\n // Default to speed\n Method result = Method.SPEED;\n\n // Figure out which scalingMethod should be used\n if (length <= Scalr.THRESHOLD_QUALITY_BALANCED)\n result = Method.QUALITY;\n else if (length <= Scalr.THRESHOLD_BALANCED_SPEED)\n result = Method.BALANCED;\n\n if (DEBUG)\n log(2, \"AUTOMATIC scaling method selected: %s\", result.name());\n\n return result;\n }\n\n /**\n * Used to implement a straight-forward image-scaling operation using Java\n * 2D.\n * <p>\n * This method uses the Oracle-encouraged method of\n * <code>Graphics2D.drawImage(...)</code> to scale the given image with the\n * given interpolation hint.\n *\n * @param src The image that will be scaled.\n * @param targetWidth The target width for the scaled image.\n * @param targetHeight The target height for the scaled image.\n * @param interpolationHintValue The {@link RenderingHints} interpolation value used to\n * indicate the method that {@link Graphics2D} should use when\n * scaling the image.\n * @return the result of scaling the original <code>src</code> to the given\n * dimensions using the given interpolation method.\n */\n protected static BufferedImage scaleImage(BufferedImage src,\n int targetWidth, int targetHeight, Object interpolationHintValue) {\n // Setup the rendering resources to match the source image's\n BufferedImage result = createOptimalImage(src, targetWidth,\n targetHeight);\n Graphics2D resultGraphics = result.createGraphics();\n\n // Scale the image to the new buffer using the specified rendering hint.\n resultGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,\n interpolationHintValue);\n resultGraphics.drawImage(src, 0, 0, targetWidth, targetHeight, null);\n\n // Just to be clean, explicitly dispose our temporary graphics object\n resultGraphics.dispose();\n\n // Return the scaled image to the caller.\n return result;\n }\n\n /**\n * Used to implement Chris Campbell's incremental-scaling algorithm: <a\n * href=\"http://today.java.net/pub/a/today/2007/04/03/perils\n * -of-image-getscaledinstance\n * .html\">http://today.java.net/pub/a/today/2007/04/03/perils\n * -of-image-getscaledinstance.html</a>.\n * <p>\n * Modifications to the original algorithm are variable names and comments\n * added for clarity and the hard-coding of using BICUBIC interpolation as\n * well as the explicit \"flush()\" operation on the interim BufferedImage\n * instances to avoid image leaking.\n *\n * @param src The image that will be scaled.\n * @param targetWidth The target width for the scaled image.\n * @param targetHeight The target height for the scaled image.\n * @param scalingMethod The scaling method specified by the user (or calculated by\n * imgscalr) to use for this incremental scaling operation.\n * @param interpolationHintValue The {@link RenderingHints} interpolation value used to\n * indicate the method that {@link Graphics2D} should use when\n * scaling the image.\n * @return an image scaled to the given dimensions using the given rendering\n * hint.\n */\n protected static BufferedImage scaleImageIncrementally(BufferedImage src,\n int targetWidth, int targetHeight, Method scalingMethod,\n Object interpolationHintValue) {\n boolean hasReassignedSrc = false;\n int incrementCount = 0;\n int currentWidth = src.getWidth();\n int currentHeight = src.getHeight();\n\n\t\t/*\n\t\t * The original QUALITY mode, representing Chris Campbell's algorithm,\n\t\t * is to step down by 1/2s every time when scaling the image\n\t\t * incrementally. Users pointed out that using this method to scale\n\t\t * images with noticeable straight lines left them really jagged in\n\t\t * smaller thumbnail format.\n\t\t *\n\t\t * After investigation it was discovered that scaling incrementally by\n\t\t * smaller increments was the ONLY way to make the thumbnail sized\n\t\t * images look less jagged and more accurate; almost matching the\n\t\t * accuracy of Mac's built in thumbnail generation which is the highest\n\t\t * quality resize I've come across (better than GIMP Lanczos3 and\n\t\t * Windows 7).\n\t\t *\n\t\t * A divisor of 7 was chose as using 5 still left some jaggedness in the\n\t\t * image while a divisor of 8 or higher made the resulting thumbnail too\n\t\t * soft; like our OP_ANTIALIAS convolve op had been forcibly applied to\n\t\t * the result even if the user didn't want it that soft.\n\t\t *\n\t\t * Using a divisor of 7 for the ULTRA_QUALITY seemed to be the sweet\n\t\t * spot.\n\t\t *\n\t\t * NOTE: Below when the actual fraction is used to calculate the small\n\t\t * portion to subtract from the current dimension, this is a\n\t\t * progressively smaller and smaller chunk. When the code was changed to\n\t\t * do a linear reduction of the image of equal steps for each\n\t\t * incremental resize (e.g. say 50px each time) the result was\n\t\t * significantly worse than the progressive approach used below; even\n\t\t * when a very high number of incremental steps (13) was tested.\n\t\t */\n int fraction = (scalingMethod == Method.ULTRA_QUALITY ? 7 : 2);\n\n do {\n int prevCurrentWidth = currentWidth;\n int prevCurrentHeight = currentHeight;\n\n\t\t\t/*\n\t\t\t * If the current width is bigger than our target, cut it in half\n\t\t\t * and sample again.\n\t\t\t */\n if (currentWidth > targetWidth) {\n currentWidth -= (currentWidth / fraction);\n\n\t\t\t\t/*\n\t\t\t\t * If we cut the width too far it means we are on our last\n\t\t\t\t * iteration. Just set it to the target width and finish up.\n\t\t\t\t */\n if (currentWidth < targetWidth)\n currentWidth = targetWidth;\n }\n\n\t\t\t/*\n\t\t\t * If the current height is bigger than our target, cut it in half\n\t\t\t * and sample again.\n\t\t\t */\n\n if (currentHeight > targetHeight) {\n currentHeight -= (currentHeight / fraction);\n\n\t\t\t\t/*\n\t\t\t\t * If we cut the height too far it means we are on our last\n\t\t\t\t * iteration. Just set it to the target height and finish up.\n\t\t\t\t */\n\n if (currentHeight < targetHeight)\n currentHeight = targetHeight;\n }\n\n\t\t\t/*\n\t\t\t * Stop when we cannot incrementally step down anymore.\n\t\t\t *\n\t\t\t * This used to use a || condition, but that would cause problems\n\t\t\t * when using FIT_EXACT such that sometimes the width OR height\n\t\t\t * would not change between iterations, but the other dimension\n\t\t\t * would (e.g. resizing 500x500 to 500x250).\n\t\t\t *\n\t\t\t * Now changing this to an && condition requires that both\n\t\t\t * dimensions do not change between a resize iteration before we\n\t\t\t * consider ourselves done.\n\t\t\t */\n if (prevCurrentWidth == currentWidth\n && prevCurrentHeight == currentHeight)\n break;\n\n if (DEBUG)\n log(2, \"Scaling from [%d x %d] to [%d x %d]\", prevCurrentWidth,\n prevCurrentHeight, currentWidth, currentHeight);\n\n // Render the incremental scaled image.\n BufferedImage incrementalImage = scaleImage(src, currentWidth,\n currentHeight, interpolationHintValue);\n\n\t\t\t/*\n\t\t\t * Before re-assigning our interim (partially scaled)\n\t\t\t * incrementalImage to be the new src image before we iterate around\n\t\t\t * again to process it down further, we want to flush() the previous\n\t\t\t * src image IF (and only IF) it was one of our own temporary\n\t\t\t * BufferedImages created during this incremental down-sampling\n\t\t\t * cycle. If it wasn't one of ours, then it was the original\n\t\t\t * caller-supplied BufferedImage in which case we don't want to\n\t\t\t * flush() it and just leave it alone.\n\t\t\t */\n if (hasReassignedSrc)\n src.flush();\n\n\t\t\t/*\n\t\t\t * Now treat our incremental partially scaled image as the src image\n\t\t\t * and cycle through our loop again to do another incremental\n\t\t\t * scaling of it (if necessary).\n\t\t\t */\n src = incrementalImage;\n\n\t\t\t/*\n\t\t\t * Keep track of us re-assigning the original caller-supplied source\n\t\t\t * image with one of our interim BufferedImages so we know when to\n\t\t\t * explicitly flush the interim \"src\" on the next cycle through.\n\t\t\t */\n hasReassignedSrc = true;\n\n // Track how many times we go through this cycle to scale the image.\n incrementCount++;\n } while (currentWidth != targetWidth || currentHeight != targetHeight);\n\n if (DEBUG)\n log(2, \"Incrementally Scaled Image in %d steps.\", incrementCount);\n\n\t\t/*\n\t\t * Once the loop has exited, the src image argument is now our scaled\n\t\t * result image that we want to return.\n\t\t */\n return src;\n }\n}", "public class AnimatedGifEncoder\n{\n\n protected int width; // image size\n\n protected int height;\n\n protected Color transparent = null; // transparent color if given\n\n protected int transIndex; // transparent index in color table\n\n protected int repeat = -1; // no repeat\n\n protected int delay = 0; // frame delay (hundredths)\n\n protected boolean started = false; // ready to output frames\n\n protected OutputStream out;\n\n protected BufferedImage image; // current frame\n\n protected byte[] pixels; // BGR byte array from frame\n\n protected byte[] indexedPixels; // converted frame indexed to palette\n\n protected int colorDepth; // number of bit planes\n\n protected byte[] colorTab; // RGB palette\n\n protected boolean[] usedEntry = new boolean[256]; // active palette entries\n\n protected int palSize = 7; // color table size (bits-1)\n\n protected int dispose = -1; // disposal code (-1 = use default)\n\n protected boolean closeStream = false; // close stream when finished\n\n protected boolean firstFrame = true;\n\n protected boolean sizeSet = false; // if false, get size from first frame\n\n protected int sample = 10; // default sample interval for quantizer\n\n /**\n * Sets the delay time between each frame, or changes it for subsequent frames\n * (applies to last frame added).\n *\n * @param ms int delay time in milliseconds\n */\n public void setDelay(int ms)\n {\n delay = Math.round(ms / 10.0f);\n }\n\n /**\n * Sets the GIF frame disposal code for the last added frame and any\n * subsequent frames. Default is 0 if no transparent color has been set,\n * otherwise 2.\n *\n * @param code int disposal code.\n */\n public void setDispose(int code)\n {\n if (code >= 0)\n {\n dispose = code;\n }\n }\n\n /**\n * Sets the number of times the set of GIF frames should be played. Default is\n * 1; 0 means play indefinitely. Must be invoked before the first image is\n * added.\n *\n * @param iter int number of iterations.\n * @return\n */\n public void setRepeat(int iter)\n {\n if (iter >= 0)\n {\n repeat = iter;\n }\n }\n\n /**\n * Sets the transparent color for the last added frame and any subsequent\n * frames. Since all colors are subject to modification in the quantization\n * process, the color in the final palette for each frame closest to the given\n * color becomes the transparent color for that frame. May be set to null to\n * indicate no transparent color.\n *\n * @param c Color to be treated as transparent on display.\n */\n public void setTransparent(Color c)\n {\n transparent = c;\n }\n\n /**\n * Adds next GIF frame. The frame is not written immediately, but is actually\n * deferred until the next frame is received so that timing data can be\n * inserted. Invoking <code>finish()</code> flushes all frames. If\n * <code>setSize</code> was not invoked, the size of the first image is used\n * for all subsequent frames.\n *\n * @param im BufferedImage containing frame to write.\n * @return true if successful.\n */\n public boolean addFrame(BufferedImage im)\n {\n if ((im == null) || !started)\n {\n return false;\n }\n boolean ok = true;\n try\n {\n if (!sizeSet)\n {\n // use first frame's size\n setSize(im.getWidth(), im.getHeight());\n }\n image = im;\n getImagePixels(); // convert to correct format if necessary\n analyzePixels(); // build color table & map pixels\n if (firstFrame)\n {\n writeLSD(); // logical screen descriptior\n writePalette(); // global color table\n if (repeat >= 0)\n {\n // use NS app extension to indicate reps\n writeNetscapeExt();\n }\n }\n writeGraphicCtrlExt(); // write graphic control extension\n writeImageDesc(); // image descriptor\n if (!firstFrame)\n {\n writePalette(); // local color table\n }\n writePixels(); // encode and write pixel data\n firstFrame = false;\n } catch (IOException e)\n {\n ok = false;\n }\n\n return ok;\n }\n\n /**\n * Flushes any pending data and closes output file. If writing to an\n * OutputStream, the stream is not closed.\n */\n public boolean finish()\n {\n if (!started)\n return false;\n boolean ok = true;\n started = false;\n try\n {\n out.write(0x3b); // gif trailer\n out.flush();\n if (closeStream)\n {\n out.close();\n }\n } catch (IOException e)\n {\n ok = false;\n }\n\n // reset for subsequent use\n transIndex = 0;\n out = null;\n image = null;\n pixels = null;\n indexedPixels = null;\n colorTab = null;\n closeStream = false;\n firstFrame = true;\n\n return ok;\n }\n\n /**\n * Sets frame rate in frames per second. Equivalent to\n * <code>setDelay(1000/fps)</code>.\n *\n * @param fps float frame rate (frames per second)\n */\n public void setFrameRate(float fps)\n {\n if (fps != 0f)\n {\n delay = Math.round(100f / fps);\n }\n }\n\n /**\n * Sets quality of color quantization (conversion of images to the maximum 256\n * colors allowed by the GIF specification). Lower values (minimum = 1)\n * produce better colors, but slow processing significantly. 10 is the\n * default, and produces good color mapping at reasonable speeds. Values\n * greater than 20 do not yield significant improvements in speed.\n *\n * @param quality int greater than 0.\n * @return\n */\n public void setQuality(int quality)\n {\n if (quality < 1)\n quality = 1;\n sample = quality;\n }\n\n /**\n * Sets the GIF frame size. The default size is the size of the first frame\n * added if this method is not invoked.\n *\n * @param w int frame width.\n * @param h int frame width.\n */\n public void setSize(int w, int h)\n {\n if (started && !firstFrame)\n return;\n width = w;\n height = h;\n if (width < 1)\n width = 320;\n if (height < 1)\n height = 240;\n sizeSet = true;\n }\n\n /**\n * Initiates GIF file creation on the given stream. The stream is not closed\n * automatically.\n *\n * @param os OutputStream on which GIF images are written.\n * @return false if initial write failed.\n */\n public boolean start(OutputStream os)\n {\n if (os == null)\n return false;\n boolean ok = true;\n closeStream = false;\n out = os;\n try\n {\n writeString(\"GIF89a\"); // header\n } catch (IOException e)\n {\n ok = false;\n }\n return started = ok;\n }\n\n /**\n * Initiates writing of a GIF file with the specified name.\n *\n * @param file String containing output file name.\n * @return false if open or initial write failed.\n */\n public boolean start(String file)\n {\n boolean ok = true;\n try\n {\n out = new BufferedOutputStream(new FileOutputStream(file));\n ok = start(out);\n closeStream = true;\n } catch (IOException e)\n {\n ok = false;\n }\n return started = ok;\n }\n\n /**\n * Analyzes image colors and creates color map.\n */\n protected void analyzePixels()\n {\n int len = pixels.length;\n int nPix = len / 3;\n indexedPixels = new byte[nPix];\n NeuQuant nq = new NeuQuant(pixels, len, sample);\n // initialize quantizer\n colorTab = nq.process(); // create reduced palette\n // convert map from BGR to RGB\n for (int i = 0; i < colorTab.length; i += 3)\n {\n byte temp = colorTab[i];\n colorTab[i] = colorTab[i + 2];\n colorTab[i + 2] = temp;\n usedEntry[i / 3] = false;\n }\n // map image pixels to new palette\n int k = 0;\n for (int i = 0; i < nPix; i++)\n {\n int index = nq.map(pixels[k++] & 0xff, pixels[k++] & 0xff, pixels[k++] & 0xff);\n usedEntry[index] = true;\n indexedPixels[i] = (byte) index;\n }\n pixels = null;\n colorDepth = 8;\n palSize = 7;\n // get closest match to transparent color if specified\n if (transparent != null)\n {\n transIndex = findClosest(transparent);\n }\n }\n\n /**\n * Returns index of palette color closest to c\n */\n protected int findClosest(Color c)\n {\n if (colorTab == null)\n return -1;\n int r = c.getRed();\n int g = c.getGreen();\n int b = c.getBlue();\n int minpos = 0;\n int dmin = 256 * 256 * 256;\n int len = colorTab.length;\n for (int i = 0; i < len; )\n {\n int dr = r - (colorTab[i++] & 0xff);\n int dg = g - (colorTab[i++] & 0xff);\n int db = b - (colorTab[i] & 0xff);\n int d = dr * dr + dg * dg + db * db;\n int index = i / 3;\n if (usedEntry[index] && (d < dmin))\n {\n dmin = d;\n minpos = index;\n }\n i++;\n }\n return minpos;\n }\n\n /**\n * Extracts image pixels into byte array \"pixels\"\n */\n protected void getImagePixels()\n {\n int w = image.getWidth();\n int h = image.getHeight();\n int type = image.getType();\n if ((w != width) || (h != height) || (type != BufferedImage.TYPE_3BYTE_BGR))\n {\n // create new image with right size/format\n BufferedImage temp = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);\n Graphics2D g = temp.createGraphics();\n g.drawImage(image, 0, 0, null);\n image = temp;\n }\n pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();\n }\n\n /**\n * Writes Graphic Control Extension\n */\n protected void writeGraphicCtrlExt() throws IOException\n {\n out.write(0x21); // extension introducer\n out.write(0xf9); // GCE label\n out.write(4); // data block size\n int transp, disp;\n if (transparent == null)\n {\n transp = 0;\n disp = 0; // dispose = no action\n } else\n {\n transp = 1;\n disp = 2; // force clear if using transparent color\n }\n if (dispose >= 0)\n {\n disp = dispose & 7; // user override\n }\n disp <<= 2;\n\n // packed fields\n out.write(0 | // 1:3 reserved\n disp | // 4:6 disposal\n 0 | // 7 user input - 0 = none\n transp); // 8 transparency flag\n\n writeShort(delay); // delay x 1/100 sec\n out.write(transIndex); // transparent color index\n out.write(0); // block terminator\n }\n\n /**\n * Writes Image Descriptor\n */\n protected void writeImageDesc() throws IOException\n {\n out.write(0x2c); // image separator\n writeShort(0); // image position x,y = 0,0\n writeShort(0);\n writeShort(width); // image size\n writeShort(height);\n // packed fields\n if (firstFrame)\n {\n // no LCT - GCT is used for first (or only) frame\n out.write(0);\n } else\n {\n // specify normal LCT\n out.write(0x80 | // 1 local color table 1=yes\n 0 | // 2 interlace - 0=no\n 0 | // 3 sorted - 0=no\n 0 | // 4-5 reserved\n palSize); // 6-8 size of color table\n }\n }\n\n /**\n * Writes Logical Screen Descriptor\n */\n protected void writeLSD() throws IOException\n {\n // logical screen size\n writeShort(width);\n writeShort(height);\n // packed fields\n out.write((0x80 | // 1 : global color table flag = 1 (gct used)\n 0x70 | // 2-4 : color resolution = 7\n 0x00 | // 5 : gct sort flag = 0\n palSize)); // 6-8 : gct size\n\n out.write(0); // background color index\n out.write(0); // pixel aspect ratio - assume 1:1\n }\n\n /**\n * Writes Netscape application extension to define repeat count.\n */\n protected void writeNetscapeExt() throws IOException\n {\n out.write(0x21); // extension introducer\n out.write(0xff); // app extension label\n out.write(11); // block size\n writeString(\"NETSCAPE\" + \"2.0\"); // app id + auth code\n out.write(3); // sub-block size\n out.write(1); // loop sub-block id\n writeShort(repeat); // loop count (extra iterations, 0=repeat forever)\n out.write(0); // block terminator\n }\n\n /**\n * Writes color table\n */\n protected void writePalette() throws IOException\n {\n out.write(colorTab, 0, colorTab.length);\n int n = (3 * 256) - colorTab.length;\n for (int i = 0; i < n; i++)\n {\n out.write(0);\n }\n }\n\n /**\n * Encodes and writes pixel data\n */\n protected void writePixels() throws IOException\n {\n LZWEncoder encoder = new LZWEncoder(width, height, indexedPixels, colorDepth);\n encoder.encode(out);\n }\n\n /**\n * Write 16-bit value to output stream, LSB first\n */\n protected void writeShort(int value) throws IOException\n {\n out.write(value & 0xff);\n out.write((value >> 8) & 0xff);\n }\n\n /**\n * Writes string to output stream\n */\n protected void writeString(String s) throws IOException\n {\n for (int i = 0; i < s.length(); i++)\n {\n out.write((byte) s.charAt(i));\n }\n }\n}", "public class GifDecoder\n{\n\n /**\n * File read status: No errors.\n */\n public static final int STATUS_OK = 0;\n /**\n * File read status: Error decoding file (may be partially decoded)\n */\n public static final int STATUS_FORMAT_ERROR = 1;\n /**\n * File read status: Unable to open source.\n */\n public static final int STATUS_OPEN_ERROR = 2;\n protected BufferedInputStream in;\n protected int status;\n protected int width; // full image width\n\n protected int height; // full image height\n\n protected boolean gctFlag; // global color table used\n\n protected int gctSize; // size of global color table\n\n protected int loopCount = 1; // iterations; 0 = repeat forever\n\n protected int[] gct; // global color table\n\n protected int[] lct; // local color table\n\n protected int[] act; // active color table\n\n protected int bgIndex; // background color index\n\n protected int bgColor; // background color\n\n protected int lastBgColor; // previous bg color\n\n protected int pixelAspect; // pixel aspect ratio\n\n protected boolean lctFlag; // local color table flag\n\n protected boolean interlace; // interlace flag\n\n protected int lctSize; // local color table size\n\n protected int ix, iy, iw, ih; // current image rectangle\n\n protected Rectangle lastRect; // last image rect\n\n protected BufferedImage image; // current frame\n\n protected BufferedImage lastImage; // previous frame\n\n protected byte[] block = new byte[256]; // current data block\n\n protected int blockSize = 0; // block size\n\n // last graphic control extension info\n protected int dispose = 0;\n // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev\n protected int lastDispose = 0;\n protected boolean transparency = false; // use transparent color\n\n protected int delay = 0; // delay in milliseconds\n\n protected int transIndex; // transparent color index\n\n protected static final int MaxStackSize = 4096;\n // max decoder pixel stack size\n\n // LZW decoder working arrays\n protected short[] prefix;\n protected byte[] suffix;\n protected byte[] pixelStack;\n protected byte[] pixels;\n protected ArrayList<GifFrame> frames; // frames read from current file\n\n protected int frameCount;\n\n static class GifFrame\n {\n\n public GifFrame(BufferedImage im, int del)\n {\n image = im;\n delay = del;\n }\n\n public BufferedImage image;\n public int delay;\n }\n\n /**\n * Gets display duration for specified frame.\n *\n * @param n int index of frame\n * @return delay in milliseconds\n */\n public int getDelay(int n)\n {\n //\n delay = -1;\n if ((n >= 0) && (n < frameCount))\n {\n delay = frames.get(n).delay;\n }\n return delay;\n }\n\n /**\n * Gets the number of frames read from file.\n *\n * @return frame count\n */\n public int getFrameCount()\n {\n return frameCount;\n }\n\n /**\n * Gets the first (or only) image read.\n *\n * @return BufferedImage containing first frame, or null if none.\n */\n public BufferedImage getImage()\n {\n return getFrame(0);\n }\n\n /**\n * Gets the \"Netscape\" iteration count, if any.\n * A count of 0 means repeat indefinitiely.\n *\n * @return iteration count if one was specified, else 1.\n */\n public int getLoopCount()\n {\n return loopCount;\n }\n\n /**\n * Creates new frame image from current data (and previous\n * frames as specified by their disposition codes).\n */\n protected void setPixels()\n {\n // expose destination image's pixels as int array\n int[] dest =\n ((DataBufferInt) image.getRaster().getDataBuffer()).getData();\n\n // fill in starting image contents based on last image's dispose code\n if (lastDispose > 0)\n {\n if (lastDispose == 3)\n {\n // use image before last\n int n = frameCount - 2;\n if (n > 0)\n {\n lastImage = getFrame(n - 1);\n } else\n {\n lastImage = null;\n }\n }\n\n if (lastImage != null)\n {\n int[] prev =\n ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData();\n System.arraycopy(prev, 0, dest, 0, width * height);\n // copy pixels\n\n if (lastDispose == 2)\n {\n // fill last image rect area with background color\n Graphics2D g = image.createGraphics();\n Color c = null;\n if (transparency)\n {\n c = new Color(0, 0, 0, 0); // assume background is transparent\n\n } else\n {\n c = new Color(lastBgColor); // use given background color\n\n }\n g.setColor(c);\n g.setComposite(AlphaComposite.Src); // replace area\n\n g.fill(lastRect);\n g.dispose();\n }\n }\n }\n\n // copy each source line to the appropriate place in the destination\n int pass = 1;\n int inc = 8;\n int iline = 0;\n for (int i = 0; i < ih; i++)\n {\n int line = i;\n if (interlace)\n {\n if (iline >= ih)\n {\n pass++;\n switch (pass)\n {\n case 2:\n iline = 4;\n break;\n case 3:\n iline = 2;\n inc = 4;\n break;\n case 4:\n iline = 1;\n inc = 2;\n }\n }\n line = iline;\n iline += inc;\n }\n line += iy;\n if (line < height)\n {\n int k = line * width;\n int dx = k + ix; // start of line in dest\n\n int dlim = dx + iw; // end of dest line\n\n if ((k + width) < dlim)\n {\n dlim = k + width; // past dest edge\n\n }\n int sx = i * iw; // start of line in source\n\n while (dx < dlim)\n {\n // map color and insert in destination\n int index = ((int) pixels[sx++]) & 0xff;\n int c = act[index];\n if (c != 0)\n {\n dest[dx] = c;\n }\n dx++;\n }\n }\n }\n }\n\n /**\n * Gets the image contents of frame n.\n *\n * @return BufferedImage representation of frame, or null if n is invalid.\n */\n public BufferedImage getFrame(int n)\n {\n BufferedImage im = null;\n if ((n >= 0) && (n < frameCount))\n {\n im = frames.get(n).image;\n }\n return im;\n }\n\n /**\n * Gets image size.\n *\n * @return GIF image dimensions\n */\n public Dimension getFrameSize()\n {\n return new Dimension(width, height);\n }\n\n /**\n * Reads GIF image from stream\n *\n * @param is BufferedInputStream containing GIF file.\n * @return read status code (0 = no errors)\n */\n public int read(BufferedInputStream is)\n {\n init();\n if (is == null) return STATUS_OPEN_ERROR;\n\n try (BufferedInputStream bis = is)\n {\n in = bis;\n readHeader();\n if (!err())\n {\n readContents();\n if (frameCount < 0)\n {\n status = STATUS_FORMAT_ERROR;\n }\n }\n } catch (Exception e)\n {\n status = STATUS_OPEN_ERROR;\n }\n return status;\n }\n\n /**\n * Reads GIF image from stream\n *\n * @param is InputStream containing GIF file.\n * @return read status code (0 = no errors)\n */\n public int read(InputStream is)\n {\n init();\n\n if (is == null) return STATUS_OPEN_ERROR;\n\n try (BufferedInputStream bis = (is instanceof BufferedInputStream) ? (BufferedInputStream) is : new BufferedInputStream(is))\n {\n in = bis;\n readHeader();\n if (!err())\n {\n readContents();\n if (frameCount < 0)\n {\n status = STATUS_FORMAT_ERROR;\n }\n }\n } catch (Exception e)\n {\n status = STATUS_OPEN_ERROR;\n }\n\n return status;\n }\n\n /**\n * Reads GIF file from specified file/URL source\n * (URL assumed if name contains \":/\" or \"file:\")\n *\n * @param name String containing source\n * @return read status code (0 = no errors)\n */\n public int read(String name)\n {\n status = STATUS_OK;\n try\n {\n name = name.trim().toLowerCase();\n if (name.contains(\"file:\") || (name.indexOf(\":/\") > 0))\n {\n URL url = new URL(name);\n in = new BufferedInputStream(url.openStream());\n } else\n {\n in = new BufferedInputStream(new FileInputStream(name));\n }\n status = read(in);\n } catch (IOException e)\n {\n status = STATUS_OPEN_ERROR;\n }\n\n return status;\n }\n\n /**\n * Decodes LZW image data into pixel array.\n * Adapted from John Cristy's ImageMagick.\n */\n protected void decodeImageData()\n {\n int NullCode = -1;\n int npix = iw * ih;\n int available,\n clear,\n code_mask,\n code_size,\n end_of_information,\n in_code,\n old_code,\n bits,\n code,\n count,\n i,\n datum,\n data_size,\n first,\n top,\n bi,\n pi;\n\n if ((pixels == null) || (pixels.length < npix))\n {\n pixels = new byte[npix]; // allocate new pixel array\n\n }\n if (prefix == null)\n {\n prefix = new short[MaxStackSize];\n }\n if (suffix == null)\n {\n suffix = new byte[MaxStackSize];\n }\n if (pixelStack == null)\n {\n pixelStack = new byte[MaxStackSize + 1];\n\n // Initialize GIF data stream decoder.\n }\n data_size = read();\n clear = 1 << data_size;\n end_of_information = clear + 1;\n available = clear + 2;\n old_code = NullCode;\n code_size = data_size + 1;\n code_mask = (1 << code_size) - 1;\n for (code = 0; code < clear; code++)\n {\n prefix[code] = 0;\n suffix[code] = (byte) code;\n }\n\n // Decode GIF pixel stream.\n\n datum = bits = count = first = top = pi = bi = 0;\n\n for (i = 0; i < npix; )\n {\n if (top == 0)\n {\n if (bits < code_size)\n {\n // Load bytes until there are enough bits for a code.\n if (count == 0)\n {\n // Read a new data block.\n count = readBlock();\n if (count <= 0)\n {\n break;\n }\n bi = 0;\n }\n datum += (((int) block[bi]) & 0xff) << bits;\n bits += 8;\n bi++;\n count--;\n continue;\n }\n\n // Get the next code.\n\n code = datum & code_mask;\n datum >>= code_size;\n bits -= code_size;\n\n // Interpret the code\n\n if ((code > available) || (code == end_of_information))\n {\n break;\n }\n if (code == clear)\n {\n // Reset decoder.\n code_size = data_size + 1;\n code_mask = (1 << code_size) - 1;\n available = clear + 2;\n old_code = NullCode;\n continue;\n }\n if (old_code == NullCode)\n {\n pixelStack[top++] = suffix[code];\n old_code = code;\n first = code;\n continue;\n }\n in_code = code;\n if (code == available)\n {\n pixelStack[top++] = (byte) first;\n code = old_code;\n }\n while (code > clear)\n {\n pixelStack[top++] = suffix[code];\n code = prefix[code];\n }\n first = ((int) suffix[code]) & 0xff;\n\n // Add a new string to the string table,\n\n if (available >= MaxStackSize)\n {\n break;\n }\n pixelStack[top++] = (byte) first;\n prefix[available] = (short) old_code;\n suffix[available] = (byte) first;\n available++;\n if (((available & code_mask) == 0) && (available < MaxStackSize))\n {\n code_size++;\n code_mask += available;\n }\n old_code = in_code;\n }\n\n // Pop a pixel off the pixel stack.\n\n top--;\n pixels[pi++] = pixelStack[top];\n i++;\n }\n\n for (i = pi; i < npix; i++)\n {\n pixels[i] = 0; // clear missing pixels\n\n }\n\n }\n\n /**\n * Returns true if an error was encountered during reading/decoding\n */\n protected boolean err()\n {\n return status != STATUS_OK;\n }\n\n /**\n * Initializes or re-initializes reader\n */\n protected void init()\n {\n status = STATUS_OK;\n frameCount = 0;\n frames = new ArrayList<>();\n gct = null;\n lct = null;\n }\n\n /**\n * Reads a single byte from the input stream.\n */\n protected int read()\n {\n int curByte = 0;\n try\n {\n curByte = in.read();\n } catch (IOException e)\n {\n status = STATUS_FORMAT_ERROR;\n }\n return curByte;\n }\n\n /**\n * Reads next variable length block from input.\n *\n * @return number of bytes stored in \"buffer\"\n */\n protected int readBlock()\n {\n blockSize = read();\n int n = 0;\n if (blockSize > 0)\n {\n try\n {\n int count = 0;\n while (n < blockSize)\n {\n count = in.read(block, n, blockSize - n);\n if (count == -1)\n {\n break;\n }\n n += count;\n }\n } catch (IOException e)\n {\n }\n\n if (n < blockSize)\n {\n status = STATUS_FORMAT_ERROR;\n }\n }\n return n;\n }\n\n /**\n * Reads color table as 256 RGB integer values\n *\n * @param ncolors int number of colors to read\n * @return int array containing 256 colors (packed ARGB with full alpha)\n */\n protected int[] readColorTable(int ncolors)\n {\n int nbytes = 3 * ncolors;\n int[] tab = null;\n byte[] c = new byte[nbytes];\n int n = 0;\n try\n {\n n = in.read(c);\n } catch (IOException e)\n {\n }\n if (n < nbytes)\n {\n status = STATUS_FORMAT_ERROR;\n } else\n {\n tab = new int[256]; // max size to avoid bounds checks\n\n int i = 0;\n int j = 0;\n while (i < ncolors)\n {\n int r = ((int) c[j++]) & 0xff;\n int g = ((int) c[j++]) & 0xff;\n int b = ((int) c[j++]) & 0xff;\n tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;\n }\n }\n return tab;\n }\n\n /**\n * Main file parser. Reads GIF content blocks.\n */\n protected void readContents()\n {\n // read GIF file content blocks\n boolean done = false;\n while (!(done || err()))\n {\n int code = read();\n switch (code)\n {\n\n case 0x2C: // image separator\n\n readImage();\n break;\n\n case 0x21: // extension\n\n code = read();\n switch (code)\n {\n case 0xf9: // graphics control extension\n\n readGraphicControlExt();\n break;\n\n case 0xff: // application extension\n\n readBlock();\n String app = \"\";\n for (int i = 0; i < 11; i++)\n {\n app += (char) block[i];\n }\n if (app.equals(\"NETSCAPE2.0\"))\n {\n readNetscapeExt();\n } else\n {\n skip(); // don't care\n\n }\n break;\n\n default: // uninteresting extension\n\n skip();\n }\n break;\n\n case 0x3b: // terminator\n\n done = true;\n break;\n\n case 0x00: // bad byte, but keep going and see what happens\n\n break;\n\n default:\n status = STATUS_FORMAT_ERROR;\n }\n }\n }\n\n /**\n * Reads Graphics Control Extension values\n */\n protected void readGraphicControlExt()\n {\n read(); // block size\n\n int packed = read(); // packed fields\n\n dispose = (packed & 0x1c) >> 2; // disposal method\n\n if (dispose == 0)\n {\n dispose = 1; // elect to keep old image if discretionary\n\n }\n transparency = (packed & 1) != 0;\n delay = readShort() * 10; // delay in milliseconds\n\n transIndex = read(); // transparent color index\n\n read(); // block terminator\n\n }\n\n /**\n * Reads GIF file header information.\n */\n protected void readHeader()\n {\n String id = \"\";\n for (int i = 0; i < 6; i++)\n {\n id += (char) read();\n }\n if (!id.startsWith(\"GIF\"))\n {\n status = STATUS_FORMAT_ERROR;\n return;\n }\n\n readLSD();\n if (gctFlag && !err())\n {\n gct = readColorTable(gctSize);\n bgColor = gct[bgIndex];\n }\n }\n\n /**\n * Reads next frame image\n */\n protected void readImage()\n {\n ix = readShort(); // (sub)image position & size\n\n iy = readShort();\n iw = readShort();\n ih = readShort();\n\n int packed = read();\n lctFlag = (packed & 0x80) != 0; // 1 - local color table flag\n\n interlace = (packed & 0x40) != 0; // 2 - interlace flag\n // 3 - sort flag\n // 4-5 - reserved\n\n lctSize = 2 << (packed & 7); // 6-8 - local color table size\n\n if (lctFlag)\n {\n lct = readColorTable(lctSize); // read table\n\n act = lct; // make local table active\n\n } else\n {\n act = gct; // make global table active\n\n if (bgIndex == transIndex)\n {\n bgColor = 0;\n }\n }\n int save = 0;\n if (transparency)\n {\n save = act[transIndex];\n act[transIndex] = 0; // set transparent color if specified\n\n }\n\n if (act == null)\n {\n status = STATUS_FORMAT_ERROR; // no color table defined\n\n }\n\n if (err())\n {\n return;\n }\n decodeImageData(); // decode pixel data\n\n skip();\n\n if (err())\n {\n return;\n }\n frameCount++;\n\n // create new image to receive frame data\n image =\n new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);\n\n setPixels(); // transfer pixel data to image\n\n frames.add(new GifFrame(image, delay)); // add image to frame list\n\n if (transparency)\n {\n act[transIndex] = save;\n }\n resetFrame();\n\n }\n\n /**\n * Reads Logical Screen Descriptor\n */\n protected void readLSD()\n {\n\n // logical screen size\n width = readShort();\n height = readShort();\n\n // packed fields\n int packed = read();\n gctFlag = (packed & 0x80) != 0; // 1 : global color table flag\n // 2-4 : color resolution\n // 5 : gct sort flag\n\n gctSize = 2 << (packed & 7); // 6-8 : gct size\n\n bgIndex = read(); // background color index\n\n pixelAspect = read(); // pixel aspect ratio\n\n }\n\n /**\n * Reads Netscape extenstion to obtain iteration count\n */\n protected void readNetscapeExt()\n {\n do\n {\n readBlock();\n if (block[0] == 1)\n {\n // loop count sub-block\n int b1 = ((int) block[1]) & 0xff;\n int b2 = ((int) block[2]) & 0xff;\n loopCount = (b2 << 8) | b1;\n }\n } while ((blockSize > 0) && !err());\n }\n\n /**\n * Reads next 16-bit value, LSB first\n */\n protected int readShort()\n {\n // read 16-bit value, LSB first\n return read() | (read() << 8);\n }\n\n /**\n * Resets frame state for reading next image.\n */\n protected void resetFrame()\n {\n lastDispose = dispose;\n lastRect = new Rectangle(ix, iy, iw, ih);\n lastImage = image;\n lastBgColor = bgColor;\n//\t\tint dispose = 0;\n//\t\tboolean transparency = false;\n//\t\tint delay = 0;\n dispose = 0;\n transparency = false;\n delay = 0;\n lct = null;\n }\n\n /**\n * Skips variable length blocks up to and including\n * next zero length block.\n */\n protected void skip()\n {\n do\n {\n readBlock();\n } while ((blockSize > 0) && !err());\n }\n}", "public class Utils {\n\n /**\n * Returns a random number from 0 to the specified.\n *\n * @param param The max number to choose.\n */\n public static int nextInt(int param) {\n return random(0, param);\n }\n\n /**\n * Calls the #getExtension(String) method using the file name of the file.\n *\n * @param f The file to get the extension of.\n * @return The extension of the file, or null if there is none.\n */\n public static String getExtension(File f) {\n return getExtension(f.getName());\n }\n\n /**\n * Gets the extension of a file.\n *\n * @param fileName Name of the file to get the extension of.\n * @return The file's extension (ex: \".png\" or \".wav\"), or null if there is none.\n */\n public static String getExtension(String fileName) {\n String ext = null;\n int i = fileName.lastIndexOf('.');\n int len = fileName.length();\n int after = len - i;\n if (i > 0 && (i < len - 1) && after < 5) {//has to be near the end\n ext = fileName.substring(i).toLowerCase();\n }\n return ext;\n }\n\n /**\n * Sets the extension of a file to the specified extension.\n * <p>\n * This can also be used as an assurance that the extension of the\n * file is the specified extension.\n * <p>\n * It's expected that this method will be called before any file saving is\n * done.\n *\n * @param fileName The name of the file to change the extension of.\n * @param extension The extension (ex: \".png\" or \".wav\") for the file.\n * @return The filename with the new extension.\n */\n public static String setExtension(String fileName, String extension) {\n String ext = getExtension(fileName);\n if (ext != null) {\n if (!ext.equalsIgnoreCase(extension)) {\n fileName = fileName.substring(0, fileName.indexOf(ext)) + extension;\n }\n } else {\n fileName = fileName + extension;\n }\n return fileName;\n }\n\n /**\n * Converts a font to string. Only really used in the Settings GUI.\n * (Font#toString() was too messy for me, and fuck making a wrapper class.\n *\n * @return The name, size, and style of the font.\n */\n public static String fontToString(Font f) {\n String toRet = \"\";\n if (f != null) {\n String type;\n if (f.isBold()) {\n type = f.isItalic() ? \"Bold Italic\" : \"Bold\";\n } else {\n type = f.isItalic() ? \"Italic\" : \"Plain\";\n }\n toRet = f.getName() + \",\" + f.getSize() + \",\" + type;\n }\n return toRet;\n }\n\n /**\n * Converts a formatted string (@see #fontToString()) into a font.\n *\n * @param fontString The string to be turned into a font.\n * @return The font.\n */\n public static Font stringToFont(String fontString) {\n String[] toFont = fontString.substring(fontString.indexOf('[') + 1, fontString.length() - 1).split(\",\");\n Font f = new Font(\"Calibri\", Font.PLAIN, 18);\n if (toFont.length == 4) {\n String name = \"Calibri\";\n int size = 18;\n int type = Font.PLAIN;\n for (String keyValPair : toFont) {\n String[] split = keyValPair.split(\"=\");\n String key = split[0];\n String val = split[1];\n switch (key) {\n case \"name\":\n name = val;\n break;\n case \"style\":\n switch (val) {\n case \"plain\":\n type = Font.PLAIN;\n break;\n case \"italic\":\n type = Font.ITALIC;\n break;\n case \"bolditalic\":\n type = Font.BOLD + Font.ITALIC;\n break;\n case \"bold\":\n type = Font.BOLD;\n break;\n default:\n type = Font.PLAIN;\n break;\n }\n break;\n case \"size\":\n try {\n size = Integer.parseInt(val);\n } catch (Exception e) {\n size = 18;\n }\n break;\n default:\n break;\n }\n }\n f = new Font(name, type, size);\n }\n return f;\n }\n\n\n /**\n * Adds a single string to an array of strings, first checking to see if the array contains it.\n *\n * @param toAdd The string(s) to add to the array.\n * @param array The array to add the string to.\n * @return The array of Strings.\n */\n public static String[] addStringsToArray(String[] array, String... toAdd) {\n ArrayList<String> list = new ArrayList<>();\n Collections.addAll(list, array);\n checkAndAdd(list, toAdd);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Compares two arrays of Strings and adds the non-repeating ones to the same one.\n *\n * @param list List of strings to compare to.\n * @param toAdd String(s) to add to the list.\n */\n public static void checkAndAdd(ArrayList<String> list, String... toAdd) {\n for (String s : toAdd) {\n if (!list.contains(s)) {\n list.add(s);\n }\n }\n }\n\n /**\n * Checks individual files one by one like #areFilesGood(String...) and\n * returns the good and legitimate files.\n *\n * @param files The path(s) to the file(s) to check.\n * @return The array of paths to files that actually exist.\n * @see #areFilesGood(String...) for determining if files exist.\n */\n public static String[] checkFiles(String... files) {\n ArrayList<String> list = new ArrayList<>();\n for (String s : files) {\n if (areFilesGood(s)) {\n list.add(s);\n }\n }\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Checks to see if the file(s) is (are) actually existing and non-blank.\n *\n * @param files The path(s) to the file(s) to check.\n * @return true if (all) the file(s) exist(s)\n * @see #checkFiles(String...) For removing bad files and adding the others anyway.\n */\n public static boolean areFilesGood(String... files) {\n int i = 0;\n for (String s : files) {\n File test = new File(s);\n if (test.exists() && test.length() > 0) i++;\n }\n return i == files.length;\n }\n\n /**\n * Logs the chat to a file.\n *\n * @param message The chat separated by newline characters.\n * @param channel The channel the chat was in.\n * @param type The int that determines what the logger should do.\n * 0 = boot\n * 1 = append (clear chat)\n * 2 = shutdown\n */\n public static void logChat(String[] message, String channel, int type) {\n if (channel.startsWith(\"#\")) channel = channel.substring(1);\n try {\n PrintWriter out = new PrintWriter(new BufferedWriter(\n new FileWriter(new File(Settings.logDir.getAbsolutePath() + File.separator + channel + \".txt\"), true)));\n if (type == 0) {\n out.println(\"====================== \" + Settings.date + \" ======================\");\n }\n if (message != null && !(message.length == 0 || (message.length == 1 && message[0].equalsIgnoreCase(\"\")))) {\n for (String s : message) {\n if (s != null && !s.equals(\"\") && !s.equals(\"\\n\")) {\n out.println(s);\n }\n }\n }\n if (type == 2) {\n out.println(\"====================== End of \" + Settings.date + \" ======================\");\n }\n out.close();\n } catch (IOException e) {\n GUIMain.log(e);\n }\n }\n\n /**\n * Removes the last file extension from a path.\n * <p>\n * Note that if the string contains multiple extensions, this will only remove the last one.\n * <p>\n * Ex: \"portal.png.exe.java\" becomes \"portal.png.exe\" after this method returns.\n *\n * @param s The path to a file, or the file name with its extension.\n * @return The file/path name without the extension.\n */\n public static String removeExt(String s) {\n int pos = s.lastIndexOf(\".\");\n if (pos == -1) return s;\n return s.substring(0, pos);\n }\n\n /**\n * Checks to see if the input is IRC-worthy of printing.\n *\n * @param input The input in question.\n * @return The given input if it checks out, otherwise nothing.\n */\n public static String checkText(String input) {\n input = input.trim();\n return !input.isEmpty() ? input : \"\";\n }\n\n /**\n * Returns a number between a given minimum and maximum (exclusive).\n *\n * @param min The minimum number to generate on.\n * @param max The non-inclusive maximum number to generate on.\n * @return Some random number between the given numbers.\n */\n public static int random(int min, int max) {\n return min + (max == min ? 0 : new Random().nextInt(max - min));\n }\n\n /**\n * Generates a color from the #hashCode() of any java.lang.Object.\n * <p>\n * Author - Dr_Kegel from Gocnak's stream.\n *\n * @param seed The Hashcode of the object you want dynamic color for.\n * @return The Color of the object's hash.\n */\n public static Color getColorFromHashcode(final int seed) {\n /* We do some bit hacks here\n hashCode has 32 bit, we use every bit as a random source */\n final int HUE_BITS = 12, HUE_MASK = ((1 << HUE_BITS) - 1);\n final int SATURATION_BITS = 8, SATURATION_MASK = ((1 << SATURATION_BITS) - 1);\n final int BRIGHTNESS_BITS = 12, BRIGHTNESS_MASK = ((1 << BRIGHTNESS_BITS) - 1);\n int t = seed;\n /*\n * We want the full hue spectrum, that means all colors of the color\n\t\t * circle\n\t\t */\n /* [0 .. 1] */\n final float h = (t & HUE_MASK) / (float) HUE_MASK;\n t >>= HUE_BITS;\n final float s = (t & SATURATION_MASK) / (float) SATURATION_MASK;\n t >>= SATURATION_BITS;\n final float b = (t & BRIGHTNESS_MASK) / (float) BRIGHTNESS_MASK;\n /* some tweaks that nor black nor white can be reached */\n /* at the moment h,s,b are in the range of [0 .. 1) */\n /* For s and b this is restricted to [0.75 .. 1) at the moment. */\n return Color.getHSBColor(h, s * 0.25f + 0.75f, b * 0.25f + 0.75f);\n }\n\n /**\n * Returns the SimpleAttributeSet for a specified URL.\n *\n * @param URL The link to make into a URL.\n * @return The SimpleAttributeSet of the URL.\n */\n public static SimpleAttributeSet URLStyle(String URL) {\n SimpleAttributeSet attrs = new SimpleAttributeSet();\n StyleConstants.setForeground(attrs, new Color(43, 162, 235));\n StyleConstants.setFontFamily(attrs, Settings.font.getValue().getFamily());\n StyleConstants.setFontSize(attrs, Settings.font.getValue().getSize());\n StyleConstants.setUnderline(attrs, true);\n attrs.addAttribute(HTML.Attribute.HREF, URL);\n return attrs;\n }\n\n /**\n * Credit: TDuva\n *\n * @param URL The URL to check\n * @return True if the URL can be formed, else false\n */\n public static boolean checkURL(String URL) {\n try {\n new URI(URL);\n } catch (Exception ignored) {\n return false;\n }\n return true;\n }\n\n /**\n * Checks if the given integer is within the range of any of the key=value\n * pairs of the Map (inclusive).\n * <p>\n * Credit: TDuva\n *\n * @param i The integer to check.\n * @param ranges The map of the ranges to check.\n * @return true if the given int is within the range set, else false\n */\n public static boolean inRanges(int i, Map<Integer, Integer> ranges) {\n for (Map.Entry<Integer, Integer> range : ranges.entrySet()) {\n if (i >= range.getKey() && i <= range.getValue()) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Converts a given int to the correct millis form, except for 0.\n *\n * @param given Integer to convert.\n * @return The correct Integer in milliseconds.\n */\n public static int handleInt(int given) {\n if (given < 1000 && given > 0) {// not in millis\n given = given * 1000; //convert to millis\n }\n return given;\n }\n\n /**\n * Gets a time (in seconds) from a parsable string.\n *\n * @param toParse The string to parse.\n * @return A time (in seconds) as an integer.\n */\n public static int getTime(String toParse) {\n int toRet;\n if (toParse.contains(\"m\")) {\n String toParseSub = toParse.substring(0, toParse.indexOf(\"m\"));\n try {\n toRet = Integer.parseInt(toParseSub) * 60;\n if (toParse.contains(\"s\")) {\n toParseSub = toParse.substring(toParse.indexOf(\"m\") + 1, toParse.indexOf(\"s\"));\n toRet += Integer.parseInt(toParseSub);\n }\n } catch (Exception e) {\n toRet = -1;\n }\n\n } else {\n if (toParse.contains(\"s\")) {\n toParse = toParse.substring(0, toParse.indexOf('s'));\n }\n try {\n toRet = Integer.parseInt(toParse);\n } catch (Exception e) {\n toRet = -1;\n }\n }\n return toRet;\n }\n\n /**\n * Adds a command to the command map.\n * <p>\n * To do this in chat, simply type !addcommand command message\n * More examples at https://bit.ly/1366RwM\n *\n * @param s The string from the chat.\n * @return true if added, false if fail\n */\n public static Response addCommands(String s) {\n Response toReturn = new Response();\n String[] split = s.split(\" \");\n if (GUIMain.commandSet != null) {\n try {\n String name = split[1];//name of the command, [0] is \"addcommand\"\n if (name.startsWith(\"!\")) name = name.substring(1);\n if (getCommand(name) != null) {\n toReturn.setResponseText(\"Failed to add command, !\" + name + \" already exists!\");\n return toReturn;\n }\n ArrayList<String> arguments = new ArrayList<>();\n if (s.contains(\" | \")) {//command with arguments\n StringTokenizer st = new StringTokenizer(s.substring(0, s.indexOf(\" | \")), \" \");\n while (st.hasMoreTokens()) {\n String work = st.nextToken();\n if (work.startsWith(\"%\") && work.endsWith(\"%\")) {\n arguments.add(work);\n }\n }\n }\n int bingo;\n if (!arguments.isEmpty()) {\n bingo = s.indexOf(\" | \") + 3;//message comes after the pipe separator\n } else {\n int bingoIndex = s.indexOf(\" \", s.indexOf(\" \") + 1);\n if (bingoIndex == -1) {\n toReturn.setResponseText(\"Failed to add command; there is no command content!\");\n return toReturn;\n }\n bingo = bingoIndex + 1;//after second space is the message without arguments\n }\n String[] message = s.substring(bingo).split(\"]\");\n Command c = new Command(name, message);\n if (!arguments.isEmpty()) c.addArguments(arguments.toArray(new String[arguments.size()]));\n if (GUIMain.commandSet.add(c)) {\n toReturn.wasSuccessful();\n toReturn.setResponseText(\"Successfully added command \\\"!\" + name + \"\\\"\");\n }\n } catch (Exception e) {\n toReturn.setResponseText(\"Failed to add command due to Exception: \" + e.getMessage());\n }\n }\n return toReturn;\n }\n\n /**\n * Removes a command from the command map.\n *\n * @param key The !command trigger, or key.\n * @return true if removed, else false\n */\n public static Response removeCommands(String key) {\n Response toReturn = new Response();\n if (GUIMain.commandSet != null && key != null) {\n Command c = getCommand(key);\n if (c != null) {\n if (GUIMain.commandSet.remove(c)) {\n toReturn.wasSuccessful();\n toReturn.setResponseText(\"Successfully removed command \\\"\" + key + \"\\\"\");\n }\n } else {\n toReturn.setResponseText(\"Failed to remove command, \" + key + \" does not exist!\");\n }\n }\n return toReturn;\n }\n\n /**\n * Tests to see if the tab of the given index is selected.\n *\n * @param tabIndex The index of the chat pane.\n * @return True if the t, else false.\n */\n public static boolean isTabSelected(int tabIndex) {\n return !GUIMain.chatPanes.isEmpty() && GUIMain.channelPane.getSelectedIndex() == tabIndex;\n }\n\n /**\n * Checks to see if a chat pane tab of a given name is visible.\n *\n * @param name The name of the chat pane.\n * @return True if the tab is visible in the TabbedPane, else false.\n */\n public static boolean isTabVisible(String name) {\n if (!GUIMain.chatPanes.isEmpty()) {\n Set<String> keys = GUIMain.chatPanes.keySet();\n for (String s : keys) {\n ChatPane cp = GUIMain.getChatPane(s);\n if (cp.getChannel().equalsIgnoreCase(name)) {\n return cp.isTabVisible();\n }\n }\n }\n return false;\n }\n\n /**\n * Gets a chat pane of the given index.\n *\n * @param index The index of the tab.\n * @return The chat pane if it exists on the index, or null.\n */\n public static ChatPane getChatPane(int index) {\n if (GUIMain.chatPanes != null && !GUIMain.chatPanes.isEmpty()) {\n Set<String> keys = GUIMain.chatPanes.keySet();\n for (String s : keys) {\n ChatPane cp = GUIMain.getChatPane(s);\n if (cp.isTabVisible() && cp.getIndex() == index) return cp;\n }\n }\n return null;\n }\n\n /**\n * Gets the combined chat pane of the given index.\n *\n * @param index The index of the tab.\n * @return The combined chat pane if it exists, or null.\n */\n public static CombinedChatPane getCombinedChatPane(int index) {\n if (!GUIMain.combinedChatPanes.isEmpty()) {\n for (CombinedChatPane cp : GUIMain.combinedChatPanes) {\n if (cp.getIndex() == index) return cp;\n }\n }\n return null;\n }\n\n /**\n * Get the Command from the given !<string> trigger.\n *\n * @param key The !command trigger, or key.\n * @return The Command that the key relates to, or null if there is no command.\n */\n public static Command getCommand(String key) {\n if (GUIMain.commandSet != null && key != null) {\n for (Command c1 : GUIMain.commandSet) {\n if (key.equals(c1.getTrigger())) {\n return c1;\n }\n }\n }\n return null;\n }\n\n /**\n * Gets the console command if the user met the trigger and permission of it.\n *\n * @param key The name of the command.\n * @param channel The channel the user is in.\n * @return The console command, or null if the user didn't meet the requirements.\n */\n public static ConsoleCommand getConsoleCommand(String key, String channel, User u) {\n String master = Settings.accountManager.getUserAccount().getName();\n if (!channel.contains(master)) return null;\n if (u != null) {\n for (ConsoleCommand c : GUIMain.conCommands) {\n if (key.equalsIgnoreCase(c.getTrigger())) {\n int conPerm = c.getClassPermission();\n if (conPerm == -1) {\n List<String> certainPerms = c.getCertainPermissions();\n if (certainPerms.contains(u.getNick()))\n return c;\n } else {//int class permission\n if (Permissions.hasAtLeast(Permissions.getUserPermissions(u, channel), conPerm)) {\n return c;\n }\n }\n }\n }\n }\n return null;\n }\n\n /**\n * Checks to see if a given channel is the main Botnak user's channel.\n *\n * @param channel The channel to check.\n * @return true if indeed the channel, otherwise false.\n */\n public static boolean isMainChannel(String channel) {\n return Settings.accountManager.getUserAccount() != null &&\n (channel.replaceAll(\"#\", \"\").equalsIgnoreCase(Settings.accountManager.getUserAccount().getName()));\n }\n\n /**\n * Gets the String value of the integer permission.\n *\n * @param permission The permission to get the String representation of.\n * @return The String representation of the permission.\n */\n public static String getPermissionString(int permission) {\n return (permission > 0 ? (permission > 1 ? (permission > 2 ? (permission > 3 ?\n \"Only the Broadcaster\" :\n \"Only Mods and the Broadcaster\") :\n \"Donators, Mods, and the Broadcaster\") :\n \"Subscribers, Donators, Mods, and the Broadcaster\") :\n \"Everyone\");\n }\n\n /**\n * Sets the permission of a console command based on the input received.\n * <p>\n * Ex:\n * !setpermission mod 0\n * >Everybody can now mod each other\n * <p>\n * !setpermission mod gocnak,gmansoliver\n * >Only Gocnak and Gmansoliver can mod people\n * <p>\n * etc.\n * <p>\n * Note: This WILL reset the permissions and /then/ set it to specified.\n * If you wish to add another name, you will have to retype the ones already\n * allowed!\n *\n * @param mess The entire message to dissect.\n */\n public static Response setCommandPermission(String mess) {\n Response toReturn = new Response();\n if (mess == null) {\n toReturn.setResponseText(\"Failed to set command permission, message is null!\");\n return toReturn;\n }\n String[] split = mess.split(\" \");\n String trigger = split[1];\n for (ConsoleCommand c : GUIMain.conCommands) {\n if (trigger.equalsIgnoreCase(c.getTrigger())) {\n int classPerm;\n String[] certainPerm = null;\n try {\n classPerm = Integer.parseInt(split[2]);\n } catch (Exception e) {\n classPerm = -1;\n certainPerm = split[2].split(\",\");\n }\n c.setCertainPermission(certainPerm);\n c.setClassPermission(classPerm);\n toReturn.wasSuccessful();\n toReturn.setResponseText(\"Successfully set the command permission for \" + trigger + \" !\");\n break;\n }\n }\n return toReturn;\n }\n\n /**\n * Gets the SimpleAttributeSet with the correct color for the message.\n * Cycles through all of the keywords, so the first keyword it matches is the color.\n *\n * @param message The message to dissect.\n * @return The set with the correct color.\n */\n public static SimpleAttributeSet getSetForKeyword(String message) {\n SimpleAttributeSet setToRet = new SimpleAttributeSet(GUIMain.norm);\n Set<String> keys = GUIMain.keywordMap.keySet();\n //case doesnt matter\n keys.stream().filter(\n s -> message.toLowerCase().contains(s.toLowerCase())).forEach(\n s -> StyleConstants.setForeground(setToRet, GUIMain.keywordMap.get(s)));\n return setToRet;\n }\n\n /**\n * Checks to see if the message contains a keyword.\n *\n * @param message The message to check.\n * @return True if the message contains a keyword, else false.\n */\n public static boolean mentionsKeyword(String message) {\n Set<String> keys = GUIMain.keywordMap.keySet();\n for (String s : keys) {\n if (message.toLowerCase().contains(s.toLowerCase())) {//case doesnt matter\n return true;\n }\n }\n return false;\n }\n\n /**\n * Handles the adding/removing of a keyword and the colors.\n *\n * @param mess The entire message to dissect.\n */\n public static Response handleKeyword(String mess) {\n Response toReturn = new Response();\n if (mess == null || \"\".equals(mess)) {\n toReturn.setResponseText(\"Failed to handle keyword, the message is null!\");\n return toReturn;\n }\n String[] split = mess.split(\" \");\n if (split.length > 1) {\n String trigger = split[0];\n String word = split[1];\n if (trigger.equalsIgnoreCase(\"addkeyword\")) {\n String color = mess.substring(mess.indexOf(\" \", mess.indexOf(\" \") + 1) + 1);\n Color c = getColor(color, null);\n if (!c.equals(Color.white)) {\n GUIMain.keywordMap.put(word, c);\n toReturn.wasSuccessful();\n toReturn.setResponseText(\"Successfully added keyword \\\"\" + word + \"\\\" !\");\n } else {\n toReturn.setResponseText(\"Failed to add keyword, the color cannot be white!\");\n }\n } else if (trigger.equalsIgnoreCase(\"removekeyword\")) {\n Set<String> keys = GUIMain.keywordMap.keySet();\n for (String s : keys) {\n if (s.equalsIgnoreCase(word)) {\n GUIMain.keywordMap.remove(s);\n toReturn.wasSuccessful();\n toReturn.setResponseText(\"Successfully removed keyword \\\"\" + word + \"\\\" !\");\n return toReturn;\n }\n }\n toReturn.setResponseText(\"Failed to remove keyword, \\\"\" + word + \"\\\" does not exist!\");\n }\n } else {\n toReturn.setResponseText(\"Failed to handle keyword, the keyword is null!\");\n }\n return toReturn;\n }\n\n /**\n * Generates a pseudo-random color that works for Botnak.\n *\n * @return The randomly generated color.\n */\n public static Color getRandomColor() {\n return new Color(random(100, 256), random(100, 256), random(100, 256));\n }\n\n /**\n * Gets the color from the given string. Supports hexadecimal, RGB, and color\n * name.\n *\n * @param message The message to dissect.\n * @param fallback The fallback color to set to if the parsing failed. Defaults to white if null.\n * @return The parsed color from the message, or the fallback color if parsing failed.\n */\n public static Color getColor(String message, Color fallback) {\n Color toRet = (fallback == null ? new Color(255, 255, 255) : fallback);\n String[] split = message.split(\" \");\n if (split.length > 1) { //R G B\n int R;\n int G;\n int B;\n try {\n R = Integer.parseInt(split[0]);\n } catch (NumberFormatException e) {\n R = 0;\n }\n try {\n G = Integer.parseInt(split[1]);\n } catch (NumberFormatException e) {\n G = 0;\n }\n try {\n B = Integer.parseInt(split[2]);\n } catch (NumberFormatException e) {\n B = 0;\n }\n if (checkInts(R, G, B)) toRet = new Color(R, G, B);\n } else {\n try {\n //this is for hexadecimal\n Color toCheck = Color.decode(split[0]);\n if (checkColor(toCheck)) toRet = toCheck;\n } catch (Exception e) {\n //didn't parse it right, so it may be a name of a color\n for (NamedColor nc : Constants.namedColors) {\n if (split[0].equalsIgnoreCase(nc.getName())) {\n toRet = nc.getColor();\n break;\n }\n }\n if (split[0].equalsIgnoreCase(\"random\")) {\n toRet = getRandomColor();\n }\n }\n }\n return toRet;\n }\n\n\n /**\n * Sets a color to the user based on either a R G B value in their message\n * or a standard color from the Color class.\n *\n * @param user User to change the color for.\n * @param mess Their message.\n */\n public static Response handleColor(final User user, String mess, Color old)\n {\n Response toReturn = new Response();\n if (mess != null)\n {\n //mess = \"!setcol r g b\" or \"!setcol #cd4fd5\"\n //so let's send just the second part.\n Color newColor = getColor(mess.substring(mess.indexOf(\" \") + 1), old);\n if (!newColor.equals(old)) {\n GUIMain.userColMap.put(user.getUserID(), newColor);\n toReturn.setResponseText(\"Successfully set color for user \" + user.getDisplayName() + \" !\");\n toReturn.wasSuccessful();\n } else {\n toReturn.setResponseText(\"Failed to update color, it may be too dark!\");\n }\n } else {\n toReturn.setResponseText(\"Failed to update user color, user or message is null!\");\n }\n return toReturn;\n }\n\n /**\n * Gets a color from the given user, whether it be\n * 1. From the manually-set User Color map.\n * 2. From their Twitch color set on the website.\n * 3. The generated color from their name's hash code.\n *\n * @param u The user to get the color of.\n * @return The color of the user.\n */\n public static Color getColorFromUser(User u) {\n Color c;\n String name = u.getNick();\n if (u.getColor() != null) {\n if (GUIMain.userColMap.containsKey(name)) {\n c = GUIMain.userColMap.get(name);\n } else {\n c = u.getColor();\n if (!Utils.checkColor(c)) {\n c = Utils.getColorFromHashcode(name.hashCode());\n }\n }\n } else {//temporarily assign their color as randomly generated\n c = Utils.getColorFromHashcode(name.hashCode());\n }\n return c;\n }\n\n /**\n * Checks a color to see if it will show up in botnak.\n *\n * @param c The color to check.\n * @return True if the color is not null, and shows up in botnak.\n */\n public static boolean checkColor(Color c) {\n return c != null && checkInts(c.getRed(), c.getGreen(), c.getBlue());\n }\n\n /**\n * Checks if the red, green, and blue show up in Botnak,\n * using the standard Luminance formula.\n *\n * @param r Red value\n * @param g Green value\n * @param b Blue value\n * @return true if the Integers meet the specification.\n */\n public static boolean checkInts(int r, int g, int b) {\n double luma = (0.3 * (double) r) + (0.6 * (double) g) + (0.1 * (double) b);\n return luma > (double) 35;\n }\n\n /**\n * Checks to see if the regex is valid.\n *\n * @param toCheck The regex to check.\n * @return <tt>true</tt> if valid regex.\n */\n public static boolean checkRegex(String toCheck) {\n try {\n Pattern.compile(toCheck);\n return true;\n } catch (Exception e) {\n GUIMain.log(e);\n return false;\n }\n }\n\n /**\n * Checks the file name to see if Windows will store it properly.\n *\n * @param toCheck The name to check.\n * @return true if the name is invalid.\n */\n public static boolean checkName(String toCheck) {\n Matcher m = Constants.PATTERN_FILE_NAME_EXCLUDE.matcher(toCheck);\n return m.find();\n }\n\n /**\n * Parses a buffered reader and adds what is read to the provided StringBuilder.\n *\n * @param toRead The stream to read.\n * @param builder The builder to add to.\n */\n public static void parseBufferedReader(BufferedReader toRead, StringBuilder builder, boolean includeNewLine) {\n try (BufferedReader toReadr = toRead) {\n String line;\n while ((line = toReadr.readLine()) != null) {\n builder.append(line);\n if (includeNewLine) builder.append(\"\\n\");\n }\n } catch (Exception e) {\n GUIMain.log(\"Failed to read buffered reader due to exception: \");\n GUIMain.log(e);\n }\n }\n\n /**\n * One to many methods required creating a BufferedReader just to read one line from it.\n * This method does that and saves the effort of writing the code elsewhere.\n *\n * @param input The InputStream to read from.\n * @return The string read from the input.\n */\n public static String createAndParseBufferedReader(InputStream input) {\n return createAndParseBufferedReader(input, false);\n }\n\n public static String createAndParseBufferedReader(InputStream input, boolean includeNewLines)\n {\n String toReturn = \"\";\n try (InputStreamReader inputStreamReader = new InputStreamReader(input, Charset.forName(\"UTF-8\"));\n BufferedReader br = new BufferedReader(inputStreamReader)) {\n StringBuilder sb = new StringBuilder();\n parseBufferedReader(br, sb, includeNewLines);\n toReturn = sb.toString();\n } catch (Exception e) {\n GUIMain.log(\"Could not parse buffered reader due to exception: \");\n GUIMain.log(e);\n }\n return toReturn;\n }\n\n /**\n * Override for the #createAndParseBufferedReader(InputStream) method for just simple URLs.\n * @param URL The URL to try to open.\n * @return The parsed buffered reader if successful, otherwise an empty string.\n */\n public static String createAndParseBufferedReader(String URL)\n {\n try\n {\n return createAndParseBufferedReader(new URL(URL).openStream());\n } catch (Exception e)\n {\n GUIMain.log(\"Could not parse buffered reader due to exception: \");\n GUIMain.log(e);\n }\n return \"\";\n }\n\n /**\n * Opens a web page in the default web browser on the system.\n *\n * @param URL The URL to open.\n */\n public static void openWebPage(String URL) {\n try {\n Desktop desktop = Desktop.getDesktop();\n URI uri = new URL(URL).toURI();\n desktop.browse(uri);\n } catch (Exception ev) {\n GUIMain.log(\"Failed openWebPage due to exception: \");\n GUIMain.log(ev);\n }\n }\n\n /**\n * Caps a number between two given numbers.\n *\n * @param numLesser The lower-bound (inclusive) number to compare against.\n * @param numHigher The higher-bound (inclusive) number to compare against.\n * @param toCompare The number to check and perhaps cap.\n * @param <E> Generics, used for making one method for all number types.\n * @return If the number is within the two bounds, the number is returned.\n * Otherwise, return the supplied number bound that the number is closer to.\n */\n public static <E extends Number> E capNumber(E numLesser, E numHigher, E toCompare) {\n E toReturn = toCompare;\n if (toCompare.floatValue() > numHigher.floatValue()) toReturn = numHigher;//floats are the most precise here\n else if (toCompare.floatValue() < numLesser.floatValue()) toReturn = numLesser;\n return toReturn;\n }\n\n /**\n * Parses Twitch's tags for an IRC message and spits them out into a HashMap.\n *\n * @param tagLine The tags line to parse\n * @param map The output map to put the tags into\n */\n public static void parseTagsToMap(String tagLine, Map<String, String> map)\n {\n if (tagLine != null)\n {\n String[] parts = tagLine.split(\";\");\n for (String part : parts)\n {\n String[] objectPair = part.split(\"=\");\n //Don't add this key/pair value if there is no value.\n if (objectPair.length <= 1) continue;\n map.put(objectPair[0], objectPair[1].replaceAll(\"\\\\\\\\s\", \" \"));\n }\n }\n }\n\n public static void populateComboBox(JComboBox<String> channelsBox)\n {\n channelsBox.removeAllItems();\n if (GUIMain.bot == null || GUIMain.bot.getBot() == null) return;\n\n List<String> channels = GUIMain.bot.getBot().getChannels();\n\n for (String s : channels)\n channelsBox.addItem(s.replaceAll(\"#\", \"\"));\n\n channelsBox.setSelectedItem(GUIMain.getCurrentPane().getChannel());\n }\n}", "public class Settings {\n\n //accounts\n public static AccountManager accountManager = null;\n public static ChannelManager channelManager = null;\n\n\n //donations\n public static DonationManager donationManager = null;\n public static boolean loadedDonationSounds = false;\n public static SubscriberManager subscriberManager = null;\n public static boolean loadedSubSounds = false;\n\n\n //directories\n public static File defaultDir = new File(FileSystemView.getFileSystemView().getDefaultDirectory().getAbsolutePath()\n + File.separator + \"Botnak\");\n public static File tmpDir = new File(defaultDir + File.separator + \"_temp\");\n public static File faceDir = new File(defaultDir + File.separator + \"Faces\");\n public static File nameFaceDir = new File(defaultDir + File.separator + \"NameFaces\");\n public static File twitchFaceDir = new File(defaultDir + File.separator + \"TwitchFaces\");\n public static File frankerFaceZDir = new File(defaultDir + File.separator + \"FrankerFaceZ\");\n public static File subIconsDir = new File(defaultDir + File.separator + \"SubIcons\");\n public static File subSoundDir = new File(defaultDir + File.separator + \"SubSounds\");\n public static File donationSoundDir = new File(defaultDir + File.separator + \"DonationSounds\");\n public static File logDir = new File(defaultDir + File.separator + \"Logs\");\n //files\n public static File accountsFile = new File(defaultDir + File.separator + \"acc.ini\");\n public static File tabsFile = new File(defaultDir + File.separator + \"tabs.txt\");\n public static File soundsFile = new File(defaultDir + File.separator + \"sounds.txt\");\n public static File faceFile = new File(defaultDir + File.separator + \"faces.txt\");\n public static File twitchFaceFile = new File(defaultDir + File.separator + \"twitchfaces.txt\");\n public static File userColFile = new File(defaultDir + File.separator + \"usercols.txt\");\n public static File commandsFile = new File(defaultDir + File.separator + \"commands.txt\");\n public static File ccommandsFile = new File(defaultDir + File.separator + \"chatcom.txt\");\n public static File defaultsFile = new File(defaultDir + File.separator + \"defaults.ini\");\n public static File lafFile = new File(defaultDir + File.separator + \"laf.txt\");\n public static File windowFile = new File(defaultDir + File.separator + \"window.txt\");\n public static File keywordsFile = new File(defaultDir + File.separator + \"keywords.txt\");\n public static File donorsFile = new File(defaultDir + File.separator + \"donors.txt\");\n public static File donationsFile = new File(defaultDir + File.separator + \"donations.txt\");\n public static File subsFile = new File(defaultDir + File.separator + \"subs.txt\");\n\n //appearance\n public static String lookAndFeel = \"lib.jtattoo.com.jtattoo.plaf.hifi.HiFiLookAndFeel\";\n //Graphite = \"lib.jtattoo.com.jtattoo.plaf.graphite.GraphiteLookAndFeel\"\n\n public static String date;\n\n\n //System Tray\n public static Setting<Boolean> stShowMentions = new Setting<>(\"ST_DisplayDonations\", false, Boolean.class);\n public static Setting<Boolean> stShowDonations = new Setting<>(\"ST_DisplayMentions\", false, Boolean.class);\n public static Setting<Boolean> stShowActivity = new Setting<>(\"ST_DisplayActivity\", false, Boolean.class);\n public static Setting<Boolean> stMuted = new Setting<>(\"\", false, Boolean.class);\n public static Setting<Boolean> stUseSystemTray = new Setting<>(\"ST_UseSystemTray\", false, Boolean.class);\n public static Setting<Boolean> stShowSubscribers = new Setting<>(\"ST_DisplaySubscribers\", false, Boolean.class);\n public static Setting<Boolean> stShowNewFollowers = new Setting<>(\"ST_DisplayFollowers\", false, Boolean.class);\n public static Setting<Boolean> stShowReconnecting = new Setting<>(\"ST_DisplayReconnects\", false, Boolean.class);\n\n //Bot Reply\n public static Setting<Boolean> botAnnounceSubscribers = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n public static Setting<Boolean> botShowYTVideoDetails = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n public static Setting<Boolean> botShowTwitchVODDetails = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n public static Setting<Boolean> botShowPreviousSubSound = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n public static Setting<Boolean> botShowPreviousDonSound = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n public static Setting<Boolean> botUnshortenURLs = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n\n public static Setting<Boolean> ffzFacesEnable = new Setting<>(\"\", true, Boolean.class);\n public static Setting<Boolean> ffzFacesUseAll = new Setting<>(\"\", false, Boolean.class);\n public static Setting<Boolean> actuallyClearChat = new Setting<>(\"\", false, Boolean.class);\n public static Setting<Boolean> showDonorIcons = new Setting<>(\"\", true, Boolean.class);\n public static Setting<Boolean> showTabPulses = new Setting<>(\"\", true, Boolean.class);\n public static Setting<Boolean> trackDonations = new Setting<>(\"TrackDonations\", false, Boolean.class);\n public static Setting<Boolean> trackFollowers = new Setting<>(\"TrackFollowers\", false, Boolean.class);\n\n public static Setting<Boolean> cleanupChat = new Setting<>(\"ClearChat\", true, Boolean.class);\n public static Setting<Boolean> logChat = new Setting<>(\"LogChat\", false, Boolean.class);\n\n\n //Icons TODO are these needed anymore?\n public static Setting<Boolean> useMod = new Setting<>(\"UseMod\", false, Boolean.class);\n public static Setting<Boolean> useAdmin = new Setting<>(\"UseAdmin\", false, Boolean.class);\n public static Setting<Boolean> useStaff = new Setting<>(\"UseStaff\", false, Boolean.class);\n public static Setting<Boolean> useBroad = new Setting<>(\"UseBroad\", false, Boolean.class);\n public static Setting<URL> modIcon = new Setting<>(\"CustomMod\", Settings.class.getResource(\"/image/mod.png\"), URL.class);\n public static Setting<URL> broadIcon = new Setting<>(\"CustomBroad\", Settings.class.getResource(\"/image/broad.png\"), URL.class);\n public static Setting<URL> adminIcon = new Setting<>(\"CustomAdmin\", Settings.class.getResource(\"/image/mod.png\"), URL.class);\n public static Setting<URL> staffIcon = new Setting<>(\"CustomStaff\", Settings.class.getResource(\"/image/mod.png\"), URL.class);\n public static Setting<URL> turboIcon = new Setting<>(\"\", Settings.class.getResource(\"/image/turbo.png\"), URL.class);\n\n public static Setting<Boolean> autoReconnectAccounts = new Setting<>(\"\", true, Boolean.class);\n\n\n public static Setting<Float> soundVolumeGain = new Setting<>(\"\"/*TODO*/, 100f, Float.class);\n public static Setting<Integer> faceMaxHeight = new Setting<>(\"FaceMaxHeight\", 20, Integer.class);\n public static Setting<Integer> chatMax = new Setting<>(\"MaxChat\", 100, Integer.class);\n public static Setting<Integer> botReplyType = new Setting<>(\"BotReplyType\", 0, Integer.class);\n //0 = none, 1 = botnak user only, 2 = everyone\n\n public static Setting<String> lastFMAccount = new Setting<>(\"LastFMAccount\", \"\", String.class);\n public static Setting<String> defaultSoundDir = new Setting<>(\"SoundDir\", \"\", String.class);\n public static Setting<String> defaultFaceDir = new Setting<>(\"FaceDir\", \"\", String.class);\n\n public static Setting<String> donationClientID = new Setting<>(\"DCID\", \"\", String.class);\n public static Setting<String> donationAuthCode = new Setting<>(\"DCOAUTH\", \"\", String.class);\n public static Setting<Boolean> scannedInitialDonations = new Setting<>(\"RanInitDonations\", true, Boolean.class);\n public static Setting<Boolean> scannedInitialSubscribers = new Setting<>(\"RanInitSub\", false, Boolean.class);\n public static Setting<Integer> soundEngineDelay = new Setting<>(\"SoundEngineDelay\", 10000, Integer.class);\n public static Setting<Integer> soundEnginePermission = new Setting<>(\"SoundEnginePerm\", 1, Integer.class);\n\n public static Setting<Boolean> alwaysOnTop = new Setting<>(\"AlwaysOnTop\", false, Boolean.class);\n\n public static Setting<Font> font = new Setting<>(\"Font\", new Font(\"Calibri\", Font.PLAIN, 18), Font.class);\n\n public static Setting<Double> donorCutoff = new Setting<>(\"DonorCutoff\", 2.50, Double.class);\n public static Setting<Integer> cheerDonorCutoff = new Setting<>(\"CheerDonorCutoff\", 250, Integer.class);\n\n private static ArrayList<Setting> settings;\n\n public static Window WINDOW = new Window();\n public static LookAndFeel LAF = new LookAndFeel();\n public static TabState TAB_STATE = new TabState();\n public static Subscribers SUBSCRIBERS = new Subscribers();\n public static Donations DONATIONS = new Donations();\n public static Donors DONORS = new Donors();\n public static Sounds SOUNDS = new Sounds();\n public static Commands COMMANDS = new Commands();\n public static UserColors USER_COLORS = new UserColors();\n public static TwitchFaces TWITCH_FACES = new TwitchFaces();\n public static Faces FACES = new Faces();\n public static Keywords KEYWORDS = new Keywords();\n\n public static void init() {\n long time = System.currentTimeMillis();\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd-MM-yy\");\n date = sdf.format(new Date(time));\n defaultDir.mkdirs();\n // This clears the temp directory\n if (tmpDir.exists())\n ShutdownHook.deleteTempOnExit();\n tmpDir.mkdirs();\n faceDir.mkdirs();\n nameFaceDir.mkdirs();\n twitchFaceDir.mkdirs();\n subIconsDir.mkdirs();\n subSoundDir.mkdirs();\n donationSoundDir.mkdirs();\n //collection for bulk saving/loading\n //(otherwise it would have been a bunch of hardcode...)\n settings = new ArrayList<>();\n try {\n Field[] fields = Settings.class.getDeclaredFields();\n for (Field f : fields) {\n if (f.getType().getName().equals(Setting.class.getName())) {\n settings.add((Setting) f.get(null));\n }\n }\n } catch (Exception e) {\n GUIMain.log(e);\n }\n /**\n * \"After the fact\":\n * These change listeners are used to update the main GUI upon the setting change.\n */\n soundEngineDelay.addChangeListener(GUIMain.instance::updateSoundDelay);\n soundEnginePermission.addChangeListener(GUIMain.instance::updateSoundPermission);\n botReplyType.addChangeListener(GUIMain.instance::updateBotReplyPerm);\n font.addChangeListener(f -> {\n StyleConstants.setFontFamily(GUIMain.norm, f.getFamily());\n StyleConstants.setFontSize(GUIMain.norm, f.getSize());\n StyleConstants.setBold(GUIMain.norm, f.isBold());\n StyleConstants.setItalic(GUIMain.norm, f.isItalic());\n });\n alwaysOnTop.addChangeListener(GUIMain.instance::updateAlwaysOnTopStatus);\n }\n\n /**\n * This void loads everything Botnak will use, and sets the appropriate settings.\n */\n public static void load() {\n if (Utils.areFilesGood(WINDOW.getFile().getAbsolutePath())) WINDOW.load();\n accountManager = new AccountManager();\n channelManager = new ChannelManager();\n accountManager.start();\n donationManager = new DonationManager();\n subscriberManager = new SubscriberManager();\n if (Utils.areFilesGood(accountsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading accounts...\");\n loadPropData(0);\n }\n if (Utils.areFilesGood(defaultsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading defaults...\");\n loadPropData(1);\n }\n if (Utils.areFilesGood(tabsFile.getAbsolutePath()) && accountManager.getUserAccount() != null) {\n GUIMain.log(\"Loading tabs...\");\n TAB_STATE.load();\n GUIMain.channelPane.setSelectedIndex(TabState.startIndex);\n GUIMain.log(\"Loaded tabs!\");\n }\n if (Utils.areFilesGood(soundsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading sounds...\");\n SOUNDS.load();\n GUIMain.log(\"Loaded sounds!\");\n }\n if (subSoundDir.exists())\n {\n String[] dirList = subSoundDir.list();\n if (dirList != null && dirList.length > 0)\n {\n GUIMain.log(\"Loading sub sounds...\");\n doLoadSubSounds();\n }\n }\n if (donationSoundDir.exists())\n {\n String[] dirList = donationSoundDir.list();\n if (dirList != null && dirList.length > 0)\n {\n GUIMain.log(\"Loading donation sounds...\");\n doLoadDonationSounds();\n }\n }\n if (Utils.areFilesGood(userColFile.getAbsolutePath())) {\n GUIMain.log(\"Loading user colors...\");\n USER_COLORS.load();\n GUIMain.log(\"Loaded user colors!\");\n }\n if (Utils.areFilesGood(donorsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading donors...\");\n DONORS.load();\n GUIMain.log(\"Loaded donors!\");\n }\n if (Utils.areFilesGood(donationsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading donations...\");\n DONATIONS.load();//these are stored locally\n if (Donations.mostRecent != null) {\n donationManager.setLastDonation(Donations.mostRecent);\n GUIMain.log(String.format(\"Most recent donation: %s for %s\", Donations.mostRecent.getFromWho(),\n DonationManager.getCurrencyFormat().format(Donations.mostRecent.getAmount())));\n }\n if (!Donations.donations.isEmpty()) {\n donationManager.fillDonations(Donations.donations);\n Donations.donations.clear();\n Donations.donations = null;\n Donations.mostRecent = null;\n GUIMain.log(\"Loaded donations!\");\n }\n }\n //checks online for offline donations and adds them\n if (donationManager.canCheck() && scannedInitialDonations.getValue()) {\n ThreadEngine.submit(() ->\n {\n donationManager.checkDonations(false);\n donationManager.ranFirstCheck = true;\n });\n }\n if (!scannedInitialDonations.getValue()) {\n ThreadEngine.submit(() ->\n {\n donationManager.scanInitialDonations(0);\n scannedInitialDonations.setValue(true);\n });\n }\n if (accountManager.getUserAccount() != null && accountManager.getUserAccount().getOAuth().canReadSubscribers())\n {\n if (!scannedInitialSubscribers.getValue() && accountManager.getUserAccount() != null) {\n subscriberManager.scanInitialSubscribers(accountManager.getUserAccount().getName(),\n accountManager.getUserAccount().getOAuth(), 0, new HashSet<>());\n }\n }\n if (Utils.areFilesGood(subsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading subscribers...\");\n SUBSCRIBERS.load();\n if (Subscribers.mostRecent != null) {\n subscriberManager.setLastSubscriber(Subscribers.mostRecent);\n //GUIMain.log(\"Most recent subscriber: \" + Subscribers.mostRecent.getName());\n }\n if (!Subscribers.subscribers.isEmpty()) subscriberManager.fillSubscribers(Subscribers.subscribers);\n Subscribers.subscribers.clear();\n Subscribers.subscribers = null;\n Subscribers.mostRecent = null;\n GUIMain.log(\"Loaded subscribers!\");\n }\n if (Utils.areFilesGood(commandsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading text commands...\");\n COMMANDS.load();\n GUIMain.log(\"Loaded text commands!\");\n }\n if (subIconsDir.exists()) {\n File[] subIcons = subIconsDir.listFiles();\n if (subIcons != null && subIcons.length > 0) {\n GUIMain.log(\"Loading subscriber icons...\");\n loadSubIcons(subIcons);\n }\n }\n File[] nameFaces = nameFaceDir.listFiles();\n if (nameFaces != null && nameFaces.length > 0) {\n GUIMain.log(\"Loading name faces...\");\n loadNameFaces(nameFaces);\n }\n if (ffzFacesEnable.getValue()) {\n frankerFaceZDir.mkdirs();\n File[] files = frankerFaceZDir.listFiles();\n if (files != null && files.length > 0) {\n GUIMain.log(\"Loading FrankerFaceZ faces...\");\n loadFFZFaces(files);\n }\n }\n if (keywordsFile.exists()) {\n GUIMain.log(\"Loading keywords...\");\n KEYWORDS.load();\n } else {\n if (accountManager.getUserAccount() != null) {\n GUIMain.keywordMap.put(accountManager.getUserAccount().getName(), Color.orange);\n }\n }\n GUIMain.log(\"Loading console commands...\");\n loadConsoleCommands();//has to be out of the check for files for first time boot\n if (Utils.areFilesGood(faceFile.getAbsolutePath())) {\n GUIMain.log(\"Loading custom faces...\");\n FACES.load();\n FaceManager.doneWithFaces = true;\n GUIMain.log(\"Loaded custom faces!\");\n }\n GUIMain.log(\"Loading default Twitch faces...\");\n if (Utils.areFilesGood(twitchFaceFile.getAbsolutePath())) {\n TWITCH_FACES.load();\n }\n FaceManager.loadDefaultFaces();\n }\n\n /**\n * This handles saving all the settings that need saved.\n */\n public static void save() {\n LAF.save();\n WINDOW.save();\n if (accountManager.getUserAccount() != null || accountManager.getBotAccount() != null) savePropData(0);\n savePropData(1);\n if (!SoundEngine.getEngine().getSoundMap().isEmpty()) SOUNDS.save();\n if (!FaceManager.faceMap.isEmpty()) FACES.save();\n if (!FaceManager.twitchFaceMap.isEmpty()) TWITCH_FACES.save();\n TAB_STATE.save();\n if (!GUIMain.userColMap.isEmpty()) USER_COLORS.save();\n if (GUIMain.loadedCommands()) COMMANDS.save();\n if (!GUIMain.keywordMap.isEmpty()) KEYWORDS.save();\n if (!donationManager.getDonors().isEmpty()) DONORS.save();\n if (!donationManager.getDonations().isEmpty()) DONATIONS.save();\n if (!subscriberManager.getSubscribers().isEmpty()) SUBSCRIBERS.save();\n saveConCommands();\n }\n\n /**\n * *********VOIDS*************\n */\n\n public static void loadPropData(int type) {\n Properties p = new Properties();\n if (type == 0) {//accounts\n try {\n p.load(new FileInputStream(accountsFile));\n String userNorm = p.getProperty(\"UserNorm\", \"\").toLowerCase();\n String userNormPass = p.getProperty(\"UserNormPass\", \"\");\n String status = p.getProperty(\"CanStatus\", \"false\");\n String commercial = p.getProperty(\"CanCommercial\", \"false\");\n if (!userNorm.equals(\"\") && !userNormPass.equals(\"\") && userNormPass.contains(\"oauth\")) {\n boolean stat = Boolean.parseBoolean(status);\n if (!stat) {\n GUIMain.instance.updateStatusOption.setEnabled(false);\n GUIMain.instance.updateStatusOption.setToolTipText(\"Enable \\\"Edit Title and Game\\\" in the Authorize GUI to use this feature.\");\n }\n boolean ad = Boolean.parseBoolean(commercial);\n if (!ad) {\n GUIMain.instance.runAdMenu.setEnabled(false);\n GUIMain.instance.runAdMenu.setToolTipText(\"Enable \\\"Play Commercials\\\" in the Authorize GUI to use this feature.\");\n }\n boolean subs = Boolean.parseBoolean(p.getProperty(\"CanParseSubscribers\", \"false\"));\n boolean followed = Boolean.parseBoolean(p.getProperty(\"CanParseFollowedStreams\", \"false\"));\n if (followed) trackFollowers.setValue(true);\n accountManager.setUserAccount(new Account(userNorm, new OAuth(userNormPass, stat, ad, subs, followed)));\n }\n String userBot = p.getProperty(\"UserBot\", \"\").toLowerCase();\n String userBotPass = p.getProperty(\"UserBotPass\", \"\");\n if (!userBot.equals(\"\") && !userBotPass.equals(\"\") && userBotPass.contains(\"oauth\")) {\n accountManager.setBotAccount(new Account(userBot, new OAuth(userBotPass, false, false, false, false)));\n }\n if (accountManager.getUserAccount() != null) {\n accountManager.addTask(new Task(null, Task.Type.CREATE_VIEWER_ACCOUNT, null));\n }\n if (accountManager.getBotAccount() != null) {\n accountManager.addTask(new Task(null, Task.Type.CREATE_BOT_ACCOUNT, null));\n }\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n if (type == 1) {//defaults\n try {\n p.load(new FileInputStream(defaultsFile));\n settings.forEach(s -> s.load(p));\n if (logChat.getValue()) logDir.mkdirs();\n GUIMain.log(\"Loaded defaults!\");\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n }\n\n public static void savePropData(int type) {\n Properties p = new Properties();\n File writerFile = null;\n String detail = \"\";\n switch (type) {\n case 0:\n Account user = accountManager.getUserAccount();\n Account bot = accountManager.getBotAccount();\n if (user != null) {\n OAuth key = user.getOAuth();\n p.put(\"UserNorm\", user.getName());\n p.put(\"UserNormPass\", key.getKey());\n p.put(\"CanStatus\", String.valueOf(key.canSetTitle()));\n p.put(\"CanCommercial\", String.valueOf(key.canPlayAd()));\n p.put(\"CanParseSubscribers\", String.valueOf(key.canReadSubscribers()));\n p.put(\"CanParseFollowedStreams\", String.valueOf(key.canReadFollowed()));\n }\n if (bot != null) {\n OAuth key = bot.getOAuth();\n p.put(\"UserBot\", bot.getName());\n p.put(\"UserBotPass\", key.getKey());\n }\n writerFile = accountsFile;\n detail = \"Account Info\";\n break;\n case 1:\n settings.forEach(s -> s.save(p));\n writerFile = defaultsFile;\n detail = \"Defaults/Other Settings\";\n break;\n default:\n break;\n }\n if (writerFile != null) {\n try {\n p.store(new FileWriter(writerFile), detail);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n } else {\n GUIMain.log(\"Failed to store settings due to some unforseen exception!\");\n }\n }\n\n\n /**\n * Sounds\n */\n private static class Sounds extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\",\", 3);\n String[] split2add = split[2].split(\",\");//files\n int perm = 0;\n try {\n perm = Integer.parseInt(split[1]);\n } catch (NumberFormatException e) {\n GUIMain.log(split[0] + \" has a problem. Making it public.\");\n }\n SoundEngine.getEngine().getSoundMap().put(split[0].toLowerCase(), new Sound(perm, split2add));\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n Iterator<Map.Entry<String, Sound>> keys = SoundEngine.getEngine().getSoundMap().entrySet().iterator();\n StringBuilder sb = new StringBuilder();\n while (keys.hasNext()) {\n Map.Entry<String, Sound> entry = keys.next();\n sb.append(entry.getKey());\n sb.append(\",\");\n sb.append(entry.getValue().getPermission());\n for (String sound : entry.getValue().getSounds().data) {\n sb.append(\",\");\n sb.append(sound);\n }\n pw.println(sb.toString());\n sb.setLength(0);\n }\n }\n\n @Override\n public File getFile() {\n return soundsFile;\n }\n }\n\n\n /**\n * User Colors\n */\n public static class UserColors extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\",\");\n GUIMain.userColMap.put(Long.parseLong(split[0]), new Color(Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3])));\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n for (Map.Entry<Long, Color> entry : GUIMain.userColMap.entrySet())\n {\n Color col = entry.getValue();\n pw.println(String.format(\"%d,%d,%d,%d\", entry.getKey(), col.getRed(), col.getGreen(), col.getBlue()));\n }\n }\n\n @Override\n public File getFile() {\n return userColFile;\n }\n }\n\n /**\n * Normal faces\n */\n public static class Faces extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\",\");\n // name name/regex path\n FaceManager.faceMap.put(split[0], new Face(split[1], split[2]));\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n FaceManager.faceMap.keySet().stream().filter(s -> s != null && FaceManager.faceMap.get(s) != null).forEach(s -> {\n Face fa = FaceManager.faceMap.get(s);\n pw.println(s + \",\" + fa.getRegex() + \",\" + fa.getFilePath());\n });\n }\n\n @Override\n public File getFile() {\n return faceFile;\n }\n }\n\n /**\n * Twitch Faces\n */\n public static class TwitchFaces extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n try {\n String[] split = line.split(\",\");\n int emoteID = Integer.parseInt(split[0]);\n TwitchFace tf = new TwitchFace(split[1],\n new File(twitchFaceDir + File.separator + String.valueOf(emoteID) + \".png\").getAbsolutePath(),\n Boolean.parseBoolean(split[2]));\n FaceManager.twitchFaceMap.put(emoteID, tf);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n FaceManager.twitchFaceMap.keySet().stream().filter(s -> s != null && FaceManager.twitchFaceMap.get(s) != null)\n .forEach(s -> {\n TwitchFace fa = FaceManager.twitchFaceMap.get(s);\n pw.println(s + \",\" + fa.getRegex() + \",\" + Boolean.toString(fa.isEnabled()));\n });\n }\n\n @Override\n public File getFile() {\n return twitchFaceFile;\n }\n }\n\n\n /**\n * Commands\n * <p>\n * trigger[message (content)[arguments?\n */\n public static class Commands extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\"\\\\[\");\n String[] contents = split[1].split(\"]\");\n Command c = new Command(split[0], contents);\n if (split.length > 2) {\n c.addArguments(split[2].split(\",\"));\n }\n GUIMain.commandSet.add(c);\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n for (Command next : GUIMain.commandSet) {\n if (next != null) {\n String name = next.getTrigger();\n String[] contents = next.getMessage().data;\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < contents.length; i++) {\n sb.append(contents[i]);\n if (i != (contents.length - 1)) sb.append(\"]\");\n }\n pw.print(name + \"[\" + sb.toString());\n if (next.hasArguments()) {\n pw.print(\"[\");\n for (int i = 0; i < next.countArguments(); i++) {\n pw.print(next.getArguments().get(i));\n if (i != (next.countArguments() - 1)) pw.print(\",\");\n }\n }\n pw.println();\n }\n }\n }\n\n @Override\n public File getFile() {\n return commandsFile;\n }\n }\n\n /**\n * Console Commands\n */\n public static void saveConCommands() {\n try (PrintWriter br = new PrintWriter(ccommandsFile)) {\n GUIMain.conCommands.forEach(br::println);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n\n private static ConsoleCommand.Action getAction(String key) {\n ConsoleCommand.Action act = null;\n for (ConsoleCommand.Action a : ConsoleCommand.Action.values()) {\n if (a.toString().equalsIgnoreCase(key)) {\n act = a;\n break;\n }\n }\n return act;\n }\n\n public static void loadConsoleCommands() {\n Set<ConsoleCommand> hardcoded = new HashSet<>();\n hardcoded.add(new ConsoleCommand(\"addface\", ConsoleCommand.Action.ADD_FACE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"changeface\", ConsoleCommand.Action.CHANGE_FACE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removeface\", ConsoleCommand.Action.REMOVE_FACE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"toggleface\", ConsoleCommand.Action.TOGGLE_FACE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"addsound\", ConsoleCommand.Action.ADD_SOUND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"changesound\", ConsoleCommand.Action.CHANGE_SOUND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removesound\", ConsoleCommand.Action.REMOVE_SOUND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setsound\", ConsoleCommand.Action.SET_SOUND_DELAY, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"togglesound\", ConsoleCommand.Action.TOGGLE_SOUND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"stopsound\", ConsoleCommand.Action.STOP_SOUND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"stopallsounds\", ConsoleCommand.Action.STOP_ALL_SOUNDS, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"addkeyword\", ConsoleCommand.Action.ADD_KEYWORD, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removekeyword\", ConsoleCommand.Action.REMOVE_KEYWORD, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setcol\", ConsoleCommand.Action.SET_USER_COL, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setpermission\", ConsoleCommand.Action.SET_COMMAND_PERMISSION, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"addcommand\", ConsoleCommand.Action.ADD_TEXT_COMMAND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removecommand\", ConsoleCommand.Action.REMOVE_TEXT_COMMAND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"adddonation\", ConsoleCommand.Action.ADD_DONATION, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setsoundperm\", ConsoleCommand.Action.SET_SOUND_PERMISSION, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setnameface\", ConsoleCommand.Action.SET_NAME_FACE, Permissions.Permission.SUBSCRIBER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removenameface\", ConsoleCommand.Action.REMOVE_NAME_FACE, Permissions.Permission.SUBSCRIBER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"playad\", ConsoleCommand.Action.PLAY_ADVERT, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"settitle\", ConsoleCommand.Action.SET_STREAM_TITLE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"title\", ConsoleCommand.Action.SEE_STREAM_TITLE, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setgame\", ConsoleCommand.Action.SET_STREAM_GAME, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"game\", ConsoleCommand.Action.SEE_STREAM_GAME, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"startraffle\", ConsoleCommand.Action.START_RAFFLE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"addrafflewinner\", ConsoleCommand.Action.ADD_RAFFLE_WINNER, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"stopraffle\", ConsoleCommand.Action.STOP_RAFFLE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removerafflewinner\", ConsoleCommand.Action.REMOVE_RAFFLE_WINNER, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"winners\", ConsoleCommand.Action.SEE_WINNERS, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"startpoll\", ConsoleCommand.Action.START_POLL, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"vote\", ConsoleCommand.Action.VOTE_POLL, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"pollresult\", ConsoleCommand.Action.POLL_RESULT, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"cancelpoll\", ConsoleCommand.Action.CANCEL_POLL, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"song\", ConsoleCommand.Action.NOW_PLAYING, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"soundstate\", ConsoleCommand.Action.SEE_SOUND_STATE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"uptime\", ConsoleCommand.Action.SHOW_UPTIME, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"lastsubsound\", ConsoleCommand.Action.SEE_PREV_SOUND_SUB, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"lastdonationsound\", ConsoleCommand.Action.SEE_PREV_SOUND_DON, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"botreply\", ConsoleCommand.Action.SEE_OR_SET_REPLY_TYPE, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"volume\", ConsoleCommand.Action.SEE_OR_SET_VOLUME, Permissions.Permission.MODERATOR.permValue, null));\n\n if (Utils.areFilesGood(ccommandsFile.getAbsolutePath())) {\n try (InputStreamReader isr = new InputStreamReader(ccommandsFile.toURI().toURL().openStream());\n BufferedReader br = new BufferedReader(isr)) {\n\n String line;\n while ((line = br.readLine()) != null) {\n String[] split = line.split(\"\\\\[\");\n ConsoleCommand.Action a = getAction(split[1]);\n int classPerm;\n try {\n classPerm = Integer.parseInt(split[2]);\n } catch (Exception e) {\n classPerm = -1;\n }\n List<String> customUsers = new ArrayList<>();\n if (!split[3].equalsIgnoreCase(\"null\")) {\n customUsers.addAll(Arrays.asList(split[3].split(\",\")));\n }\n GUIMain.conCommands.add(new ConsoleCommand(split[0], a, classPerm, customUsers));\n }\n\n // Did we miss any commands?\n if (GUIMain.conCommands.size() != hardcoded.size()) {\n //this ensures every hard coded ConCommand is loaded for Botnak\n hardcoded.stream().filter(con -> !GUIMain.conCommands.contains(con)).forEach(GUIMain.conCommands::add);\n }\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n else { //first time boot/reset/deleted file etc.\n GUIMain.conCommands.addAll(hardcoded);\n }\n GUIMain.log(\"Loaded console commands!\");\n }\n\n\n /**\n * Keywords\n */\n public static class Keywords extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\",\");\n int r, g, b;\n try {\n r = Integer.parseInt(split[1]);\n } catch (Exception e) {\n r = 255;\n }\n try {\n g = Integer.parseInt(split[2]);\n } catch (Exception e) {\n g = 255;\n }\n try {\n b = Integer.parseInt(split[3]);\n } catch (Exception e) {\n b = 255;\n }\n GUIMain.keywordMap.put(split[0], new Color(r, g, b));\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n Set<String> keys = GUIMain.keywordMap.keySet();\n keys.stream().filter(Objects::nonNull).forEach(word ->\n {\n Color c = GUIMain.keywordMap.get(word);\n pw.println(word + \",\" + c.getRed() + \",\" + c.getGreen() + \",\" + c.getBlue());\n });\n }\n\n @Override\n public File getFile() {\n return keywordsFile;\n }\n }\n\n /**\n * Donors\n */\n public static class Donors extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\",\");\n double amount;\n try {\n amount = Double.parseDouble(split[1]);\n } catch (Exception e) {\n amount = 0.0;\n }\n donationManager.getDonors().add(new Donor(split[0], amount));\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n donationManager.getDonors().forEach(pw::println);\n }\n\n @Override\n public File getFile() {\n return donorsFile;\n }\n }\n\n\n /**\n * Donations.\n */\n public static class Donations extends AbstractFileSave {\n\n private static HashSet<Donation> donations = new HashSet<>();\n private static Donation mostRecent = null;\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\"\\\\[\");\n double amount;\n try {\n amount = Double.parseDouble(split[3]);\n } catch (Exception e) {\n amount = 0.0;\n }\n Donation d = new Donation(split[0], split[1], split[2], amount, Date.from(Instant.parse(split[4])));\n if ((mostRecent == null || mostRecent.compareTo(d) > 0) && !d.getDonationID().equals(\"LOCAL\"))\n mostRecent = d;\n donations.add(d);\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n donationManager.getDonations().stream().sorted().forEach(pw::println);\n }\n\n @Override\n public File getFile() {\n return donationsFile;\n }\n }\n\n\n /**\n * Subscribers of your own channel\n * <p>\n * Saves each subscriber with the first date Botnak meets them\n * and each month check to see if they're still subbed, if not, make them an ex-subscriber\n */\n private static class Subscribers extends AbstractFileSave {\n\n private static Set<Subscriber> subscribers = new HashSet<>();\n private static Subscriber mostRecent = null;\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\"\\\\[\");\n Subscriber s = new Subscriber(Long.parseLong(split[0]), LocalDateTime.parse(split[1]), Boolean.parseBoolean(split[2]), Integer.parseInt(split[3]));\n subscribers.add(s);\n if (mostRecent == null || mostRecent.compareTo(s) > 0) mostRecent = s;\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n subscriberManager.getSubscribers().values().stream().sorted().forEach(pw::println);\n }\n\n @Override\n public File getFile() {\n return subsFile;\n }\n }\n\n\n /**\n * Tab State\n * <p>\n * This is for opening back up to the correct tab, with the correct pane showing.\n * This also handles saving the combined tabs.\n * Format:\n * <p>\n * Single:\n * bool bool string\n * single[ selected[ name\n * <p>\n * Combined:\n * bool boolean String String String[] (split(\",\"))\n * single[ selected[ activeChannel[ title[ every,channel,in,it,separated,by,commas\n * <p>\n * No spaces though.\n * <p>\n * Single tabs can be invisible if they are in a combined tab.\n */\n private static class TabState extends AbstractFileSave {\n\n public static int startIndex = 0;\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\"\\\\[\");\n boolean isSingle = Boolean.parseBoolean(split[0]);\n boolean isSelected = Boolean.parseBoolean(split[1]);\n if (isSingle) {\n String channel = split[2];\n if (accountManager.getUserAccount() != null) {\n String channelName = \"#\" + channel;\n GUIMain.channelSet.add(channelName);\n }\n ChatPane cp = ChatPane.createPane(channel);\n GUIMain.chatPanes.put(cp.getChannel(), cp);\n GUIMain.channelPane.insertTab(cp.getChannel(), null, cp.getScrollPane(), null, cp.getIndex());\n if (isSelected) startIndex = cp.getIndex();\n } else {\n String activeChannel = split[2];\n String title = split[3];\n String[] channels = split[4].split(\",\");\n ArrayList<ChatPane> cps = new ArrayList<>();\n for (String c : channels) {\n if (accountManager.getUserAccount() != null) {\n String channelName = \"#\" + c;\n GUIMain.channelSet.add(channelName);\n }\n ChatPane cp = ChatPane.createPane(c);\n GUIMain.chatPanes.put(cp.getChannel(), cp);\n cps.add(cp);\n }\n CombinedChatPane ccp = CombinedChatPane.createCombinedChatPane(cps.toArray(new ChatPane[cps.size()]));\n GUIMain.channelPane.insertTab(ccp.getTabTitle(), null, ccp.getScrollPane(), null, ccp.getIndex());\n ccp.setCustomTitle(title);\n if (isSelected) startIndex = ccp.getIndex();\n if (!activeChannel.equalsIgnoreCase(\"all\")) {\n ccp.setActiveChannel(activeChannel);\n ccp.setActiveScrollPane(activeChannel);\n }\n GUIMain.combinedChatPanes.add(ccp);\n }\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n int currentSelectedIndex = GUIMain.channelPane.getSelectedIndex();\n for (int i = 1; i < GUIMain.channelPane.getTabCount() - 1; i++) {\n ChatPane current = Utils.getChatPane(i);\n if (current != null) {\n if (current.isTabVisible()) {\n boolean selected = current.getIndex() == currentSelectedIndex;\n pw.println(\"true[\" + String.valueOf(selected) + \"[\" + current.getChannel());\n }\n } else {\n CombinedChatPane cc = Utils.getCombinedChatPane(i);\n if (cc != null) {\n //all the panes in them should be set to false\n //their indexes are technically going to be -1\n boolean selected = cc.getIndex() == currentSelectedIndex;\n pw.print(\"false[\" + String.valueOf(selected) + \"[\" + cc.getActiveChannel() + \"[\" + cc.getTabTitle() + \"[\");\n pw.print(cc.getChannels().stream().collect(Collectors.joining(\",\")));\n pw.println();\n }\n }\n }\n }\n\n @Override\n public File getFile() {\n return tabsFile;\n }\n }\n\n /**\n * Look and Feel\n */\n public static class LookAndFeel extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n if (line.contains(\"jtattoo\")) lookAndFeel = line;\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n pw.println(lookAndFeel);\n }\n\n @Override\n public File getFile() {\n return lafFile;\n }\n }\n\n /**\n * Window Location and Size\n */\n private static class Window extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] parts = line.substring(1).split(\",\");\n String first = parts[0];\n String second = parts[1];\n if (line.startsWith(\"p\")) {\n try {\n int x = Integer.parseInt(first);\n int y = Integer.parseInt(second);\n GUIMain.instance.setLocation(x, y);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n } else if (line.startsWith(\"s\")) {\n try {\n double w = Double.parseDouble(first);\n double h = Double.parseDouble(second);\n GUIMain.instance.setSize((int) w, (int) h);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n pw.println(\"p\" + GUIMain.instance.getLocationOnScreen().x + \",\" + GUIMain.instance.getLocationOnScreen().y);\n pw.println(\"s\" + GUIMain.instance.getSize().getWidth() + \",\" + GUIMain.instance.getSize().getHeight());\n }\n\n\n @Override\n public File getFile() {\n return windowFile;\n }\n }\n\n //Other methods that don't follow standardization\n\n /**\n * Name faces\n */\n public static void loadNameFaces(File[] nameFaces) {\n try {\n for (File nameFace : nameFaces) {\n if (nameFace.isDirectory()) continue;\n String userID = Utils.removeExt(nameFace.getName());\n FaceManager.nameFaceMap.put(Long.parseLong(userID), new Face(userID, nameFace.getAbsolutePath()));\n }\n GUIMain.log(\"Loaded name faces!\");\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n\n private static void doLoadSubSounds() {\n loadSubSounds();\n loadedSubSounds = true;\n GUIMain.log(\"Loaded sub sounds!\");\n }\n\n public static void loadSubSounds() {\n loadShuffleSet(subSoundDir, SoundEngine.getEngine().getSubStack());\n }\n\n private static void doLoadDonationSounds() {\n loadDonationSounds();\n loadedDonationSounds = true;\n GUIMain.log(\"Loaded donation sounds!\");\n }\n\n public static void loadDonationSounds() {\n loadShuffleSet(donationSoundDir, SoundEngine.getEngine().getDonationStack());\n }\n\n private static void loadShuffleSet(File directory, Deque<Sound> stack) {\n try {\n File[] files = directory.listFiles();\n if (files != null && files.length > 0) {\n ArrayList<Sound> sounds = new ArrayList<>();\n for (File f : files) {\n sounds.add(new Sound(5, f.getAbsolutePath()));\n }\n Collections.shuffle(sounds);\n stack.addAll(sounds);\n }\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n\n /**\n * Sub icons\n */\n public static void loadSubIcons(File[] subIconFiles) {\n for (File f : subIconFiles) {\n FaceManager.subIconMap.put(Utils.removeExt(f.getName()), f.getAbsolutePath());\n }\n }\n\n /**\n * FrankerFaceZ\n * <p>\n * We can be a little more broad about this saving, since it's a per-channel basis\n */\n public static void loadFFZFaces(File[] channels) {\n for (File channel : channels) {\n if (channel.isDirectory() && channel.length() > 0) {\n File[] faces = channel.listFiles();\n if (faces != null) {\n ArrayList<FrankerFaceZ> loadedFaces = new ArrayList<>();\n for (File face : faces) {\n if (face != null) {\n loadedFaces.add(new FrankerFaceZ(face.getName(), face.getAbsolutePath(), true));\n }\n }\n FaceManager.ffzFaceMap.put(channel.getName(), loadedFaces);\n } else {\n channel.delete();\n }\n }\n }\n }\n}" ]
import gui.ChatPane; import gui.forms.GUIMain; import lib.scalr.Scalr; import util.AnimatedGifEncoder; import util.GifDecoder; import util.Utils; import util.settings.Settings; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL;
package face; /** * A class which specifies special chat icons, or 'badges'. * This allows for easier creation of custom icons, and * should be easily adaptable to create custom donation * levels. * * @author Joseph Blackman * @version 4/10/2015 */ public class Icons { /** * For a specified icon, returns the file containing the * image, resized to fit into the chat window. * * @param i the type of icon to get * @return the icon along with what type it is */ public static BotnakIcon getIcon(IconEnum i, String channel) { ImageIcon icon = null; switch (i) { case MOD: icon = sizeIcon(Settings.modIcon.getValue()); break; case BROADCASTER: icon = sizeIcon(Settings.broadIcon.getValue()); break; case ADMIN: icon = sizeIcon(Settings.adminIcon.getValue()); break; case STAFF: icon = sizeIcon(Settings.staffIcon.getValue()); break; case TURBO: icon = sizeIcon(Settings.turboIcon.getValue()); break; case PRIME:
icon = sizeIcon(ChatPane.class.getResource("/image/prime.png"));
0
rla/while
src/com/infdot/analysis/cfg/node/AssignmentNode.java
[ "public abstract class AbstractNodeVisitor<V> {\n\t\n\tprivate Map<AbstractNode, DataflowExpression<V>> visited =\n\t\tnew HashMap<AbstractNode, DataflowExpression<V>>();\n\t\n\tprivate int currentVarId = 0;\n\tprivate Map<AbstractNode, Integer> variables =\n\t\tnew HashMap<AbstractNode, Integer>();\n\t\n\tpublic abstract void visitAssignment(AssignmentNode node);\n\t\n\tpublic abstract void visitDeclaration(DeclarationNode node);\n\t\n\tpublic abstract void visitExit(ExitNode node);\n\t\n\tpublic abstract void visitOutput(OutputNode node);\n\t\n\tpublic abstract void visitCondition(ConditionNode node);\n\t\n\tpublic abstract void visitEntry(EntryNode node);\n\t\n\tpublic boolean hasVisited(AbstractNode node) {\n\t\treturn visited.containsKey(node);\n\t}\n\t\n\tpublic void markVisited(AbstractNode node) {\n\t\tvisited.put(node, null);\n\t}\n\t\n\tprotected void setConstraint(AbstractNode node, DataflowExpression<V> expression) {\n\t\tvisited.put(node, expression);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder builder = new StringBuilder();\n\t\t\n\t\tfor (Entry<AbstractNode, DataflowExpression<V>> e : visited.entrySet()) {\n\t\t\tbuilder.append(\"[[\").append(e.getKey()).append(\"]]\")\n\t\t\t\t.append(\" = \").append(e.getValue()).append('\\n');\n\t\t}\n\t\t\n\t\treturn builder.toString();\n\t}\n\t\n\t/**\n\t * Returns collected dataflow expressions.\n\t */\n\tpublic Map<AbstractNode, DataflowExpression<V>> getExpressions() {\n\t\treturn visited;\n\t}\n\t\n\t/**\n\t * Helper method to generate variable id from given node.\n\t * For this analysis each node is a variable.\n\t */\n\tprotected int getVariableId(AbstractNode node) {\n\t\tInteger id = variables.get(node);\n\t\tif (id == null) {\n\t\t\tid = currentVarId++;\n\t\t\tvariables.put(node, id);\n\t\t}\n\t\t\n\t\treturn id;\n\t}\n\t\n\t/**\n\t * Creates constraint set from found expressions.\n\t */\n\tpublic DataflowConstraintSet<V, AbstractNode> getConstraints() {\n\t\t\n\t\tDataflowConstraintSet<V, AbstractNode> set =\n\t\t\tnew DataflowConstraintSet<V, AbstractNode>();\n\t\t\n\t\tfor (Entry<AbstractNode, DataflowExpression<V>> e : visited.entrySet()) {\n\t\t\t\n\t\t\t// Ignore if there is no constraint\n\t\t\t// for the node.\n\t\t\tif (e.getValue() == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tset.addConstraint(getVariableId(e.getKey()), e.getValue(), e.getKey());\n\t\t}\n\t\t\n\t\treturn set;\n\t}\n\n}", "public class VariableNameTransform implements Transform<Identifier, String> {\n\n\t@Override\n\tpublic String apply(Identifier o) {\n\t\treturn o.getName();\n\t}\n\n}", "public abstract class Expression {\n\t/**\n\t * Unique identifier for each expression.\n\t * @see {@link ExpressionNumberingVisitor}\n\t */\n\tprivate int id = -1;\n\t\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Helper method to collect variables.\n\t */\n\tpublic abstract void collectVariables(Set<Identifier> variables);\n\t\n\t/**\n\t * Method to accept visitor.\n\t */\n\tpublic abstract <V> V visit(AbstractExpressionVisitor<V> visitor);\n\n\t@Override\n\tpublic final boolean equals(Object obj) {\n\t\tcheckId();\n\t\treturn obj instanceof Expression\n\t\t\t&& ((Expression) obj).id == id;\n\t}\n\n\t@Override\n\tpublic final int hashCode() {\n\t\tcheckId();\n\t\treturn id;\n\t}\n\t\n\tprivate void checkId() {\n\t\tif (id < 0) {\n\t\t\tthrow new IllegalStateException(\"Expression \" + this + \" has no id set\");\n\t\t}\n\t}\n\n}", "public class Identifier extends Expression {\n\tprivate String name;\n\n\tpublic Identifier(String name) {\n\t\tthis.name = name;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn name;\n\t}\n\n\t@Override\n\tpublic void collectVariables(Set<Identifier> variables) {\n\t\tvariables.add(this);\n\t}\n\n\t@Override\n\tpublic <V> V visit(AbstractExpressionVisitor<V> visitor) {\n\t\treturn visitor.visitIdentifier(this);\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t\n}", "public class Assignment implements Statement {\n\tprivate Identifier identifier;\n\tprivate Expression expression;\n\t\n\tpublic Assignment(String string, Expression expression) {\n\t\tthis.identifier = new Identifier(string);\n\t\tthis.expression = expression;\n\t}\n\t\n\tpublic Assignment(Identifier identifier, Expression expression) {\n\t\tthis.identifier = identifier;\n\t\tthis.expression = expression;\n\t}\n\n\t@Override\n\tpublic void toCodeString(StringBuilder builder, String ident) {\n\t\tbuilder.append(ident).append(this).append(';');\n\t}\n\n\tpublic Identifier getIdentifier() {\n\t\treturn identifier;\n\t}\n\n\tpublic Expression getExpression() {\n\t\treturn expression;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn identifier + \"=\" + expression;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\treturn obj instanceof Assignment\n\t\t\t&& ((Assignment) obj).identifier.equals(identifier)\n\t\t\t&& ((Assignment) obj).expression.equals(expression);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn identifier.hashCode() ^ expression.hashCode();\n\t}\n\n\t@Override\n\tpublic <T> T visit(AbstractStatementVisitor<T> visitor) {\n\t\treturn visitor.visitAssignment(this);\n\t}\n\t\n}", "public interface DataflowExpression<V> {\n\t/**\n\t * Evaluates expression using the given variable values.\n\t */\n\tV eval(V[] values);\n\t\n\t/**\n\t * Helper to collect all variables,\n\t */\n\tvoid collectVariables(Set<Integer> variables);\n}", "public class PowersetDomain<T> implements Domain<Set<T>> {\n\n\t@Override\n\tpublic Set<T> bottom() {\n\t\treturn Collections.<T>emptySet();\n\t}\n\n\t@Override\n\tpublic Set<T>[] createStartState(int size) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tSet<T>[] s = new Set[size];\n\t\t\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\ts[i] = bottom();\n\t\t}\n\t\t\n\t\treturn s;\n\t}\n\t\n\t/**\n\t * Helper method to construct set expression from concrete set.\n\t */\n\tpublic static <V> DataflowExpression<Set<V>> set(Collection<V> set) {\n\t\tSet<V> strings = new HashSet<V>();\n\t\t\n\t\tfor (V i : set) {\n\t\t\tstrings.add(i);\n\t\t}\n\t\t\n\t\treturn new SetExpression<V>(strings);\n\t}\n\t\n\t/**\n\t * Helper method to construct expression for removing single\n\t * element from the powerset value.\n\t */\n\tpublic static <V> DataflowExpression<Set<V>> remove(\n\t\tDataflowExpression<Set<V>> set, V e) {\n\t\t\n\t\treturn new RemoveOperation<V>(set, e);\n\t}\n\t\n\t/**\n\t * Helper method to construct union operation between two\n\t * powerset dataflow expressions.\n\t */\n\tpublic static <V> DataflowExpression<Set<V>> union(\n\t\tDataflowExpression<Set<V>> e1,\n\t\tDataflowExpression<Set<V>> e2) {\n\t\t\n\t\treturn new UnionOperation<V>(e1, e2);\n\t}\n\t\n\t/**\n\t * Helper method to construct set substract operation.\n\t */\n\tpublic static <V> DataflowExpression<Set<V>> sub(\n\t\tDataflowExpression<Set<V>> e1,\n\t\tDataflowExpression<Set<V>> e2) {\n\t\t\n\t\treturn new SubstractOperation<V>(e1, e2);\n\t}\n\t\n\t/**\n\t * Helper method to construct singleton set.\n\t */\n\tpublic static <V> DataflowExpression<Set<V>> one(V e) {\n\t\treturn new SetExpression<V>(e);\n\t}\n\n\tpublic static <V> DataflowExpression<Set<V>> empty() {\n\t\treturn new EmptySet<V>();\n\t}\n\n}", "public class CollectionUtil {\n\t\n\tpublic static <T> Set<T> union(Set<T> s1, Set<T> s2) {\n\t\tSet<T> s = new HashSet<T>();\n\t\ts.addAll(s1);\n\t\ts.addAll(s2);\n\t\t\n\t\treturn s;\n\t}\n\t\n\tpublic static <T1, T2> Collection<T2> transform(Collection<T1> c1, Collection<T2> c2, Transform<T1, T2> t) {\n\t\tfor (T1 o : c1) {\n\t\t\tc2.add(t.apply(o));\n\t\t}\n\t\t\n\t\treturn c2;\n\t}\n\n}" ]
import java.util.HashSet; import java.util.Set; import com.infdot.analysis.cfg.node.visitor.AbstractNodeVisitor; import com.infdot.analysis.examples.VariableNameTransform; import com.infdot.analysis.language.expression.Expression; import com.infdot.analysis.language.expression.Identifier; import com.infdot.analysis.language.statement.Assignment; import com.infdot.analysis.solver.DataflowExpression; import com.infdot.analysis.solver.lattice.powerset.PowersetDomain; import com.infdot.analysis.util.CollectionUtil;
package com.infdot.analysis.cfg.node; /** * CFG node for assignments. * * @author Raivo Laanemets */ public class AssignmentNode extends AbstractNode { private Assignment assignment; public AssignmentNode(Assignment assignment) { this.assignment = assignment; }
public Identifier getIdentifier() {
3
zer0Black/zer0MQTTServer
zer0MQTTServer/src/com/syxy/protocol/mqttImp/MQTTProcess.java
[ "public class ConnectMessage extends Message {\n\t\n\tpublic ConnectMessage(FixedHeader fixedHeader, ConnectVariableHeader variableHeader,\n\t\t\tConnectPayload payload) {\n\t\tsuper(fixedHeader, variableHeader, payload);\n\t}\n\t\n\t@Override\n\tpublic ConnectVariableHeader getVariableHeader() {\n\t\treturn (ConnectVariableHeader)super.getVariableHeader();\n\t}\n\t\n\t@Override\n\tpublic ConnectPayload getPayload() {\n\t\treturn (ConnectPayload)super.getPayload();\n\t}\n\n}", "public class Message {\n\t\n\tprivate final FixedHeader fixedHeader;\n\tprivate final Object variableHeader;\n\tprivate final Object payload;\n\t\n\tpublic Message(FixedHeader fixedHeader,\n\t\t\t\t Object variableHeader,\n\t\t\t\t Object payload){\n\t\tthis.fixedHeader = fixedHeader;\n\t\tthis.variableHeader = variableHeader;\n\t\tthis.payload = payload;\n\t}\n\t\n\t/**\n\t * 初始化message,针对没有可变头部和荷载的协议类型\n\t * @author zer0\n\t * @version 1.0\n\t * @date 2016-3-3\n\t */\n\tpublic Message(FixedHeader fixedHeader){\n\t\tthis(fixedHeader, null, null);\n\t}\n\t\n\t/**\n\t * 初始化message,针对没有荷载的协议类型\n\t * @author zer0\n\t * @version 1.0\n\t * @date 2016-3-3\n\t */\n\tpublic Message(FixedHeader fixedHeader, Object variableHeader){\n\t\tthis(fixedHeader, variableHeader, null);\n\t}\n\n\tpublic FixedHeader getFixedHeader() {\n\t\treturn fixedHeader;\n\t}\n\n\tpublic Object getVariableHeader() {\n\t\treturn variableHeader;\n\t}\n\n\tpublic Object getPayload() {\n\t\treturn payload;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder stringBuilder = new StringBuilder();\n\t\tstringBuilder.append(StringUtil.simpleClassName(this))\n\t\t\t\t\t .append(\"[\")\n\t\t\t\t\t .append(\"fixedHeader=\")\n\t\t\t\t\t .append(getFixedHeader() != null?getFixedHeader().toString():\"\")\n\t\t\t\t\t .append(\",variableHeader=\")\n\t\t\t\t\t .append(getVariableHeader() != null?getVariableHeader().toString():\"\")\n\t\t\t\t\t .append(\",payload=\")\n\t\t\t\t\t .append(getPayload() != null?getPayload().toString():\"\")\n\t\t\t\t\t .append(\"]\");\n\t\treturn stringBuilder.toString();\n\t}\n\n}", "public class PackageIdVariableHeader {\n\t\n\tprivate int packageID;\n\n\tpublic PackageIdVariableHeader(int packageID) {\n\t\tif (packageID < 1 || packageID > 65535) {\n\t\t\tthrow new IllegalArgumentException(\"消息ID:\" + packageID + \"必须在1~65535范围内\");\n\t\t}\n\t\tthis.packageID = packageID;\n\t}\n\n\tpublic int getPackageID() {\n\t\treturn packageID;\n\t}\n\n\tpublic void setPackageID(int packageID) {\n\t\tthis.packageID = packageID;\n\t}\n\t\n}", "public class PublishMessage extends Message {\n\n\tpublic PublishMessage(FixedHeader fixedHeader, PublishVariableHeader variableHeader,\n\t\t\tByteBuf payload) {\n\t\tsuper(fixedHeader, variableHeader, payload);\n\t}\n\t\n\t@Override\n\tpublic PublishVariableHeader getVariableHeader() {\n\t\treturn (PublishVariableHeader)super.getVariableHeader();\n\t}\n\t\n\t@Override\n\tpublic ByteBuf getPayload() {\n\t\treturn (ByteBuf)super.getPayload();\n\t}\n\n}", "public class SubscribeMessage extends Message {\n\n\tpublic SubscribeMessage(FixedHeader fixedHeader, PackageIdVariableHeader variableHeader,\n\t\t\tSubscribePayload payload) {\n\t\tsuper(fixedHeader, variableHeader, payload);\n\t}\n\t\n\t@Override\n\tpublic PackageIdVariableHeader getVariableHeader() {\n\t\treturn (PackageIdVariableHeader)super.getVariableHeader();\n\t}\n\t\n\t@Override\n\tpublic SubscribePayload getPayload() {\n\t\treturn (SubscribePayload)super.getPayload();\n\t}\n\t\n}", "public class UnSubscribeMessage extends Message {\n\n\tpublic UnSubscribeMessage(FixedHeader fixedHeader, PackageIdVariableHeader variableHeader,\n\t\t\tUnSubscribePayload payload) {\n\t\tsuper(fixedHeader, variableHeader, payload);\n\t}\n\t\n\t@Override\n\tpublic PackageIdVariableHeader getVariableHeader() {\n\t\treturn (PackageIdVariableHeader)super.getVariableHeader();\n\t}\n\t\n\t@Override\n\tpublic UnSubscribePayload getPayload() {\n\t\treturn (UnSubscribePayload)super.getPayload();\n\t}\n\t\n}", "public class ProtocolProcess {\n\n\t//遗嘱信息类\n\tstatic final class WillMessage {\n private final String topic;\n private final ByteBuf payload;\n private final boolean retained;\n private final QoS qos;\n\n public WillMessage(String topic, ByteBuf payload, boolean retained, QoS qos) {\n this.topic = topic;\n this.payload = payload;\n this.retained = retained;\n this.qos = qos;\n }\n\n public String getTopic() {\n return topic;\n }\n\n public ByteBuf getPayload() {\n return payload;\n }\n\n public boolean isRetained() {\n return retained;\n }\n\n public QoS getQos() {\n return qos;\n }\n }\n\t\n\tprivate final static Logger Log = Logger.getLogger(ProtocolProcess.class);\n\t\n\tprivate ConcurrentHashMap<Object, ConnectionDescriptor> clients = new ConcurrentHashMap<Object, ConnectionDescriptor>();// 客户端链接映射表\n //存储遗嘱信息,通过ID映射遗嘱信息\n\tprivate ConcurrentHashMap<String, WillMessage> willStore = new ConcurrentHashMap<>();\n\t\n\tprivate IAuthenticator authenticator;\n\tprivate IMessagesStore messagesStore;\n\tprivate ISessionStore sessionStore;\n\tprivate SubscribeStore subscribeStore;\n\t\n\tpublic ProtocolProcess(){\n\t\tMapDBPersistentStore storge = new MapDBPersistentStore();\n\t\tthis.authenticator = new IdentityAuthenticator();\n\t\tthis.messagesStore = storge;\n\t\tthis.messagesStore.initStore();//初始化存储\n\t\tthis.sessionStore = storge;\n\t\tthis.subscribeStore = new SubscribeStore();\n\t}\n\t\n\t//将此类单例\n\tprivate static ProtocolProcess INSTANCE;\n\tpublic static ProtocolProcess getInstance(){\n\t\tif (INSTANCE == null) {\n\t\t\tINSTANCE = new ProtocolProcess();\n\t\t}\n\t\treturn INSTANCE;\n\t}\n\t\n /**\n \t * 处理协议的CONNECT消息类型\n \t * @param clientID\n \t * @param connectMessage\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-3-7\n \t */\n\tpublic void processConnect(Channel client, ConnectMessage connectMessage){\n\t\tLog.info(\"处理Connect的数据\");\n\t\t//首先查看保留位是否为0,不为0则断开连接,协议P24\n\t\tif (!connectMessage.getVariableHeader().isReservedIsZero()) {\n\t\t\tclient.close();\n\t\t\treturn;\n\t\t}\n\t\t//处理protocol name和protocol version, 如果返回码!=0,sessionPresent必为0,协议P24,P32\n\t\tif (!connectMessage.getVariableHeader().getProtocolName().equals(\"MQTT\") || \n\t\t\t\tconnectMessage.getVariableHeader().getProtocolVersionNumber() != 4 ) {\n\t\t\t\n\t\t\tConnAckMessage connAckMessage = (ConnAckMessage) MQTTMesageFactory.newMessage(\n\t\t\t\t\tFixedHeader.getConnAckFixedHeader(), \n\t\t\t\t\tnew ConnAckVariableHeader(ConnectionStatus.UNACCEPTABLE_PROTOCOL_VERSION, false), \n\t\t\t\t\tnull);\n\t\t\t\n\t\t\tclient.writeAndFlush(connAckMessage);\n\t\t\tclient.close();//版本或协议名不匹配,则断开该客户端连接\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t//处理Connect包的保留位不为0的情况,协议P24\n\t\tif (!connectMessage.getVariableHeader().isReservedIsZero()) {\n\t\t\tclient.close();\n\t\t}\n\t\t\n\t\t//处理clientID为null或长度为0的情况,协议P29\n\t\tif (connectMessage.getPayload().getClientId() == null || connectMessage.getPayload().getClientId().length() == 0) {\n\t\t\t//clientID为null的时候,cleanSession只能为1,此时给client设置一个随机的,不存在的mac地址为ID,否则,断开连接\n\t\t\tif (connectMessage.getVariableHeader().isCleanSession()) {\n\t\t\t\tboolean isExist = true;\n\t\t\t\tString macClientID = StringTool.generalMacString();\n\t\t\t\twhile (isExist) {\n\t\t\t\t\tConnectionDescriptor connectionDescriptor = clients.get(macClientID);\n\t\t\t\t\tif (connectionDescriptor == null) {\n\t\t\t\t\t\tconnectMessage.getPayload().setClientId(macClientID);\n\t\t\t\t\t\tisExist = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmacClientID = StringTool.generalMacString();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tLog.info(\"客户端ID为空,cleanSession为0,根据协议,不接收此客户端\");\n\t\t\t\tConnAckMessage connAckMessage = (ConnAckMessage) MQTTMesageFactory.newMessage(\n\t\t\t\t\t\tFixedHeader.getConnAckFixedHeader(), \n\t\t\t\t\t\tnew ConnAckVariableHeader(ConnectionStatus.IDENTIFIER_REJECTED, false), \n\t\t\t\t\t\tnull);\n\t\t\t\tclient.writeAndFlush(connAckMessage);\n\t\t\t\tclient.close();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t\n//\t\t//检查clientID的格式符合与否\n//\t\tif (!StringTool.isMacString(connectMessage.getPayload().getClientId())) {\n//\t\t\tLog.info(\"客户端ID为{\"+connectMessage.getPayload().getClientId()+\"},拒绝此客户端\");\n//\t\t\tConnAckMessage connAckMessage = (ConnAckMessage) MQTTMesageFactory.newMessage(\n//\t\t\t\t\tFixedHeader.getConnAckFixedHeader(), \n//\t\t\t\t\tnew ConnAckVariableHeader(ConnectionStatus.IDENTIFIER_REJECTED, false), \n//\t\t\t\t\tnull);\n//\t\t\tclient.writeAndFlush(connAckMessage);\n//\t\t\tclient.close();\n//\t\t\treturn;\n//\t\t}\n\t\t\n\t\t//如果会话中已经存储了这个新连接的ID,就关闭之前的clientID\n\t\tif (clients.containsKey(connectMessage.getPayload().getClientId())) {\n\t\t\tLog.error(\"客户端ID{\"+connectMessage.getPayload().getClientId()+\"}已存在,强制关闭老连接\");\n\t\t\tChannel oldChannel = clients.get(connectMessage.getPayload().getClientId()).getClient();\n\t\t\tboolean cleanSession = NettyAttrManager.getAttrCleanSession(oldChannel);\n\t\t\tif (cleanSession) {\n\t\t\t\tcleanSession(connectMessage.getPayload().getClientId());\n\t\t\t}\n\t\t\toldChannel.close();\n\t\t}\n\t\t\n\t\t//若至此没问题,则将新客户端连接加入client的维护列表中\n\t\tConnectionDescriptor connectionDescriptor = \n\t\t\t\tnew ConnectionDescriptor(connectMessage.getPayload().getClientId(), \n\t\t\t\t\t\tclient, connectMessage.getVariableHeader().isCleanSession());\n\t\tthis.clients.put(connectMessage.getPayload().getClientId(), connectionDescriptor);\n\t\t//处理心跳包时间,把心跳包时长和一些其他属性都添加到会话中,方便以后使用\n\t\tint keepAlive = connectMessage.getVariableHeader().getKeepAlive();\n\t\tLog.debug(\"连接的心跳包时长是 {\" + keepAlive + \"} s\");\n\t\tNettyAttrManager.setAttrClientId(client, connectMessage.getPayload().getClientId());\n\t\tNettyAttrManager.setAttrCleanSession(client, connectMessage.getVariableHeader().isCleanSession());\n\t\t//协议P29规定,在超过1.5个keepAlive的时间以上没收到心跳包PingReq,就断开连接(但这里要注意把单位是s转为ms)\n\t\tNettyAttrManager.setAttrKeepAlive(client, keepAlive);\n\t\t//添加心跳机制处理的Handler\n\t\tclient.pipeline().addFirst(\"idleStateHandler\", new IdleStateHandler(keepAlive, Integer.MAX_VALUE, Integer.MAX_VALUE, TimeUnit.SECONDS));\n\t\t\n\t\t//处理Will flag(遗嘱信息),协议P26\n\t\tif (connectMessage.getVariableHeader().isHasWill()) {\n\t\t\tQoS willQos = connectMessage.getVariableHeader().getWillQoS();\n\t\t\tByteBuf willPayload = Unpooled.buffer().writeBytes(connectMessage.getPayload().getWillMessage().getBytes());//获取遗嘱信息的具体内容\n\t\t\tWillMessage will = new WillMessage(connectMessage.getPayload().getWillTopic(),\n\t\t\t\t\twillPayload, connectMessage.getVariableHeader().isWillRetain(),willQos);\n\t\t\t//把遗嘱信息与和其对应的的clientID存储在一起\n\t\t\twillStore.put(connectMessage.getPayload().getClientId(), will);\n\t\t}\n\t\t\n\t\t//处理身份验证(userNameFlag和passwordFlag)\n\t\tif (connectMessage.getVariableHeader().isHasUsername() && \n\t\t\t\tconnectMessage.getVariableHeader().isHasPassword()) {\n\t\t\tString userName = connectMessage.getPayload().getUsername();\n\t\t\tString pwd = connectMessage.getPayload().getPassword();\n\t\t\t//此处对用户名和密码做验证\n\t\t\tif (!authenticator.checkValid(userName, pwd)) {\n\t\t\t\tConnAckMessage connAckMessage = (ConnAckMessage) MQTTMesageFactory.newMessage(\n\t\t\t\t\t\tFixedHeader.getConnAckFixedHeader(), \n\t\t\t\t\t\tnew ConnAckVariableHeader(ConnectionStatus.BAD_USERNAME_OR_PASSWORD, false), \n\t\t\t\t\t\tnull);\n\t\t\t\tclient.writeAndFlush(connAckMessage);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//处理cleanSession为1的情况\n if (connectMessage.getVariableHeader().isCleanSession()) {\n //移除所有之前的session并开启一个新的,并且原先保存的subscribe之类的都得从服务器删掉\n cleanSession(connectMessage.getPayload().getClientId());\n }\n \n //TODO 此处生成一个token(以后每次客户端每次请求服务器,都必须先验证此token正确与否),并把token保存到本地以及传回给客户端\n //鉴权获取不应该在这里做\n \n// String token = StringTool.generalRandomString(32);\n// sessionStore.addSession(connectMessage.getClientId(), token);\n// //把荷载封装成json字符串\n// JSONObject jsonObject = new JSONObject();\n// try {\n//\t\t\tjsonObject.put(\"token\", token);\n//\t\t} catch (JSONException e) {\n//\t\t\te.printStackTrace();\n//\t\t}\n \n //处理回写的CONNACK,并回写,协议P29\n ConnAckMessage okResp = null;\n //协议32,session present的处理\n if (!connectMessage.getVariableHeader().isCleanSession() && \n \t\tsessionStore.searchSubscriptions(connectMessage.getPayload().getClientId())) {\n \tokResp = (ConnAckMessage) MQTTMesageFactory.newMessage(\n\t\t\t\t\tFixedHeader.getConnAckFixedHeader(), \n\t\t\t\t\tnew ConnAckVariableHeader(ConnectionStatus.ACCEPTED, true), \n\t\t\t\t\tnull);\n\t\t}else{\n\t\t\tokResp = (ConnAckMessage) MQTTMesageFactory.newMessage(\n\t\t\t\t\tFixedHeader.getConnAckFixedHeader(), \n\t\t\t\t\tnew ConnAckVariableHeader(ConnectionStatus.ACCEPTED, false), \n\t\t\t\t\tnull);\n\t\t}\n \n client.writeAndFlush(okResp);\n Log.info(\"CONNACK处理完毕并成功发送\");\n Log.info(\"连接的客户端clientID=\"+connectMessage.getPayload().getClientId()+\", \" +\n \t\t\"cleanSession为\"+connectMessage.getVariableHeader().isCleanSession());\n \n //如果cleanSession=0,需要在重连的时候重发同一clientID存储在服务端的离线信息\n if (!connectMessage.getVariableHeader().isCleanSession()) {\n //force the republish of stored QoS1 and QoS2\n \trepublishMessage(connectMessage.getPayload().getClientId());\n }\n\t}\n\t\n\t/**\n \t * 处理协议的publish消息类型,该方法先把public需要的事件提取出来\n \t * @param clientID\n \t * @param publishMessage\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-5-18\n \t */\n\tpublic void processPublic(Channel client, PublishMessage publishMessage){\n\t\tLog.info(\"处理publish的数据\");\n\t\tString clientID = NettyAttrManager.getAttrClientId(client);\n\t\tfinal String topic = publishMessage.getVariableHeader().getTopic();\n\t final QoS qos = publishMessage.getFixedHeader().getQos();\n\t final ByteBuf message = publishMessage.getPayload();\n\t final int packgeID = publishMessage.getVariableHeader().getPackageID();\n\t final boolean retain = publishMessage.getFixedHeader().isRetain();\n\t \n\t processPublic(clientID, topic, qos, retain, message, packgeID);\n\t}\n\t\n\t/**\n \t * 处理遗言消息的发送\n \t * @param clientID\n \t * @param willMessage\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-5-26\n \t */\n\tpublic void processPublic(Channel client, WillMessage willMessage){\n\t\tLog.info(\"处理遗言的publish数据\");\n\t\tString clientID = NettyAttrManager.getAttrClientId(client);\n\t\tfinal String topic = willMessage.getTopic();\n\t final QoS qos = willMessage.getQos();\n\t final ByteBuf message = willMessage.getPayload();\n\t final boolean retain = willMessage.isRetained();\n\t \n\t processPublic(clientID, topic, qos, retain, message, null);\n\t}\n\t\n\t/**\n \t * 根据协议进行具体的处理,处理不同的Qos等级下的public事件\n \t * @param clientID\n \t * @param topic\n \t * @param qos\n \t * @param recRetain\n \t * @param message\n \t * @param recPackgeID 此包ID只是客户端传过来的,用于发回pubAck用,发送给其他客户端的包ID,需要重新生成\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-5-19\n \t */\n\tprivate void processPublic(String clientID, String topic, QoS qos, boolean recRetain, ByteBuf message, Integer recPackgeID){\n\t\tLog.info(\"接收public消息:{clientID=\"+clientID+\",Qos=\"+qos+\",topic=\"+topic+\",packageID=\"+recPackgeID+\"}\");\n\t\tString publishKey = null;\n//\t\tint sendPackageID = PackageIDManager.getNextMessageId();\n\t\t\n\t\t//根据协议P34,Qos=3的时候,就关闭连接\n\t\tif (qos == QoS.RESERVE) {\n\t\t\tclients.get(clientID).getClient().close();\n\t\t}\n\t\t\n\t\t//根据协议P52,qos=0, Dup=0, 则把消息发送给所有注册的客户端即可\n\t\tif (qos == QoS.AT_MOST_ONCE) {\n\t\t\tboolean dup = false;\n\t\t\tboolean retain = false;\n\t\t\tsendPublishMessage(topic, qos, message, retain, dup);\n\t\t}\n\t\t\n\t\t//根据协议P53,publish的接受者需要发送该publish(Qos=1,Dup=0)消息给其他客户端,然后发送pubAck给该客户端。\n\t\t//发送该publish消息时候,按此流程: 存储消息→发送给所有人→等待pubAck到来→删除消息\n\t\tif (qos == QoS.AT_LEAST_ONCE) {\n\t\t\tboolean retain = false;\n\t\t\tboolean dup = false;\n\t\t\n\t\t\tsendPublishMessage(topic, qos, message, retain, dup);\n\t\t\tsendPubAck(clientID, recPackgeID);\n\t\t}\n\t\t\n\t\t//根据协议P54,P55\n\t\t//接收端:publish接收消息→存储包ID→发给其他客户端→发回pubRec→收到pubRel→抛弃第二步存储的包ID→发回pubcomp\n\t\t//发送端:存储消息→发送publish(Qos=2,Dup=0)→收到pubRec→抛弃第一步存储的消息→存储pubRec的包ID→发送pubRel→收到pubcomp→抛弃pubRec包ID的存储\n\t\tif (qos == QoS.EXACTLY_ONCE) {\n\t\t\tboolean dup = false;\n\t\t\tboolean retain = false;\n\t\t\tmessagesStore.storePublicPackgeID(clientID, recPackgeID);\n\t\t\tsendPublishMessage(topic, qos, message, retain, dup);\n\t\t\tsendPubRec(clientID, recPackgeID);\n\t\t}\n\t\t\n\t\t//处理消息是否保留,注:publish报文中的主题名不能包含通配符(协议P35),所以retain中保存的主题名不会有通配符\n\t\tif (recRetain) {\n\t\t\tif (qos == QoS.AT_MOST_ONCE) {\n\t\t\t\tmessagesStore.cleanRetained(topic);\n\t\t\t} else {\n\t\t\t\tmessagesStore.storeRetained(topic, message, qos);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n \t * 处理协议的pubAck消息类型\n \t * @param client\n \t * @param pubAckMessage\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-5-21\n \t */\n\tpublic void processPubAck(Channel client, PackageIdVariableHeader pubAckVariableMessage){\t\t\n\t\t String clientID = NettyAttrManager.getAttrClientId(client);\n\t\t int pacakgeID = pubAckVariableMessage.getPackageID();\n\t\t String publishKey = String.format(\"%s%d\", clientID, pacakgeID);\n\t\t //取消Publish重传任务\n\t\t QuartzManager.removeJob(publishKey, \"publish\", publishKey, \"publish\");\n\t\t //删除临时存储用于重发的Publish消息\n\t\t messagesStore.removeQosPublishMessage(publishKey);\n\t\t //最后把使用完的包ID释放掉\n\t\t PackageIDManager.releaseMessageId(pacakgeID);\n\t}\n\n\t/**\n \t * 处理协议的pubRec消息类型\n \t * @param client\n \t * @param pubRecMessage\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-5-23\n \t */\n\tpublic void processPubRec(Channel client, PackageIdVariableHeader pubRecVariableMessage){\n\t\t String clientID = NettyAttrManager.getAttrClientId(client);\n\t\t int packageID = pubRecVariableMessage.getPackageID();\n\t\t String publishKey = String.format(\"%s%d\", clientID, packageID);\n\t\t \n\t\t //取消Publish重传任务,同时删除对应的值\n\t\t QuartzManager.removeJob(publishKey, \"publish\", publishKey, \"publish\");\n\t\t messagesStore.removeQosPublishMessage(publishKey);\n\t\t //此处须额外处理,根据不同的事件,处理不同的包ID\n\t\t messagesStore.storePubRecPackgeID(clientID, packageID);\n\t\t //组装PubRel事件后,存储PubRel事件,并发回PubRel\n\t\t PubRelEvent pubRelEvent = new PubRelEvent(clientID, packageID);\n\t\t //此处的Key和Publish的key一致\n\t\t messagesStore.storePubRelMessage(publishKey, pubRelEvent);\n\t\t //发回PubRel\n\t\t sendPubRel(clientID, packageID);\n\t\t //开启PubRel重传事件\n\t\t Map<String, Object> jobParam = new HashMap<String, Object>();\n\t\t jobParam.put(\"ProtocolProcess\", this);\n\t\t jobParam.put(\"pubRelKey\", publishKey);\n\t\t QuartzManager.addJob(publishKey, \"pubRel\", publishKey, \"pubRel\", RePubRelJob.class, 10, 2, jobParam);\n\t}\n\t\n\t/**\n \t * 处理协议的pubRel消息类型\n \t * @param client\n \t * @param pubRelMessage\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-5-23\n \t */\n\tpublic void processPubRel(Channel client, PackageIdVariableHeader pubRelVariableMessage){\n\t\t String clientID = NettyAttrManager.getAttrClientId(client);\n\t\t //删除的是接收端的包ID\n\t\t int pacakgeID = pubRelVariableMessage.getPackageID();\n\t\t \n\t\t messagesStore.removePublicPackgeID(clientID);\n\t\t sendPubComp(clientID, pacakgeID);\n\t}\n\t\n\t/**\n \t * 处理协议的pubComp消息类型\n \t * @param client\n \t * @param pubcompMessage\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-5-23\n \t */\n\tpublic void processPubComp(Channel client, PackageIdVariableHeader pubcompVariableMessage){\n\t\t String clientID = NettyAttrManager.getAttrClientId(client);\n\t\t int packaageID = pubcompVariableMessage.getPackageID();\n\t\t String pubRelkey = String.format(\"%s%d\", clientID, packaageID);\n\t\t \n\t\t //删除存储的PubRec包ID\n\t\t messagesStore.removePubRecPackgeID(clientID);\n\t\t //取消PubRel的重传任务,删除临时存储的PubRel事件\n\t\t QuartzManager.removeJob(pubRelkey, \"pubRel\", pubRelkey, \"pubRel\");\n\t\t messagesStore.removePubRelMessage(pubRelkey);\n\t\t //最后把使用完的包ID释放掉\n\t\t PackageIDManager.releaseMessageId(packaageID);\n\t}\n\n\t/**\n \t * 处理协议的subscribe消息类型\n \t * @param client\n \t * @param subscribeMessage\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-5-24\n \t */\n\tpublic void processSubscribe(Channel client, SubscribeMessage subscribeMessage) { \n\t\t String clientID = NettyAttrManager.getAttrClientId(client);\n\t\t boolean cleanSession = NettyAttrManager.getAttrCleanSession(client);\n\t\t Log.info(\"处理subscribe数据包,客户端ID={\"+clientID+\"},cleanSession={\"+cleanSession+\"}\");\n\t\t //一条subscribeMessage信息可能包含多个Topic和Qos\n\t\t List<TopicSubscribe> topicSubscribes = subscribeMessage.getPayload().getTopicSubscribes();\n\t\t\n\t\t List<Integer> grantedQosLevel = new ArrayList<Integer>();\n\t\t //依次处理订阅\n\t\t for (TopicSubscribe topicSubscribe : topicSubscribes) {\n\t\t\tString topicFilter = topicSubscribe.getTopicFilter();\n\t\t\tQoS qos = topicSubscribe.getQos();\n\t\t\tSubscription newSubscription = new Subscription(clientID, topicFilter, qos, cleanSession);\n\t\t\t//订阅新的订阅\n\t\t\tsubscribeSingleTopic(newSubscription, topicFilter);\n\t\t\t\n\t\t\t//生成suback荷载\n\t\t\tgrantedQosLevel.add(qos.value());\n\t\t }\n\t\t \n\t\t SubAckMessage subAckMessage = (SubAckMessage) MQTTMesageFactory.newMessage(\n\t\t\t\t FixedHeader.getSubAckFixedHeader(), \n\t\t\t\t new PackageIdVariableHeader(subscribeMessage.getVariableHeader().getPackageID()), \n\t\t\t\t new SubAckPayload(grantedQosLevel));\n\t\t \n\t\t Log.info(\"回写subAck消息给订阅者,包ID={\"+subscribeMessage.getVariableHeader().getPackageID()+\"}\");\n\t\t client.writeAndFlush(subAckMessage);\n\t}\n\t\n\n\t/**\n \t * 处理协议的unSubscribe消息类型\n \t * @param client\n \t * @param unSubscribeMessage\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-5-24\n \t */\n\tpublic void processUnSubscribe(Channel client, UnSubscribeMessage unSubscribeMessage){\n\t\t String clientID = NettyAttrManager.getAttrClientId(client);\n\t\t int packageID = unSubscribeMessage.getVariableHeader().getPackageID();\n\t\t Log.info(\"处理unSubscribe数据包,客户端ID={\"+clientID+\"}\");\n\t\t List<String> topicFilters = unSubscribeMessage.getPayload().getTopics();\n\t\t for (String topic : topicFilters) {\n\t\t\t//取消订阅树里的订阅\n\t\t\tsubscribeStore.removeSubscription(topic, clientID);\n\t\t\tsessionStore.removeSubscription(topic, clientID);\n\t\t }\n\t\t \n\t\t Message unSubAckMessage = MQTTMesageFactory.newMessage(\n\t\t\t\t FixedHeader.getUnSubAckFixedHeader(), \n\t\t\t\t new PackageIdVariableHeader(packageID), \n\t\t\t\t null);\n\t\t Log.info(\"回写unSubAck信息给客户端,包ID为{\"+packageID+\"}\");\n\t\t client.writeAndFlush(unSubAckMessage);\n\t}\n\t\n\t/**\n \t * 处理协议的pingReq消息类型\n \t * @param client\n \t * @param pingReqMessage\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-5-24\n \t */\n\tpublic void processPingReq(Channel client, Message pingReqMessage){\n\t\t Log.info(\"收到心跳包\");\n\t\t Message pingRespMessage = MQTTMesageFactory.newMessage(\n\t\t\t\t FixedHeader.getPingRespFixedHeader(), \n\t\t\t\t null, \n\t\t\t\t null);\n\t\t //重置心跳包计时器\n\t\t client.writeAndFlush(pingRespMessage);\n\t}\n\t\n\t/**\n \t * 处理协议的disconnect消息类型\n \t * @param client\n \t * @param disconnectMessage\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-5-24\n \t */\n\tpublic void processDisconnet(Channel client, Message disconnectMessage){\n\t\t String clientID = NettyAttrManager.getAttrClientId(client);\n\t\t boolean cleanSession = NettyAttrManager.getAttrCleanSession(client);\n\t\t if (cleanSession) {\n\t\t\tcleanSession(clientID);\n\t\t }\n\t\t \n\t\twillStore.remove(clientID);\n\n\t\t this.clients.remove(clientID);\n\t\t client.close();\n\t}\n\t\n\t/**\n \t * 清除会话,除了要从订阅树中删掉会话信息,还要从会话存储中删除会话信息\n \t * @param client\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-05-07\n \t */\n\tprivate void cleanSession(String clientID) {\n\t\tsubscribeStore.removeForClient(clientID);\n\t\t//从会话存储中删除信息\n\t\tsessionStore.wipeSubscriptions(clientID);\n\t}\n\n\t/**\n \t * 在客户端重连以后,针对QoS1和Qos2的消息,重发存储的离线消息\n \t * @param clientID\n \t * @author zer0\n \t * @version 1.0\n \t * @date 2015-05-18\n \t */\n\tprivate void republishMessage(String clientID){\n\t\t//取出需要重发的消息列表\n\t\t//查看消息列表是否为空,为空则返回\n\t\t//不为空则依次发送消息并从会话中删除此消息\n\t\tList<PublishEvent> publishedEvents = messagesStore.listMessagesInSession(clientID);\n\t\tif (publishedEvents.isEmpty()) {\n\t\t\tLog.info(\"没有客户端{\"+clientID+\"}存储的离线消息\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tLog.info(\"重发客户端{\"+ clientID +\"}存储的离线消息\");\n\t\tfor (PublishEvent pubEvent : publishedEvents) {\n\t\t\tboolean dup = true;\n\t\t\tsendPublishMessage(pubEvent.getClientID(), \n\t\t\t\t\t\t\t pubEvent.getTopic(), \n\t\t\t\t\t\t\t pubEvent.getQos(), \n\t\t\t\t\t\t\t Unpooled.buffer().writeBytes(pubEvent.getMessage()), \n\t\t\t\t\t\t\t pubEvent.isRetain(), \n\t\t\t\t\t\t\t pubEvent.getPackgeID(),\n\t\t\t\t\t\t\t dup);\n\t\t\tmessagesStore.removeMessageInSessionForPublish(clientID, pubEvent.getPackgeID());\n\t\t}\n\t}\n\t\n\t/**\n\t * 在未收到对应包的情况下,重传Publish消息\n\t * @param publishKey\n\t * @author zer0\n\t * @version 1.0\n\t * @date 2015-11-28\n\t */\n\tpublic void reUnKnowPublishMessage(String publishKey){\n\t\tPublishEvent pubEvent = messagesStore.searchQosPublishMessage(publishKey);\n\t\tLog.info(\"重发PublishKey为{\"+ publishKey +\"}的Publish离线消息\");\n\t\tboolean dup = true;\n\t\tPublishMessage publishMessage = (PublishMessage) MQTTMesageFactory.newMessage(\n\t\t\t\tFixedHeader.getPublishFixedHeader(dup, pubEvent.getQos(), pubEvent.isRetain()), \n\t\t\t\tnew PublishVariableHeader(pubEvent.getTopic(), pubEvent.getPackgeID()), \n\t\t\t\tUnpooled.buffer().writeBytes(pubEvent.getMessage()));\n\t\t//从会话列表中取出会话,然后通过此会话发送publish消息\n\t\tthis.clients.get(pubEvent.getClientID()).getClient().writeAndFlush(publishMessage);\n\t}\n\t\n\t/**\n\t * 在未收到对应包的情况下,重传PubRel消息\n\t * @param pubRelKey\n\t * @author zer0\n\t * @version 1.0\n\t * @date 2015-11-28\n\t */\n\tpublic void reUnKnowPubRelMessage(String pubRelKey){\n\t\tPubRelEvent pubEvent = messagesStore.searchPubRelMessage(pubRelKey);\n\t\tLog.info(\"重发PubRelKey为{\"+ pubRelKey +\"}的PubRel离线消息\");\n\t\tsendPubRel(pubEvent.getClientID(), pubEvent.getPackgeID());\n//\t messagesStore.removeQosPublishMessage(pubRelKey);\n\t}\n\t\n\t/**\n\t * 取出所有匹配topic的客户端,然后发送public消息给客户端\n\t * @param topic\n\t * @param qos\n\t * @param message\n\t * @param retain\n\t * @param PackgeID\n\t * @author zer0\n\t * @version 1.0\n * @date 2015-05-19\n\t */\n\tprivate void sendPublishMessage(String topic, QoS originQos, ByteBuf message, boolean retain, boolean dup){\n\t\tfor (final Subscription sub : subscribeStore.getClientListFromTopic(topic)) {\n\t\t\t\n\t\t\tString clientID = sub.getClientID();\n\t\t\tInteger sendPackageID = PackageIDManager.getNextMessageId();\n\t\t\tString publishKey = String.format(\"%s%d\", clientID, sendPackageID);\n\t\t\tQoS qos = originQos;\n\t\t\t\n\t\t\t//协议P43提到, 假设请求的QoS级别被授权,客户端接收的PUBLISH消息的QoS级别小于或等于这个级别,PUBLISH 消息的级别取决于发布者的原始消息的QoS级别\n\t\t\tif (originQos.ordinal() > sub.getRequestedQos().ordinal()) {\n\t\t\t\tqos = sub.getRequestedQos(); \n\t\t\t}\n\t\t\t\n\t\t\tPublishMessage publishMessage = (PublishMessage) MQTTMesageFactory.newMessage(\n\t\t\t\t\tFixedHeader.getPublishFixedHeader(dup, qos, retain), \n\t\t\t\t\tnew PublishVariableHeader(topic, sendPackageID), \n\t\t\t\t\tmessage);\n\t\t\t\n\t\t\tif (this.clients == null) {\n\t\t\t\tthrow new RuntimeException(\"内部错误,clients为null\");\n\t\t\t} else {\n\t\t\t\tLog.debug(\"clients为{\"+this.clients+\"}\");\n\t\t\t}\n\t\t\t\n\t\t\tif (this.clients.get(clientID) == null) {\n\t\t\t\tthrow new RuntimeException(\"不能从会话列表{\"+this.clients+\"}中找到clientID:{\"+clientID+\"}\");\n\t\t\t} else {\n\t\t\t\tLog.debug(\"从会话列表{\"+this.clients+\"}查找到clientID:{\"+clientID+\"}\");\n\t\t\t}\n\t\t\t\n\t\t\tif (originQos == QoS.AT_MOST_ONCE) {\n\t\t\t\tpublishMessage = (PublishMessage) MQTTMesageFactory.newMessage(\n\t\t\t\t\t\tFixedHeader.getPublishFixedHeader(dup, qos, retain), \n\t\t\t\t\t\tnew PublishVariableHeader(topic), \n\t\t\t\t\t\tmessage);\n\t\t\t\t//从会话列表中取出会话,然后通过此会话发送publish消息\n\t\t\t\tthis.clients.get(clientID).getClient().writeAndFlush(publishMessage);\n\t\t\t}else {\n\t\t\t\tpublishKey = String.format(\"%s%d\", clientID, sendPackageID);//针对每个重生成key,保证消息ID不会重复\n\t\t\t\t//将ByteBuf转变为byte[]\n\t\t\t\tbyte[] messageBytes = new byte[message.readableBytes()];\n\t\t\t\tmessage.getBytes(message.readerIndex(), messageBytes);\n\t\t\t\tPublishEvent storePublishEvent = new PublishEvent(topic, qos, messageBytes, retain, clientID, sendPackageID);\n\t\t\t\t\n\t\t\t\t//从会话列表中取出会话,然后通过此会话发送publish消息\n\t\t\t\tthis.clients.get(clientID).getClient().writeAndFlush(publishMessage);\n\t\t\t\t//存临时Publish消息,用于重发\n\t\t\t\tmessagesStore.storeQosPublishMessage(publishKey, storePublishEvent);\n\t\t\t\t//开启Publish重传任务,在制定时间内未收到PubAck包则重传该条Publish信息\n\t\t\t\tMap<String, Object> jobParam = new HashMap<String, Object>();\n\t\t\t\tjobParam.put(\"ProtocolProcess\", this);\n\t\t\t\tjobParam.put(\"publishKey\", publishKey);\n\t\t\t\tQuartzManager.addJob(publishKey, \"publish\", publishKey, \"publish\", RePublishJob.class, 10, 2, jobParam);\n\t\t\t}\n\t\t\t\n\t\t\tLog.info(\"服务器发送消息给客户端{\"+clientID+\"},topic{\"+topic+\"},qos{\"+qos+\"}\");\n\t\t\t\n\t\t\tif (!sub.isCleanSession()) {\n\t\t\t\t//将ByteBuf转变为byte[]\n\t\t\t\tbyte[] messageBytes = new byte[message.readableBytes()];\n\t\t\t\tmessage.getBytes(message.readerIndex(), messageBytes);\n\t\t\t\tPublishEvent newPublishEvt = new PublishEvent(topic, qos, messageBytes, \n\t\t\t\t\t\t retain, sub.getClientID(), \n\t\t\t\t\t\t sendPackageID != null ? sendPackageID : 0);\n messagesStore.storeMessageToSessionForPublish(newPublishEvt);\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t}\n\t}\n\t\n\t/**\n\t * 发送publish消息给指定ID的客户端\n\t * @param clientID\n\t * @param topic\n\t * @param qos\n\t * @param message\n\t * @param retain\n\t * @param PackgeID\n\t * @param dup\n\t * @author zer0\n\t * @version 1.0\n * @date 2015-05-19\n\t */\n\tprivate void sendPublishMessage(String clientID, String topic, QoS qos, ByteBuf message, boolean retain, Integer packageID, boolean dup){\n\t\tLog.info(\"发送pulicMessage给指定客户端\");\n\t\t\n\t\tString publishKey = String.format(\"%s%d\", clientID, packageID);\n\t\t\n\t\tPublishMessage publishMessage = (PublishMessage) MQTTMesageFactory.newMessage(\n\t\t\t\tFixedHeader.getPublishFixedHeader(dup, qos, retain), \n\t\t\t\tnew PublishVariableHeader(topic, packageID), \n\t\t\t\tmessage);\n\t\t\n\t\tif (this.clients == null) {\n\t\t\tthrow new RuntimeException(\"内部错误,clients为null\");\n\t\t} else {\n\t\t\tLog.debug(\"clients为{\"+this.clients+\"}\");\n\t\t}\n\t\t\n\t\tif (this.clients.get(clientID) == null) {\n\t\t\tthrow new RuntimeException(\"不能从会话列表{\"+this.clients+\"}中找到clientID:{\"+clientID+\"}\");\n\t\t} else {\n\t\t\tLog.debug(\"从会话列表{\"+this.clients+\"}查找到clientID:{\"+clientID+\"}\");\n\t\t}\n\t\t\n\t\tif (qos == QoS.AT_MOST_ONCE) {\n\t\t\tpublishMessage = (PublishMessage) MQTTMesageFactory.newMessage(\n\t\t\t\t\tFixedHeader.getPublishFixedHeader(dup, qos, retain), \n\t\t\t\t\tnew PublishVariableHeader(topic), \n\t\t\t\t\tmessage);\n\t\t\t//从会话列表中取出会话,然后通过此会话发送publish消息\n\t\t\tthis.clients.get(clientID).getClient().writeAndFlush(publishMessage);\n\t\t}else {\n\t\t\tpublishKey = String.format(\"%s%d\", clientID, packageID);//针对每个重生成key,保证消息ID不会重复\n\t\t\t//将ByteBuf转变为byte[]\n\t\t\tbyte[] messageBytes = new byte[message.readableBytes()];\n\t\t\tmessage.getBytes(message.readerIndex(), messageBytes);\n\t\t\tPublishEvent storePublishEvent = new PublishEvent(topic, qos, messageBytes, retain, clientID, packageID);\n\t\t\t\n\t\t\t//从会话列表中取出会话,然后通过此会话发送publish消息\n\t\t\tthis.clients.get(clientID).getClient().writeAndFlush(publishMessage);\n\t\t\t//存临时Publish消息,用于重发\n\t\t\tmessagesStore.storeQosPublishMessage(publishKey, storePublishEvent);\n\t\t\t//开启Publish重传任务,在制定时间内未收到PubAck包则重传该条Publish信息\n\t\t\tMap<String, Object> jobParam = new HashMap<String, Object>();\n\t\t\tjobParam.put(\"ProtocolProcess\", this);\n\t\t\tjobParam.put(\"publishKey\", publishKey);\n\t\t\tQuartzManager.addJob(publishKey, \"publish\", publishKey, \"publish\", RePublishJob.class, 10, 2, jobParam);\n\t\t}\n\t}\n\t\n\t /**\n\t * 发送保存的Retain消息\n\t * @param clientID\n\t * @param topic\n\t * @param qos\n\t * @param message\n\t * @param retain\n\t * @author zer0\n\t * @version 1.0\n * @date 2015-12-1\n\t */\n\tprivate void sendPublishMessage(String clientID, String topic, QoS qos, ByteBuf message, boolean retain){\n\t\tint packageID = PackageIDManager.getNextMessageId();\n\t\tsendPublishMessage(clientID, topic, qos, message, retain, packageID, false);\n\t}\n\t\n\t/**\n\t *回写PubAck消息给发来publish的客户端\n\t * @param clientID\n\t * @param packgeID\n\t * @author zer0\n\t * @version 1.0\n\t * @date 2015-5-21\n\t */\n\tprivate void sendPubAck(String clientID, Integer packageID) {\n\t Log.info(\"发送PubAck消息给客户端\");\n\n\t Message pubAckMessage = MQTTMesageFactory.newMessage(\n\t \t\tFixedHeader.getPubAckFixedHeader(), \n\t \t\tnew PackageIdVariableHeader(packageID), \n\t \t\tnull);\n\t \n\t try {\n\t \tif (this.clients == null) {\n\t\t\t\t\tthrow new RuntimeException(\"内部错误,clients为null\");\n\t\t\t\t} else {\n\t\t\t\t\tLog.debug(\"clients为{\"+this.clients+\"}\");\n\t\t\t\t}\n\t \t\n\t \tif (this.clients.get(clientID) == null) {\n\t\t\t\t\tthrow new RuntimeException(\"不能从会话列表{\"+this.clients+\"}中找到clientID:{\"+clientID+\"}\");\n\t\t\t\t} else {\n\t\t\t\t\tLog.debug(\"从会话列表{\"+this.clients+\"}查找到clientID:{\"+clientID+\"}\");\n\t\t\t\t}\t \n\t \t\n\t\t\t\tthis.clients.get(clientID).getClient().writeAndFlush(pubAckMessage);\n\t }catch(Throwable t) {\n\t Log.error(null, t);\n\t }\n\t }\n\t\n\t/**\n\t *回写PubRec消息给发来publish的客户端\n\t * @param clientID\n\t * @param packgeID\n\t * @author zer0\n\t * @version 1.0\n\t * @date 2015-5-21\n\t */\n\tprivate void sendPubRec(String clientID, Integer packageID) {\n\t Log.trace(\"发送PubRec消息给客户端\");\n\n\t Message pubRecMessage = MQTTMesageFactory.newMessage(\n\t \t\tFixedHeader.getPubAckFixedHeader(), \n\t \t\tnew PackageIdVariableHeader(packageID), \n\t \t\tnull);\n\t \n\t try {\n\t \tif (this.clients == null) {\n\t\t\t\t\tthrow new RuntimeException(\"内部错误,clients为null\");\n\t\t\t\t} else {\n\t\t\t\t\tLog.debug(\"clients为{\"+this.clients+\"}\");\n\t\t\t\t}\n\t \t\n\t \tif (this.clients.get(clientID) == null) {\n\t\t\t\t\tthrow new RuntimeException(\"不能从会话列表{\"+this.clients+\"}中找到clientID:{\"+clientID+\"}\");\n\t\t\t\t} else {\n\t\t\t\t\tLog.debug(\"从会话列表{\"+this.clients+\"}查找到clientID:{\"+clientID+\"}\");\n\t\t\t\t}\t \n\t \t\n\t \tthis.clients.get(clientID).getClient().writeAndFlush(pubRecMessage);\n\t }catch(Throwable t) {\n\t Log.error(null, t);\n\t }\n\t }\n\t\n\t/**\n\t *回写PubRel消息给发来publish的客户端\n\t * @param clientID\n\t * @param packgeID\n\t * @author zer0\n\t * @version 1.0\n\t * @date 2015-5-23\n\t */\n\tprivate void sendPubRel(String clientID, Integer packageID) {\n\t Log.trace(\"发送PubRel消息给客户端\");\n\n\t Message pubRelMessage = MQTTMesageFactory.newMessage(\n\t \t\tFixedHeader.getPubAckFixedHeader(), \n\t \t\tnew PackageIdVariableHeader(packageID), \n\t \t\tnull);\n\t \n\t try {\n\t \tif (this.clients == null) {\n\t\t\t\t\tthrow new RuntimeException(\"内部错误,clients为null\");\n\t\t\t\t} else {\n\t\t\t\t\tLog.debug(\"clients为{\"+this.clients+\"}\");\n\t\t\t\t}\n\t \t\n\t \tif (this.clients.get(clientID) == null) {\n\t\t\t\t\tthrow new RuntimeException(\"不能从会话列表{\"+this.clients+\"}中找到clientID:{\"+clientID+\"}\");\n\t\t\t\t} else {\n\t\t\t\t\tLog.debug(\"从会话列表{\"+this.clients+\"}查找到clientID:{\"+clientID+\"}\");\n\t\t\t\t}\t \n\t \t\n\t \tthis.clients.get(clientID).getClient().writeAndFlush(pubRelMessage);\n\t }catch(Throwable t) {\n\t Log.error(null, t);\n\t }\n\t }\n\t\n\t/**\n\t * 回写PubComp消息给发来publish的客户端\n\t * @param clientID\n\t * @param packgeID\n\t * @author zer0\n\t * @version 1.0\n\t * @date 2015-5-23\n\t */\n\tprivate void sendPubComp(String clientID, Integer packageID) {\n\t Log.trace(\"发送PubComp消息给客户端\");\n\n\t Message pubcompMessage = MQTTMesageFactory.newMessage(\n\t \t\tFixedHeader.getPubAckFixedHeader(), \n\t \t\tnew PackageIdVariableHeader(packageID), \n\t \t\tnull);\n\t \n\t try {\n\t \tif (this.clients == null) {\n\t\t\t\t\tthrow new RuntimeException(\"内部错误,clients为null\");\n\t\t\t\t} else {\n\t\t\t\t\tLog.debug(\"clients为{\"+this.clients+\"}\");\n\t\t\t\t}\n\t \t\n\t \tif (this.clients.get(clientID) == null) {\n\t\t\t\t\tthrow new RuntimeException(\"不能从会话列表{\"+this.clients+\"}中找到clientID:{\"+clientID+\"}\");\n\t\t\t\t} else {\n\t\t\t\t\tLog.debug(\"从会话列表{\"+this.clients+\"}查找到clientID:{\"+clientID+\"}\");\n\t\t\t\t}\t \n\t \t\n\t \tthis.clients.get(clientID).getClient().writeAndFlush(pubcompMessage);\n\t }catch(Throwable t) {\n\t Log.error(null, t);\n\t }\n\t }\n\t\n\t/**\n\t * 处理一个单一订阅,存储到会话和订阅数\n\t * @param newSubscription\n\t * @param topic\n\t * @author zer0\n\t * @version 1.0\n\t * @date 2015-5-25\n\t */\n\tprivate void subscribeSingleTopic(Subscription newSubscription, final String topic){\n\t\tLog.info(\"订阅topic{\"+topic+\"},Qos为{\"+newSubscription.getRequestedQos()+\"}\");\n\t\tString clientID = newSubscription.getClientID();\n\t\tsessionStore.addNewSubscription(newSubscription, clientID);\n\t\tsubscribeStore.addSubscrpition(newSubscription);\n\t\t//TODO 此处还需要将此订阅之前存储的信息发出去\n\t\t Collection<IMessagesStore.StoredMessage> messages = messagesStore.searchRetained(topic);\n\t\t for (IMessagesStore.StoredMessage storedMsg : messages) {\n\t Log.debug(\"send publish message for topic {\" + topic + \"}\");\n\t sendPublishMessage(newSubscription.getClientID(), storedMsg.getTopic(), storedMsg.getQos(), Unpooled.buffer().writeBytes(storedMsg.getPayload()), true);\n\t }\n\t}\n}" ]
import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateHandler; import com.syxy.protocol.mqttImp.message.ConnectMessage; import com.syxy.protocol.mqttImp.message.Message; import com.syxy.protocol.mqttImp.message.PackageIdVariableHeader; import com.syxy.protocol.mqttImp.message.PublishMessage; import com.syxy.protocol.mqttImp.message.SubscribeMessage; import com.syxy.protocol.mqttImp.message.UnSubscribeMessage; import com.syxy.protocol.mqttImp.process.ProtocolProcess;
package com.syxy.protocol.mqttImp; /** * MQTT协议业务处理 * * @author zer0 * @version 1.0 * @date 2015-2-16 */ public class MQTTProcess extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ProtocolProcess process = ProtocolProcess.getInstance();
6
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/image/ImageProcessingThread.java
[ "public class DrawingSize {\n\n\tprivate static final NumberFormat nf = NumberFormat.getInstance();\n\tstatic{\n\t\tnf.setGroupingUsed(false);\n\t\tnf.setMaximumFractionDigits(5);\n\t\tnf.setMaximumFractionDigits(0);\n\t\tnf.setMinimumIntegerDigits(1);\n\t\tnf.setMaximumIntegerDigits(5);\n\t}\n\t\n\tprivate double width;\n\tprivate double height;\n\tprivate String value=\"\";\n\t\n\tpublic DrawingSize(double width, double height){\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.value = nf.format(width) + \" x \" + nf.format(height);\n\t}\n\t\n\tpublic double getWidth() {\n\t\treturn width;\n\t}\n\n\tpublic double getHeight() {\n\t\treturn height;\n\t}\n\n\tpublic String getValue() {\n\t\treturn value;\n\t}\n\n\t// Format is width[mm] x height[mm] <comments>\n\tpublic static DrawingSize parse(String string) {\n\t\tdouble width=0;\n\t\tdouble height=0;\n\t\t\n\t\tString upperCasedString = StringUtils.upperCase(string);\n\t\tString widthString = StringUtils.substringBefore(upperCasedString, \"X\").trim();\n\t\tString heightString = StringUtils.substringAfter(upperCasedString, \"X\").trim();\n\t\t\n\t\twidthString = StringUtils.substringBeforeLast(widthString, \"MM\");\n\t\theightString = StringUtils.substringBefore(heightString, \" \");\n\t\theightString = StringUtils.substringBeforeLast(heightString, \"MM\");\n\t\t\n\t\ttry{\n\t\t\twidth = Double.parseDouble(widthString);\n\t\t\theight = Double.parseDouble(heightString);\n\t\t} catch (Exception e){\n\t\t\tthrow new RuntimeException(\"Invalid Drawing Size! '\" + string + \"'\");\n\t\t}\n\t\t\n\t\tif ((width<=0) || (height<=0)) {\n\t\t\tthrow new RuntimeException(\"Invalid Drawing Size! '\" + string + \"'\");\n\t\t}\n\t\treturn new DrawingSize(width, height);\n\t}\n\t\n}", "public enum CenterOption{\n\tCENTER_NONE, CENTER_HORIZONTAL, CENTER_VERTICAL, CENTER_BOTH\n};", "public enum FlipOption{\n\tFLIP_NONE, FLIP_VERTICAL, FLIP_HORIZONTAL, FLIP_BOTH\n};", "public enum RenderOption{\n\tRENDER_NORMAL, RENDER_HALFTONE, RENDER_EDGE_DETECTION\n};", "public enum RotateOption{\n\tROTATE_NONE, ROTATE_90, ROTATE_180, ROTATE_270\n};", "public enum ScaleOption{\n\tSCALE_BILINEAR, SCALE_BICUBIC, SCALE_NEAREST_NEIGHBOR, SCALE_AREA_AVERAGING\n};", "public class HttpServer {\n\n\tpublic static final File SOURCE_HTML_FILES_DIRECTORY = new File(\"src/main/resources/html\");\n\t\n\tpublic static final File SKETCHY_PROPERTY_FILE=new File(\"SketchyProperties.json\");\n\tpublic static final File IMAGE_UPLOAD_DIRECTORY = new File(\"upload\");\n\t\n\tpublic static ImageProcessingThread imageProcessingThread = null;\n\tpublic static DrawingProcessorThread drawingProccessorThread = null;\n\n\tpublic static File getUploadFile(String filename){\n \treturn new File(IMAGE_UPLOAD_DIRECTORY.getPath() + File.separator + filename);\n\t}\n\t\n\tpublic void start() throws Exception {\n \tif (!IMAGE_UPLOAD_DIRECTORY.exists()) {\n \t\tif (!IMAGE_UPLOAD_DIRECTORY.mkdir()) {\n \t\t\tthrow new Exception(\"Error Creating Upload Directory '\" + IMAGE_UPLOAD_DIRECTORY.getAbsolutePath() + \"!\");\n \t\t}\n \t}\n\n\t\tServer server = new Server(80);\n\n // File Upload Handler\n ServletHolder imageUploadHolder = new ServletHolder(new ImageUploadServlet());\n MultipartConfigElement multipartConfig = new MultipartConfigElement(FileUtils.getTempDirectory().getPath());\n imageUploadHolder.getRegistration().setMultipartConfig(multipartConfig);\n \n // File Upgrade Handler\n ServletHolder upgradeUploadHolder = new ServletHolder(new UpgradeUploadServlet());\n multipartConfig = new MultipartConfigElement(FileUtils.getTempDirectory().getPath());\n upgradeUploadHolder.getRegistration().setMultipartConfig(multipartConfig);\n \n ServletHandler servletHandler = new ServletHandler();\n ServletContextHandler servletContext = new ServletContextHandler();\n servletContext.setHandler(servletHandler);\n servletContext.addServlet(new ServletHolder(new JsonServlet()), \"/servlet/*\");\n servletContext.addServlet(imageUploadHolder, \"/imageUpload/*\");\n servletContext.addServlet(upgradeUploadHolder, \"/upgradeUpload/*\");\n \n // if we are developing, we shouldn't have the Sketchy.jar file in our classpath.\n // in this case, pull from the filesystem, not the .jar\n \n ContextHandler resourceContext = new ContextHandler();\n \n URL url = server.getClass().getClassLoader().getResource(\"html\");\n if (url!=null){\n\t ResourceHandler resourceHandler = new ResourceHandler();\n\t resourceHandler.setDirectoriesListed(false);\n\t resourceContext.setWelcomeFiles(new String[] { \"index.html\" });\n\t resourceContext.setContextPath(\"/\");\n\t String resourceBase = url.toExternalForm();\n\t resourceContext.setResourceBase(resourceBase);\n\t resourceContext.setHandler(resourceHandler);\n } else { \n ResourceHandler resourceHandler = new ResourceHandler();\n resourceHandler.setDirectoriesListed(false);\n resourceContext.setWelcomeFiles(new String[] { \"index.html\" });\n resourceContext.setContextPath(\"/\");\n resourceContext.setResourceBase(SOURCE_HTML_FILES_DIRECTORY.getCanonicalPath());\n resourceContext.setHandler(resourceHandler);\n }\n \n ResourceHandler uploadResourceHandler = new ResourceHandler();\n uploadResourceHandler.setDirectoriesListed(true);\n ContextHandler uploadResourceContext = new ContextHandler();\n uploadResourceContext.setContextPath(\"/upload\");\n uploadResourceContext.setResourceBase(\"./upload\");\n uploadResourceContext.setHandler(uploadResourceHandler);\n \n ContextHandlerCollection contexts = new ContextHandlerCollection();\n contexts.setHandlers(new Handler[] { resourceContext, servletContext, uploadResourceContext});\n server.setHandler(contexts);\n\n server.start();\n server.join();\n\t}\n\t\n\t\n public static void main(String[] args) throws Exception {\n \ttry{\n \t\tSketchyContext.load(SKETCHY_PROPERTY_FILE);\n \t} catch (Exception e){\n \t\tSystem.out.println(\"Error Loading Sketchy Property file! \" + e.getMessage());\n \t}\n \tHttpServer server = new HttpServer();\n \tserver.start();\n }\n}", "public class SketchyImage {\n\tprivate double dotsPerMillimeterWidth = 0;\n\tprivate double dotsPerMillimeterHeight = 0;\n\t\n\tpublic SketchyImage(BufferedImage image, double dotsPerMillimeterWidth, double dotsPerMillimeterHeight) {\n\t\t// make sure image is a byte array\n\t\t// if not, then convert it\n\t\tif (image.getType() !=BufferedImage.TYPE_BYTE_INDEXED){\n\t\t\tthis.image = toByteImage(image);\n\t\t} else {\n\t\t\tthis.image = image;\n\t\t}\n\t\tthis.dotsPerMillimeterWidth = dotsPerMillimeterWidth;\n\t\tthis.dotsPerMillimeterHeight=dotsPerMillimeterHeight;\n\t}\n\t\n\tprivate BufferedImage image = null;\n\t\n\tpublic double getDotsPerMillimeterWidth() {\n\t\treturn dotsPerMillimeterWidth;\n\t}\n\n\tpublic void setDotsPerMillimeterWidth(double dotsPerMillimeterWidth) {\n\t\tthis.dotsPerMillimeterWidth = dotsPerMillimeterWidth;\n\t}\n\n\tpublic double getDotsPerMillimeterHeight() {\n\t\treturn dotsPerMillimeterHeight;\n\t}\n\n\tpublic void setDotsPerMillimeterHeight(double dotsPerMillimeterHeight) {\n\t\tthis.dotsPerMillimeterHeight = dotsPerMillimeterHeight;\n\t}\n\n\tpublic BufferedImage getImage() {\n\t\treturn image;\n\t}\n\tpublic void setImage(BufferedImage image) {\n\t\tthis.image = image;\n\t}\n\t\n\tpublic int getWidth(){\n\t\treturn image.getWidth();\n\t}\n\t\n\tpublic int getHeight(){\n\t\treturn image.getHeight();\n\t}\n\n\tpublic int getWidthInMillimeters(){\n\t\treturn (int) Math.ceil(image.getWidth() / getDotsPerMillimeterWidth());\n\t}\n\t\n\tpublic int getHeightInMillimeters(){\n\t\treturn (int) Math.ceil(image.getHeight() / getDotsPerMillimeterHeight());\n\t}\n\t\n\n\t\n\tpublic static void save(SketchyImage sketchyImage, File file) throws Exception {\n\t\tif (!file.getParentFile().canWrite()){\n\t\t\tthrow new Exception(\"Can not write to File: \" + file.getPath() + \"!\");\n\t\t}\n\t\t\n\t\tif (!StringUtils.endsWithIgnoreCase(file.getName(), \".png\")){\n\t\t\tthrow new Exception(\"Can not save SketchyImage! Must be a .png file!\");\n\t\t}\n\t\t\n\t\tIterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName(\"png\");\n\t\tImageWriter imageWriter = null;\n\t if (imageWriters.hasNext()) { // Just get first one\n\t \timageWriter = imageWriters.next();\n\t }\n\t if (imageWriter==null){\n\t \t// this should never happen!! if so.. we got problems\n\t \tthrow new Exception(\"Can not find ImageReader for .png Files!\");\n\t }\n\t\t\t\n\t\tImageOutputStream os = null;\n\t try {\n\t \tos = ImageIO.createImageOutputStream(file);\n\t \timageWriter.setOutput(os);\n\t \t\n\t ImageWriteParam imageWriterParam = imageWriter.getDefaultWriteParam();\n\t IIOMetadata metadata = imageWriter.getDefaultImageMetadata(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY), imageWriterParam);\n\n\t String metaDataFormatName = metadata.getNativeMetadataFormatName();\n\t IIOMetadataNode metaDataNode =(IIOMetadataNode) metadata.getAsTree(metaDataFormatName);\n\t \n\t NodeList childNodes = metaDataNode.getElementsByTagName(\"pHYs\");\n\t IIOMetadataNode physNode = null;\n\t if (childNodes.getLength() == 0) {\n\t \t physNode = new IIOMetadataNode(\"pHYs\");\n\t \t physNode.setAttribute(\"pixelsPerUnitXAxis\", Integer.toString((int)Math.ceil(sketchyImage.dotsPerMillimeterWidth*1000)));\n\t \t physNode.setAttribute(\"pixelsPerUnitYAxis\", Integer.toString((int)Math.ceil(sketchyImage.dotsPerMillimeterHeight*1000)));\n\t \t physNode.setAttribute(\"unitSpecifier\",\"meter\"); // always meter\n\t \t metaDataNode.appendChild(physNode);\n\t } else {\n\t \t for (int nodeIdx=0;nodeIdx<childNodes.getLength();nodeIdx++){\n\t \t\t physNode = (IIOMetadataNode) childNodes.item(nodeIdx);\n\t \t\t physNode.setAttribute(\"pixelsPerUnitXAxis\", Integer.toString((int)Math.ceil(sketchyImage.dotsPerMillimeterWidth*1000)));\n\t\t \t physNode.setAttribute(\"pixelsPerUnitYAxis\", Integer.toString((int)Math.ceil(sketchyImage.dotsPerMillimeterHeight*1000)));\n\t\t \t physNode.setAttribute(\"unitSpecifier\",\"meter\"); // always meter\n\t \t\t metaDataNode.appendChild(physNode);\n\t \t }\n\t }\n\t metadata.setFromTree(metaDataFormatName, metaDataNode);\n\t imageWriter.write(new IIOImage(sketchyImage.image, null, metadata));\n\t os.flush();\n\t } catch (Exception e){\n\t \tthrow new Exception(\"Error Saving SketchyImage File: \" + file.getPath() + \"! \" + e.getMessage());\n\t } finally {\n\t \tIOUtils.closeQuietly(os);\n\t } \n\t}\n\t\n\tpublic static SketchyImage load(File file) throws Exception {\n\t\tSketchyImage sketchyImage = null;\n\t\t\n\t\tif (!file.exists() || !file.canRead()){\n\t\t\tthrow new Exception(\"Can not find or read File: \" + file.getPath() + \"!\");\n\t\t}\n\t\t\n\t\tif (!StringUtils.endsWithIgnoreCase(file.getName(), \".png\")){\n\t\t\tthrow new Exception(\"Can not load SketchyImage! Must be a .png file!\");\n\t\t}\n\t\t\n\t\tIterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName(\"png\");\n\t ImageReader imageReader = null;\n\t if (imageReaders.hasNext()) { // Just get first one\n\t \timageReader = imageReaders.next();\n\t }\n\t if (imageReader==null){\n\t \t// this should never happen!! if so.. we got problems\n\t \tthrow new Exception(\"Can not find ImageReader for .png Files!\");\n\t }\n\t\t\t\n\t\tImageInputStream is = null;\n\t try {\n\t \tis = ImageIO.createImageInputStream(file);\n\t \timageReader.setInput(is, true);\n\t \tIIOMetadata metaData = imageReader.getImageMetadata(0); // always get first image\n\t IIOMetadataNode metaDataNode = (IIOMetadataNode) metaData.getAsTree(metaData.getNativeMetadataFormatName());\n\t if (metaDataNode==null){\n\t \tthrow new Exception(\"Error retreiving MetaData properties from .png File!\");\n\t }\n\t \n\t NodeList childNodes = metaDataNode.getElementsByTagName(\"pHYs\");\n\t // only look in the first node\n\t if (childNodes.getLength()==0){\n\t \tthrow new Exception(\"Invalid SketchyImage file. It must contain 'pixelsPerUnit' MetaData!\");\n\t }\n \tIIOMetadataNode physNode = (IIOMetadataNode) childNodes.item(0);\n \tString pixelsPerUnitXAxisAttribute = physNode.getAttribute(\"pixelsPerUnitXAxis\");\n \tString pixelsPerUnitYAxisAttribute = physNode.getAttribute(\"pixelsPerUnitYAxis\");\n \t// String unitSpecifierAttribute = physNode.getAttribute(\"unitSpecifier\"); Just assuming meter\n \tif (StringUtils.isBlank(pixelsPerUnitXAxisAttribute)){\n \t\tthrow new Exception(\"Invalid SketchyImage file. It must contain 'pixelsPerUnitXAxis' MetaData!\");\n\t }\n \tif (StringUtils.isBlank(pixelsPerUnitYAxisAttribute)){\n \t\tthrow new Exception(\"Invalid SketchyImage file. It must contain 'pixelsPerUnitYAxis' MetaData!\");\n\t }\n \t\n \tint pixelsPerUnitXAxis;\n \ttry{\n \t\tpixelsPerUnitXAxis = Integer.parseInt(pixelsPerUnitXAxisAttribute);\n \t\tif (pixelsPerUnitXAxis<=0) throw new Exception(\"Value must be > 0\");\n \t} catch (Exception e){\n \t\tthrow new Exception(\"Invalid 'pixelsPerUnitXAxis' MetaData Attribute! \" + e.getMessage());\n \t}\n \t\n \tint pixelsPerUnitYAxis;\n \ttry{\n \t\tpixelsPerUnitYAxis = Integer.parseInt(pixelsPerUnitYAxisAttribute);\n \t\tif (pixelsPerUnitYAxis<=0) throw new Exception(\"Value must be > 0\");\n \t} catch (Exception e){\n \t\tthrow new Exception(\"Invalid 'pixelsPerUnitYAxis' MetaData Attribute! \" + e.getMessage());\n \t}\n \t\n \t// We successfully processed the MetaData.. now read/set the image \n \tBufferedImage bufferedImage = imageReader.read(0); // always get first image\n\n \tdouble xPixelsPerMM = pixelsPerUnitXAxis/1000.0;\n \tdouble yPixelsPerMM = pixelsPerUnitYAxis/1000.0;\n \t\n \tsketchyImage = new SketchyImage(bufferedImage, xPixelsPerMM, yPixelsPerMM);\n\t } catch (Exception e){\n\t \tthrow new Exception(\"Error Loading SketchyImage File: \" + file.getPath() + \"! \" + e.getMessage());\n\t } finally {\n\t \tIOUtils.closeQuietly(is);\n\t } \n\t\t\n\t\treturn sketchyImage;\n\t}\n\t\n\tpublic boolean[][] toBooleanBitmapArray(int x, int y, int width, int height) throws Exception {\n\t byte[] buffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();\n\t boolean[][] ret = new boolean[width][height];\n\t int imageWidth=image.getWidth();\n\t \n\t for (int yIdx=0;yIdx<height;yIdx++){\n\t \tint yOffset=yIdx*imageWidth;\n\t \tfor (int xIdx=0;xIdx<width;xIdx++){\n\t\t \tret[xIdx][yIdx] = buffer[yOffset+xIdx]==0;\n\t\t }\n\t }\n\n\t return ret;\n }\n\t\n\tpublic static BufferedImage createByteImage(int width, int height){\n\t\tIndexColorModel model = new IndexColorModel(8,2,new byte[]{0,(byte)255}, new byte[]{0,(byte)255}, new byte[]{0,(byte)255});\n\t\treturn new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED, model);\t\t\n\t}\n\t\n\tpublic static BufferedImage toByteImage(BufferedImage image) {\n\t\tBufferedImage newImage = createByteImage(image.getWidth(), image.getHeight());\n\t\tGraphics2D graphics = newImage.createGraphics();\n\t\tgraphics.setBackground(Color.white);\n\t\tgraphics.fillRect(0, 0, image.getWidth(), image.getHeight());\n\t\tgraphics.drawImage(image, 0, 0, null);\n\t\treturn newImage;\n\t}\n\t\n\t\n\tpublic boolean[][] toBooleanBitmapArray(int blackValue) throws Exception {\n\t\treturn toBooleanBitmapArray(0,0, image.getWidth(), image.getHeight());\n }\n\t\n}" ]
import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.image.AreaAveragingScaleFilter; import java.awt.image.BufferedImage; import java.awt.image.FilteredImageSource; import java.awt.image.ImageProducer; import java.io.File; import javax.imageio.ImageIO; import marvin.image.MarvinImage; import marvin.image.MarvinImageMask; import marvin.plugin.MarvinImagePlugin; import marvin.util.MarvinPluginLoader; import org.apache.commons.io.FileUtils; import com.sketchy.drawing.DrawingSize; import com.sketchy.image.RenderedImageAttributes.CenterOption; import com.sketchy.image.RenderedImageAttributes.FlipOption; import com.sketchy.image.RenderedImageAttributes.RenderOption; import com.sketchy.image.RenderedImageAttributes.RotateOption; import com.sketchy.image.RenderedImageAttributes.ScaleOption; import com.sketchy.server.HttpServer; import com.sketchy.utils.image.SketchyImage;
plugin.setAttribute("brightness", brightnessValue); plugin.setAttribute("contrast", contrastValue); plugin.process(image,image,null,MarvinImageMask.NULL_MASK, false); image.update(); bufferedImage = image.getBufferedImage(); } if (cancel){ throw new CancelledException(); } progress=30; if ((renderedImageAttributes.isInvertImage())){ statusMessage = "Inverting Image"; MarvinImage image = new MarvinImage(bufferedImage); MarvinImagePlugin plugin = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.invert.jar"); if (plugin==null){ throw new Exception("Error loading Marvin Invert Image Plugin!"); } plugin.process(image,image,null,MarvinImageMask.NULL_MASK, false); image.update(); bufferedImage = image.getBufferedImage(); } if (cancel){ throw new CancelledException(); } progress=35; if (renderedImageAttributes.getRotateOption()!=RotateOption.ROTATE_NONE){ statusMessage = "Rotating Image"; bufferedImage = rotateImage(bufferedImage, renderedImageAttributes.getRotateOption()); } if (cancel){ throw new CancelledException(); } progress=40; if (renderedImageAttributes.getFlipOption()!=FlipOption.FLIP_NONE){ statusMessage = "Flipping Image"; bufferedImage = flipImage(bufferedImage, renderedImageAttributes.getFlipOption()); } if (cancel){ throw new CancelledException(); } progress=50; if (renderedImageAttributes.getRenderOption()==RenderOption.RENDER_EDGE_DETECTION){ statusMessage = "Processing Edge Detection"; MarvinImage image = new MarvinImage(bufferedImage); MarvinImagePlugin plugin = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.edgeDetector.jar"); if (plugin==null){ throw new Exception("Error loading Marvin EdgeDetector Plugin!"); } plugin.process(image,image,null,MarvinImageMask.NULL_MASK, false); image.update(); bufferedImage = image.getBufferedImage(); } int drawingWidth = (int) Math.ceil(drawingSize.getWidth()*dotsPerMM); int drawingHeight = (int) Math.ceil(drawingSize.getHeight()*dotsPerMM); if (cancel){ throw new CancelledException(); } progress=55; statusMessage = "Scaling Image"; bufferedImage = resizeImage(bufferedImage, drawingWidth, drawingHeight, renderedImageAttributes.getCenterOption(), renderedImageAttributes.getScaleOption()); if (cancel){ throw new CancelledException(); } progress=60; if (renderedImageAttributes.getRenderOption()==RenderOption.RENDER_HALFTONE){ statusMessage = "Processing Halftone"; MarvinImage image = new MarvinImage(bufferedImage); MarvinImagePlugin plugin = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion.jar"); if (plugin==null){ throw new Exception("Error loading Marvin Halftone Plugin!"); } plugin.process(image,image,null,MarvinImageMask.NULL_MASK, false); image.update(); bufferedImage = image.getBufferedImage(); } if (cancel){ throw new CancelledException(); } progress=65; if ((renderedImageAttributes.getThreshold()!=50) && (renderedImageAttributes.getRenderOption()!=RenderOption.RENDER_HALFTONE)){ statusMessage = "Processing Threshold"; MarvinImage image = new MarvinImage(bufferedImage); MarvinImagePlugin plugin = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.thresholding.jar"); if (plugin==null){ throw new Exception("Error loading Marvin Threshold Plugin!"); } // Range is 0 to 256.. convert from 0 - 100 int thresholdValue = (256-(int)(renderedImageAttributes.getThreshold()*2.56)); plugin.setAttribute("threshold", thresholdValue); plugin.process(image,image,null,MarvinImageMask.NULL_MASK, false); image.update(); bufferedImage = image.getBufferedImage(); } if (cancel){ throw new CancelledException(); } statusMessage = "Saving Rendered Image"; File renderedFile = HttpServer.getUploadFile(renderedImageAttributes.getImageFilename()); renderedImageAttributes.setWidth(bufferedImage.getWidth()); renderedImageAttributes.setHeight(bufferedImage.getHeight()); progress=70;
SketchyImage sketchyImage = new SketchyImage(bufferedImage, dotsPerMM, dotsPerMM);
7
PathwayAndDataAnalysis/causalpath
src/main/java/org/panda/causalpath/run/TCGARecurrentCorrelationRun.java
[ "public class CausalitySearcher implements Cloneable\n{\n\t/**\n\t * If that is false, then we are interested in conflicting relations.\n\t */\n\tprivate int causal;\n\n\t/**\n\t * If this is false, then we don't care if the target site of a relation and the site on the data matches.\n\t */\n\tprivate boolean forceSiteMatching;\n\n\t/**\n\t * When site matching is on, this parameter determines the largest value of the mismatch between relation and data\n\t * to consider it as a match. Set this to 0 for the most strict match.\n\t */\n\tprivate int siteProximityThreshold;\n\n\t/**\n\t * When this is true, the data whose effect is 0, but potentially can be part of the causal network if known, are\n\t * collected.\n\t */\n\tboolean collectDataWithMissingEffect;\n\n\t/**\n\t * The interesting subset of phosphorylation data with unknown effect.\n\t */\n\tprivate Set<SiteModProteinData> dataNeedsAnnotation;\n\n\t/**\n\t * When this is true, the data that are used for inference of causality or conflict are saved in a set.\n\t */\n\tboolean collectDataUsedForInference;\n\n\t/**\n\t * The set of data that is used during inference of causality.\n\t */\n\tprivate Map<Relation, Set<ExperimentData>> dataUsedForInference;\n\n\t/**\n\t * Set of pairs of data that contributed to inference.\n\t */\n\tprivate Map<Relation, Set<List<ExperimentData>>> pairsUsedForInference;\n\n\t/**\n\t * If true, then an expression relation has to have an Activity data at its source.\n\t */\n\tprotected boolean mandateActivityDataUpstreamOfExpression;\n\n\t/**\n\t * The data types that can be used for evidence of expression change. This is typically protein or rna or both.\n\t */\n\tprotected DataType[] expressionEvidence;\n\n\t/**\n\t * When true, this class uses only the strongest changing proteomic data with known effect as general activity\n\t * evidence.\n\t */\n\tprotected boolean useStrongestProteomicsDataForActivity;\n\n\t/**\n\t * When true, if a node has activity data, other data types are ignored for providing activity evidence.\n\t */\n\tprotected boolean prioritizeActivityData;\n\n\t/**\n\t * Data types that indicate activity change.\n\t */\n\tSet<DataType> generalActivityChangeIndicators;\n\n\t/**\n\t * A graph filter if needed to use at the end of network inference.\n\t */\n\tGraphFilter graphFilter;\n\n\tMap<Relation, Set<ExperimentData>> affectingSourceDataMap;\n\tMap<Relation, Set<ExperimentData>> explainableTargetDataMap;\n\n\t/**\n\t * Constructor with the reasoning type.\n\t * @param causal true:causal, false:conflicting\n\t */\n\tpublic CausalitySearcher(boolean causal)\n\t{\n\t\tsetCausal(causal);\n\t\tthis.forceSiteMatching = true;\n\t\tthis.siteProximityThreshold = 0;\n\t\tthis.collectDataWithMissingEffect = true;\n\t\tthis.collectDataUsedForInference = true;\n\t\tthis.mandateActivityDataUpstreamOfExpression = false;\n\t\tthis.useStrongestProteomicsDataForActivity = false;\n\n\t\tthis.generalActivityChangeIndicators = new HashSet<>(Arrays.asList(DataType.PROTEIN, DataType.PHOSPHOPROTEIN,\n\t\t\tDataType.ACETYLPROTEIN, DataType.METHYLPROTEIN, DataType.METABOLITE, DataType.ACTIVITY));\n\t}\n\n\tpublic void initRelationDataMappingMemory()\n\t{\n\t\tthis.affectingSourceDataMap = new HashMap<>();\n\t\tthis.explainableTargetDataMap = new HashMap<>();\n\t}\n\n\tpublic CausalitySearcher copy()\n\t{\n\t\ttry\n\t\t{\n\t\t\tCausalitySearcher cs = (CausalitySearcher) this.clone();\n\t\t\tcs.pairsUsedForInference = null;\n\t\t\tcs.dataUsedForInference = null;\n\t\t\tcs.dataNeedsAnnotation = null;\n\t\t\tcs.generalActivityChangeIndicators = new HashSet<>(generalActivityChangeIndicators);\n\t\t\tcs.setCollectDataUsedForInference(false);\n\t\t\tcs.setCollectDataWithMissingEffect(false);\n\t\t\treturn cs;\n\t\t}\n\t\tcatch (CloneNotSupportedException e)\n\t\t{\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Finds compatible or conflicting relations. The relations have to be associated with experiment data. Both the\n\t * experiment data and the relations have to be associated with related change detectors.\n\t */\n\tpublic Set<Relation> run(Set<Relation> relations)\n\t{\n//\t\tprintSizeOfRelationsBetweenSignificantData(relations);\n\n\t\t// Initialize collections\n\n\t\tif (collectDataWithMissingEffect)\n\t\t{\n\t\t\tif (dataNeedsAnnotation == null) dataNeedsAnnotation = new HashSet<>();\n\t\t\telse dataNeedsAnnotation.clear();\n\t\t}\n\t\tif (collectDataUsedForInference)\n\t\t{\n\t\t\tif (dataUsedForInference == null)\n\t\t\t{\n\t\t\t\tdataUsedForInference = new HashMap<>();\n\t\t\t\tpairsUsedForInference = new HashMap<>();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdataUsedForInference.clear();\n\t\t\t\tpairsUsedForInference.clear();\n\t\t\t}\n\t\t}\n\n\t\t// This is where magic happens\n\t\tSet<Relation> results = relations.stream().filter(this::satisfiesCriteria).collect(Collectors.toSet());\n\n\t\t// If a subset of the results is desired, trim it\n\t\tif (graphFilter != null)\n\t\t{\n\t\t\tresults = graphFilter.postAnalysisFilter(results);\n\n\t\t\t// remove unnecessary entries in the collected data\n\t\t\tif (collectDataUsedForInference)\n\t\t\t{\n\t\t\t\tSet<Relation> removedRels = new HashSet<>(dataUsedForInference.keySet());\n\t\t\t\tremovedRels.removeAll(results);\n\t\t\t\tremovedRels.forEach(r ->\n\t\t\t\t{\n\t\t\t\t\tdataUsedForInference.remove(r);\n\t\t\t\t\tpairsUsedForInference.remove(r);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Checks if the relation explains/conflicts the associated data.\n\t * @param relation relation to check\n\t * @return true if explanatory\n\t */\n\tpublic boolean satisfiesCriteria(Relation relation)\n\t{\n\t\t// Get data of target gene this relation can explain the change\n\t\tif (explainableTargetDataMap != null && !explainableTargetDataMap.containsKey(relation))\n\t\t\texplainableTargetDataMap.put(relation, getExplainableTargetDataWithSiteMatch(relation));\n\n\t\tSet<ExperimentData> td = explainableTargetDataMap == null ?\n\t\t\tgetExplainableTargetDataWithSiteMatch(relation) : explainableTargetDataMap.get(relation);\n\n\t\tif (!td.isEmpty())\n\t\t{\n\t\t\t// Get data of the source gene that can be cause of this relation\n\t\t\tif (affectingSourceDataMap != null && !affectingSourceDataMap.containsKey(relation))\n\t\t\t\taffectingSourceDataMap.put(relation, getAffectingSourceData(relation));\n\n\t\t\tSet<ExperimentData> sd = affectingSourceDataMap == null ?\n\t\t\t\tgetAffectingSourceData(relation) : affectingSourceDataMap.get(relation);\n\n\t\t\tif (!sd.isEmpty())\n\t\t\t{\n\t\t\t\treturn satisfiesCriteria(sd, relation, td);\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if the relation has potential to explain/conflict with the associated data to source and targets, but\n\t * without evaluating data values.\n\t *\n\t * @param relation relation to check\n\t * @return true if the relation has considerable data at both sides\n\t */\n\tpublic boolean hasConsiderableDownstreamData(Relation relation)\n\t{\n\t\treturn !getExplainableTargetDataWithSiteMatch(relation).isEmpty();\n\t}\n\n\t/**\n\t * Checks if the relation has potential to explain/conflict with the associated data to source and targets, but\n\t * without evaluating data values.\n\t *\n\t * @param relation relation to check\n\t * @return true if the relation has considerable data at both sides\n\t */\n\tpublic boolean hasConsiderableData(Relation relation)\n\t{\n\t\tif (hasConsiderableDownstreamData(relation))\n\t\t{\n\t\t\t// Get data of the source gene that can be cause of this relation\n\t\t\tSet<ExperimentData> sd = getAffectingSourceData(relation);\n\t\t\treturn !sd.isEmpty();\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if any pair from the given source and target data can be explained by the given relation.\n\t * @param sd source data\n\t * @param rel the relation\n\t * @param td target data\n\t * @return true if any sd td pair is explained/conflicted by the given relation\n\t */\n\tprivate boolean satisfiesCriteria(Set<ExperimentData> sd, Relation rel, Set<ExperimentData> td)\n\t{\n\t\tboolean satisfies = false;\n\n\t\tfor (ExperimentData sourceData : sd)\n\t\t{\n\t\t\tfor (ExperimentData targetData : td)\n\t\t\t{\n\t\t\t\tif (satisfiesCriteria(rel, sourceData, targetData))\n\t\t\t\t{\n\t\t\t\t\tsatisfies = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn satisfies;\n\t}\n\n\t/**\n\t * Checks if the relation can explain/conflict the given source target data pair.\n\t * @param rel the relation\n\t * @param sourceData the source data\n\t * @param targetData the target data\n\t * @return true if the relation can explain/conflict the given data pair\n\t */\n\tprivate boolean satisfiesCriteria(Relation rel, ExperimentData sourceData, ExperimentData targetData)\n\t{\n\t\tint e = rel.chDet.getChangeSign(sourceData, targetData) * rel.getSign();\n\n\t\tif (e != 0 && collectDataWithMissingEffect && sourceData.getEffect() == 0)\n\t\t{\n\t\t\tdataNeedsAnnotation.add((SiteModProteinData) sourceData);\n\t\t}\n\t\telse if (sourceData.getEffect() * e == causal)\n\t\t{\n\t\t\tif (collectDataUsedForInference)\n\t\t\t{\n\t\t\t\tif (!dataUsedForInference.containsKey(rel))\n\t\t\t\t{\n\t\t\t\t\tdataUsedForInference.put(rel, new HashSet<>());\n\t\t\t\t\tpairsUsedForInference.put(rel, new HashSet<>());\n\t\t\t\t}\n\n\t\t\t\tdataUsedForInference.get(rel).add(sourceData);\n\t\t\t\tdataUsedForInference.get(rel).add(targetData);\n\t\t\t\tpairsUsedForInference.get(rel).add(Arrays.asList(sourceData, targetData));\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Gets the source data that match with the given relation and target data.\n\t * @param rel the relation\n\t * @param target target data\n\t * @return the set of matching source data\n\t */\n\tpublic Set<ExperimentData> getSatisfyingSourceData(Relation rel, ExperimentData target)\n\t{\n\t\treturn getAffectingSourceData(rel).stream()\n\t\t\t.filter(source -> satisfiesCriteria(rel, source, target))\n\t\t\t.collect(Collectors.toSet());\n\t}\n\n\t/**\n\t * Gets the set of target data that the given relation can potentially explain its change. but that is without\n\t * checking the value changes, only by data types.\n\t * @param rel the relation\n\t * @return the set of target data explainable by the relation\n\t */\n\tpublic Set<ExperimentData> getExplainableTargetData(Relation rel)\n\t{\n\t\tif (rel.type.affectsPhosphoSite)\n\t\t{\n\t\t\treturn getEvidenceForPhosphoChange(rel.targetData);\n\t\t}\n\t\telse if (rel.type.affectsTotalProt)\n\t\t{\n\t\t\treturn getEvidenceForExpressionChange(rel.targetData);\n\t\t}\n\t\telse if (rel.type.affectsGTPase)\n\t\t{\n\t\t\treturn getEvidenceForGTPaseChange(rel.targetData);\n\t\t}\n\t\telse if (rel.type.affectsAcetylSite)\n\t\t{\n\t\t\treturn getEvidenceForAcetylChange(rel.targetData);\n\t\t}\n\t\telse if (rel.type.affectsMethlSite)\n\t\t{\n\t\t\treturn getEvidenceForMethylChange(rel.targetData);\n\t\t}\n\t\telse if (rel.type.affectsMetabolite)\n\t\t{\n\t\t\treturn getEvidenceForMetaboliteChange(rel.targetData);\n\t\t}\n\n\t\tthrow new RuntimeException(\"Code should not reach here. Is there a new relation type to handle?\");\n\t}\n\n\t/**\n\t * Gets the set of target data that the given relation can potentially explain its change. That is without\n\t * checking the value changes, but site matching (if relevant) is evaluated.\n\t * @param rel the relation\n\t * @return the set of target data explainable by the relation\n\t */\n\tpublic Set<ExperimentData> getExplainableTargetDataWithSiteMatch(Relation rel)\n\t{\n\t\tSet<ExperimentData> datas = getExplainableTargetData(rel);\n\n\t\treturn datas.stream().filter(d -> !(d instanceof SiteModProteinData) ||\n\t\t\tisTargetSiteCompatible(rel, (SiteModProteinData) d)).collect(Collectors.toSet());\n\t}\n\n\n\t/**\n\t * Checks if target sites match for the relation and the data.\n\t * @param rel the relation\n\t * @param target target data\n\t * @return true if there is a match or no match needed\n\t */\n\tpublic boolean isTargetSiteCompatible(Relation rel, SiteModProteinData target)\n\t{\n\t\treturn !forceSiteMatching || !CollectionUtil.intersectionEmpty(\n\t\t\t\trel.getTargetWithSites(siteProximityThreshold), target.getGenesWithSites());\n\t}\n\n\t/**\n\t * Gets the source data that can be cause of this relation. This is without checking any change in values, only by\n\t * data types.\n\t * @param rel the relation\n\t * @return the set of source data that can be affecting\n\t */\n\tpublic Set<ExperimentData> getAffectingSourceData(Relation rel)\n\t{\n\t\tif (rel.type.affectsPhosphoSite || rel.type.affectsAcetylSite || rel.type.affectsMethlSite)\n\t\t{\n\t\t\treturn getUpstreamEvidenceForSiteSpecificChange(rel.sourceData);\n\t\t}\n\t\telse if (rel.type.affectsTotalProt)\n\t\t{\n\t\t\treturn getUpstreamEvidenceForExpressionChange(rel.sourceData);\n\t\t}\n\t\telse if (rel.type.affectsGTPase)\n\t\t{\n\t\t\treturn getUpstreamEvidenceForGTPaseChange(rel.sourceData);\n\t\t}\n\t\telse if (rel.type.affectsMetabolite)\n\t\t{\n\t\t\treturn getUpstreamEvidenceForMetaboliteChange(rel.sourceData);\n\t\t}\n\n\t\tthrow new RuntimeException(\"Code should not reach here. There must be a new relation type to handle.\");\n\t}\n\n\t/**\n\t * Gets the evidence for activity change of a gene in terms of the associated data. This method does not evaluate a\n\t * change in values but only assesses the valid data types.\n\t * @param gene the gene\n\t * @return the data with potential to indicate activity change\n\t */\n\tpublic Set<ExperimentData> getGeneralActivationEvidence(GeneWithData gene)\n\t{\n\t\tSet<ExperimentData> set = new HashSet<>();\n\n\t\tfor (DataType type : generalActivityChangeIndicators)\n\t\t{\n\t\t\tset.addAll(gene.getData(type));\n\t\t}\n\n\t\tset = set.stream().filter(d -> d.getEffect() != 0).collect(Collectors.toSet());\n\n\t\tif (useStrongestProteomicsDataForActivity)\n\t\t{\n\t\t\tremoveShadowedProteomicData(set);\n\t\t}\n\n\t\tif (prioritizeActivityData)\n\t\t{\n\t\t\tremoveOtherDataIfActivityDataIsPresent(set);\n\t\t}\n\n\t\treturn set;\n\t}\n\n\tpublic Set<ExperimentData> getUpstreamEvidenceForSiteSpecificChange(GeneWithData gene)\n\t{\n\t\treturn getGeneralActivationEvidence(gene);\n\t}\n\n\tpublic Set<ExperimentData> getUpstreamEvidenceForExpressionChange(GeneWithData gene)\n\t{\n\t\tif (mandateActivityDataUpstreamOfExpression) return gene.getData(DataType.ACTIVITY);\n\t\telse return getGeneralActivationEvidence(gene);\n\t}\n\n\tpublic Set<ExperimentData> getUpstreamEvidenceForGTPaseChange(GeneWithData gene)\n\t{\n\t\treturn getGeneralActivationEvidence(gene);\n\t}\n\n\tpublic Set<ExperimentData> getUpstreamEvidenceForMetaboliteChange(GeneWithData gene)\n\t{\n\t\treturn getGeneralActivationEvidence(gene);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForPhosphoChange(GeneWithData gene)\n\t{\n\t\treturn gene.getData(DataType.PHOSPHOPROTEIN);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForExpressionChange(GeneWithData gene)\n\t{\n\t\tif (expressionEvidence != null) return gene.getData(expressionEvidence);\n\t\treturn gene.getData(DataType.PROTEIN);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForGTPaseChange(GeneWithData gene)\n\t{\n\t\treturn gene.getData(DataType.ACTIVITY);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForAcetylChange(GeneWithData gene)\n\t{\n\t\treturn gene.getData(DataType.ACETYLPROTEIN);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForMethylChange(GeneWithData gene)\n\t{\n\t\treturn gene.getData(DataType.METHYLPROTEIN);\n\t}\n\n\tpublic Set<ExperimentData> getEvidenceForMetaboliteChange(GeneWithData gene)\n\t{\n\t\treturn gene.getData(DataType.METABOLITE);\n\t}\n\n\n\t/**\n\t * This method iterates over total protein and phosphoprotein data that has a known effect, and leaves only the one\n\t * with the biggest change, removes others. This is sometimes useful for complexity management.\n\t * @param data data to select from\n\t */\n\tprotected void removeShadowedProteomicData(Set<ExperimentData> data)\n\t{\n\t\tif (data.size() > 1)\n\t\t{\n\t\t\tOptional<ProteinData> opt = data.stream().filter(d -> d instanceof ProteinData && d.getEffect() != 0)\n\t\t\t\t.map(d -> (ProteinData) d).sorted((d1, d2) ->\n\t\t\t\t\tDouble.compare(Math.abs(d2.getChangeValue()), Math.abs(d1.getChangeValue()))).findFirst();\n\n\t\t\tif (opt.isPresent())\n\t\t\t{\n\t\t\t\tExperimentData ed = opt.get();\n\t\t\t\tdata.removeIf(d -> d instanceof ProteinData && d != ed);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void removeOtherDataIfActivityDataIsPresent(Set<ExperimentData> data)\n\t{\n\t\tif (data.stream().anyMatch(d -> d instanceof ActivityData))\n\t\t{\n\t\t\tdata.retainAll(data.stream().filter(d -> d instanceof ActivityData).collect(Collectors.toSet()));\n\t\t}\n\t}\n\n\tpublic void writeResults(String filename) throws IOException\n\t{\n\t\tif (pairsUsedForInference.isEmpty()) return;\n\n\t\tTwoDataChangeDetector relDet = pairsUsedForInference.keySet().iterator().next().chDet;\n\t\tCorrelationDetector corDet = relDet instanceof CorrelationDetector ? (CorrelationDetector) relDet : null;\n\n\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(filename));\n\t\twriter.write(\"Source\\tRelation\\tTarget\\tSites\\t\");\n\t\tif (corDet != null) writer.write(\"Source data ID\\tTarget data ID\\tCorrelation\\tCorrelation pval\");\n\t\telse writer.write(\"Source data ID\\tSource change\\t Source change pval\\tTarget data ID\\tTarget change\\tTarget change pval\");\n\n\t\tpairsUsedForInference.keySet().stream().\n\t\t\tsorted(Comparator.comparing(this::getRelationScore).reversed()). // Sort relations to their significance\n\t\t\tforEach(r -> pairsUsedForInference.get(r).stream().forEach(pair ->\n\t\t{\n\t\t\tIterator<ExperimentData> iter = pair.iterator();\n\t\t\tExperimentData sourceData = iter.next();\n\t\t\tExperimentData targetData = iter.next();\n\n\t\t\tFileUtil.lnwrite(r.source + \"\\t\" + r.type.getName() + \"\\t\" + r.target + \"\\t\" + r.getSitesInString() + \"\\t\", writer);\n\n\t\t\tif (corDet != null)\n\t\t\t{\n\t\t\t\tTuple t = corDet.calcCorrelation(sourceData, targetData);\n\t\t\t\tFileUtil.write(sourceData.getId() + \"\\t\" + targetData.getId() + \"\\t\" + t.v + \"\\t\" + t.p, writer);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tOneDataChangeDetector sDet = sourceData.getChDet();\n\t\t\t\tOneDataChangeDetector tDet = targetData.getChDet();\n\n\t\t\t\tFileUtil.write(sourceData.getId() + \"\\t\" + sourceData.getChangeValue() + \"\\t\" +\n\t\t\t\t\t(sDet instanceof SignificanceDetector ? ((SignificanceDetector) sDet).getPValue(sourceData) : \"\") + \"\\t\", writer);\n\n\t\t\t\tFileUtil.write(targetData.getId() + \"\\t\" + targetData.getChangeValue() + \"\\t\" +\n\t\t\t\t\t(tDet instanceof SignificanceDetector ? ((SignificanceDetector) tDet).getPValue(targetData) : \"\"), writer);\n\t\t\t}\n\t\t}));\n\t\twriter.close();\n\t}\n\n\t/**\n\t * We want to sort the result rows according the their significance. This method generates a score for each relation\n\t * so that we can sort them using that score.\n\t */\n\tprivate double getRelationScore(Relation r)\n\t{\n\t\tdouble max = -Double.MAX_VALUE;\n\t\tSet<List<ExperimentData>> pairs = pairsUsedForInference.get(r);\n\t\tfor (List<ExperimentData> pair : pairs)\n\t\t{\n\t\t\tExperimentData src = pair.get(0);\n\t\t\tExperimentData tgt = pair.get(1);\n\n\t\t\tdouble val;\n\n\t\t\tif (r.chDet instanceof CorrelationDetector)\n\t\t\t{\n\t\t\t\tval = -((CorrelationDetector) r.chDet).calcCorrelation(src, tgt).p;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tOneDataChangeDetector sDet = src.getChDet();\n\t\t\t\tOneDataChangeDetector tDet = tgt.getChDet();\n\n\t\t\t\tif (sDet instanceof SignificanceDetector || tDet instanceof SignificanceDetector)\n\t\t\t\t{\n\t\t\t\t\tdouble vS = sDet instanceof SignificanceDetector ? ((SignificanceDetector) sDet).getPValue(src) : 0;\n\t\t\t\t\tdouble vT = tDet instanceof SignificanceDetector ? ((SignificanceDetector) tDet).getPValue(tgt) : 0;\n\t\t\t\t\tval = -Math.max(vS, vT);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tval = Math.min(Math.abs(sDet.getChangeValue(src)), Math.abs(tDet.getChangeValue(tgt)));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (val > max) max = val;\n\t\t}\n\t\treturn max;\n\t}\n\n\tpublic void setCausal(boolean causal)\n\t{\n\t\tthis.causal = causal ? 1 : -1;\n\t}\n\n\tpublic Set<SiteModProteinData> getDataNeedsAnnotation()\n\t{\n\t\treturn dataNeedsAnnotation;\n\t}\n\n\tpublic Set<ExperimentData> getDataUsedForInference()\n\t{\n\t\treturn dataUsedForInference.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());\n\t}\n\n\tpublic Set<List<ExperimentData>> getPairsUsedForInference()\n\t{\n\t\treturn pairsUsedForInference.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());\n\t}\n\n\t//--DEBUG----------\n\tpublic void writePairsUsedForInferenceWithCorrelations(String file)\n\t{\n\t\ttry\n\t\t{\n\t\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(file));\n\t\t\tSet<List<ExperimentData>> pairs = getPairsUsedForInference();\n\n\t\t\tCorrelationDetector cd = new CorrelationDetector(-1, 1);\n\t\t\tMap<String, Double> pvals = new HashMap<>();\n\n\t\t\tfor (List<ExperimentData> pair : pairs)\n\t\t\t{\n\t\t\t\tIterator<ExperimentData> iter = pair.iterator();\n\t\t\t\tExperimentData data1 = iter.next();\n\t\t\t\tExperimentData data2 = iter.next();\n\n\t\t\t\tTuple corr = cd.calcCorrelation(data1, data2);\n\t\t\t\tif (!corr.isNaN())\n\t\t\t\t{\n\t\t\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\t\t\tpair.stream().sorted(Comparator.comparing(ExperimentData::getId))\n\t\t\t\t\t\t.forEach(e -> sb.append(e.getId()).append(\":\"));\n\t\t\t\t\tString id = sb.toString();\n\n\t\t\t\t\tpvals.put(id, corr.p);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpvals.forEach((s, p) -> FileUtil.writeln(s + \"\\t\" + p, writer));\n\n\t\t\twriter.close();\n\t\t}\n\t\tcatch (IOException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\tpublic void printSizeOfRelationsBetweenSignificantData(Set<Relation> relations)\n\t{\n\t\tSet<Relation> rels = relations.stream().filter(r -> r.sourceData.getDataStream().anyMatch(d -> d.getChangeSign() != 0) &&\n\t\t\tr.targetData.getDataStream().anyMatch(d -> d.getChangeSign() != 0)).collect(Collectors.toSet());\n\t\tSystem.out.println(\"rels between sig data = \" + rels.size());\n\t\tlong protCnt = rels.stream().map(r -> Arrays.asList(r.source, r.target)).flatMap(Collection::stream).distinct().count();\n\t\tSystem.out.println(\"protCnt = \" + protCnt);\n\t}\n\t//--DEBUG----------\n\n\tpublic Map<Relation, Set<ExperimentData>> getInferenceUnits()\n\t{\n\t\treturn dataUsedForInference;\n\t}\n\n\tpublic void setCollectDataUsedForInference(boolean collect)\n\t{\n\t\tthis.collectDataUsedForInference = collect;\n\t}\n\n\tpublic void setCollectDataWithMissingEffect(boolean collect)\n\t{\n\t\tthis.collectDataWithMissingEffect = collect;\n\t}\n\n\tpublic void setMandateActivityDataUpstreamOfExpression(boolean mandate)\n\t{\n\t\tthis.mandateActivityDataUpstreamOfExpression = mandate;\n\t}\n\n\tpublic void setUseStrongestProteomicsDataForActivity(boolean use)\n\t{\n\t\tthis.useStrongestProteomicsDataForActivity = use;\n\t}\n\n\tpublic void setPrioritizeActivityData(boolean prioritizeActivityData)\n\t{\n\t\tthis.prioritizeActivityData = prioritizeActivityData;\n\t}\n\n\tpublic void addDataTypeForGeneralActivity(DataType type)\n\t{\n\t\tgeneralActivityChangeIndicators.add(type);\n\t}\n\n\tpublic void setForceSiteMatching(boolean forceSiteMatching)\n\t{\n\t\tthis.forceSiteMatching = forceSiteMatching;\n\t}\n\n\tpublic void setSiteProximityThreshold(int siteProximityThreshold)\n\t{\n\t\tthis.siteProximityThreshold = siteProximityThreshold;\n\t}\n\n\tpublic void setGraphFilter(GraphFilter graphFilter)\n\t{\n\t\tthis.graphFilter = graphFilter;\n\t}\n\n\tpublic boolean hasNoGraphFilter()\n\t{\n\t\treturn graphFilter == null;\n\t}\n\n\tpublic GraphFilter getGraphFilter()\n\t{\n\t\treturn graphFilter;\n\t}\n\n\tpublic void setExpressionEvidence(DataType... types)\n\t{\n\t\texpressionEvidence = types;\n\t}\n\n\t/**\n\t * This method is experimental, only to test how good is RNA expression as a proxy to protein activity. It is not\n\t * meant to be used in a regular CausalPath analysis.\n\t */\n\tpublic void useExpressionForActivity()\n\t{\n\t\tthis.generalActivityChangeIndicators = new HashSet<>(Collections.singletonList(DataType.RNA));\n\t}\n}", "public class GraphWriter\n{\n\t/**\n\t * Border color of activating phosphorylations or mutations.\n\t */\n\tprivate Color activatingBorderColor;\n\t/**\n\t * Border color of inhibiting phosphorylations or mutations.\n\t */\n\tprivate Color inhibitingBorderColor;\n\n\t/**\n\t * This color is used when the downstream of a gene suggest it is activated and inhibited at the same time.\n\t */\n\tprivate Color doubleSignificanceBorderColor;\n\n\t/**\n\t * Border color of nodes and phosphosites when their activating/inactivating status is not known, or their\n\t * activated/inactivated status is not significant.\n\t */\n\tprivate Color defaultBorderColor;\n\n\t/**\n\t * Parameter to use gene background to display the total protein change. If false, then it is displayed on the gene\n\t * node as a separate feature.\n\t */\n\tprivate boolean useGeneBGForTotalProtein;\n\n\t/**\n\t * The most intense color to show downregulation.\n\t */\n\tprivate Color maxDownColor;\n\n\t/**\n\t * The most intense color to show upregulation.\n\t */\n\tprivate Color maxUpColor;\n\n\t/**\n\t * The value where the most intense colors are reached. If a value is more extreme than this value, it will be\n\t * shown with the most intense color, and would be considered \"saturated\".\n\t */\n\tprivate double colorSaturationValue;\n\n\t/**\n\t * An object that can produce a color for a given up/downregulation value.\n\t */\n\tprivate ValToColor vtc;\n\n\t/**\n\t * The set of relations with the associated data to draw.\n\t */\n\tprivate Set<Relation> relations;\n\n\tprivate NetworkSignificanceCalculator nsc;\n\n\tprivate Set<ExperimentData> experimentDataToDraw;\n\n\tprivate Set<GeneWithData> otherGenesToShow;\n\n\tprivate boolean showInsignificantData = false;\n\n\t/**\n\t * Constructor with the relations. Those relations are the result of the causality search.\n\t */\n\tpublic GraphWriter(Set<Relation> relations)\n\t{\n\t\tthis(relations, null);\n\t}\n\n\t/**\n\t * Constructor with the relations and significance calculation results.\n\t * Those relations are the result of the causality search.\n\t */\n\tpublic GraphWriter(Set<Relation> relations, NetworkSignificanceCalculator nsc)\n\t{\n\t\tthis.relations = relations;\n\t\tactivatingBorderColor = new Color(0, 180, 20);\n\t\tinhibitingBorderColor = new Color(180, 0, 20);\n\t\tdoubleSignificanceBorderColor = new Color(150, 150, 0);\n\t\tdefaultBorderColor = new Color(50, 50, 50);\n\n\t\tmaxDownColor = new Color(40, 80, 255);\n\t\tmaxUpColor = new Color(255, 80, 40);\n\t\tcolorSaturationValue = 1;\n\n\t\tinitColorMapper();\n\n\t\tuseGeneBGForTotalProtein = false;\n\n\t\tthis.nsc = nsc;\n\t}\n\n\t/**\n\t * Saturation color for downregulation.\n\t */\n\tpublic void setMaxDownColor(Color maxDownColor)\n\t{\n\t\tthis.maxDownColor = maxDownColor;\n\t\tinitColorMapper();\n\t}\n\n\t/**\n\t * Saturation color for upregulation.\n\t */\n\tpublic void setMaxUpColor(Color maxUpColor)\n\t{\n\t\tthis.maxUpColor = maxUpColor;\n\t\tinitColorMapper();\n\t}\n\n\t/**\n\t * The value where color saturation occurs. The parameter has to be a positive value. Negative saturation will be\n\t * symmetrical to positive saturation.\n\t */\n\tpublic void setColorSaturationValue(double colorSaturationValue)\n\t{\n\t\tthis.colorSaturationValue = Math.abs(colorSaturationValue);\n\t\tinitColorMapper();\n\t}\n\n\t/**\n\t * Initializes the color mapping object.\n\t */\n\tprivate void initColorMapper()\n\t{\n\t\tvtc = new ValToColor(new double[]{-colorSaturationValue, 0, colorSaturationValue},\n\t\t\tnew Color[]{maxDownColor, Color.WHITE, maxUpColor});\n\t}\n\n\tpublic void setUseGeneBGForTotalProtein(boolean useGeneBGForTotalProtein)\n\t{\n\t\tthis.useGeneBGForTotalProtein = useGeneBGForTotalProtein;\n\t}\n\n\tpublic void setActivatingBorderColor(Color activatingBorderColor)\n\t{\n\t\tthis.activatingBorderColor = activatingBorderColor;\n\t}\n\n\tpublic void setInhibitingBorderColor(Color inhibitingBorderColor)\n\t{\n\t\tthis.inhibitingBorderColor = inhibitingBorderColor;\n\t}\n\n\tpublic void setExpColorSchema(ValToColor vtc)\n\t{\n\t\tthis.vtc = vtc;\n\t}\n\n\tpublic void setExperimentDataToDraw(Set<ExperimentData> experimentDataToDraw)\n\t{\n\t\tthis.experimentDataToDraw = experimentDataToDraw;\n\t}\n\n\tpublic void setOtherGenesToShow(Set<GeneWithData> set)\n\t{\n\t\tthis.otherGenesToShow = set;\n\t}\n\n\tpublic void setShowInsignificantData(boolean showInsignificantData)\n\t{\n\t\tthis.showInsignificantData = showInsignificantData;\n\t}\n\n\t/**\n\t * Produces a causality graph where each node corresponds to a gene. In this graph, data may be displayed more than\n\t * once if they map to more than one gene. The output .sif and .format files can be visualized using ChiBE. From\n\t * ChiBE, do SIF -> Load SIF File ... and select the output .sif file.\n\t */\n\tpublic void writeSIFGeneCentric(String filename) throws IOException\n\t{\n\t\tif (!filename.endsWith(\".sif\")) filename += \".sif\";\n\n\t\t// write relations\n\t\tBufferedWriter writer1 = new BufferedWriter(new FileWriter(filename));\n\t\trelations.stream().distinct().forEach(r -> FileUtil.writeln(r.toString(), writer1));\n\t\tif (otherGenesToShow != null)\n\t\t{\n\t\t\tSet<String> genesInGraph = getGenesInGraph();\n\t\t\totherGenesToShow.stream().filter(g -> !genesInGraph.contains(g.getId())).forEach(g ->\n\t\t\t\tFileUtil.writeln(g.getId(), writer1));\n\t\t}\n\t\twriter1.close();\n\n\t\tSet<String> totalProtUsedUp = new HashSet<>();\n\n\t\tfilename = filename.substring(0, filename.lastIndexOf(\".\")) + \".format\";\n\t\tBufferedWriter writer2 = new BufferedWriter(new FileWriter(filename));\n\t\twriter2.write(\"node\\tall-nodes\\tcolor\\t255 255 255\\n\");\n\t\twriter2.write(\"node\\tall-nodes\\tbordercolor\\t\" + inString(defaultBorderColor) + \"\\n\");\n\n\t\tSet<ExperimentData> dataInGraph = getExperimentDataToDraw();\n\n\t\tdataInGraph.forEach(data ->\n\t\t{\n\t\t\tString colS = \"255 255 255\";\n\n\t\t\tif (data.hasChangeDetector())\n\t\t\t{\n\t\t\t\tif (data.getChangeSign() != 0 || showInsignificantData)\n\t\t\t\t{\n\t\t\t\t\tcolS = vtc.getColorInString(data.getChangeValue());\n\t\t\t\t}\n\t\t\t\telse return;\n\t\t\t}\n\n\t\t\tString bor = inString(defaultBorderColor);\n\t\t\tString let = \"?\";\n\n\t\t\tif (data instanceof SiteModProteinData)\n\t\t\t{\n\t\t\t\tSiteModProteinData pd = (SiteModProteinData) data;\n\t\t\t\tif (pd.getEffect() > 0) bor = inString(activatingBorderColor);\n\t\t\t\telse if (pd.getEffect() < 0) bor = inString(inhibitingBorderColor);\n\n\t\t\t\tlet = pd.getModification().toString().substring(0, 1).toLowerCase();\n\t\t\t}\n\t\t\telse if (data instanceof ProteinData)\n\t\t\t{\n\t\t\t\tlet = \"t\";\n\t\t\t}\n\t\t\telse if (data instanceof MetaboliteData)\n\t\t\t{\n\t\t\t\tlet = \"c\";\n\t\t\t}\n\t\t\telse if (data instanceof MutationData)\n\t\t\t{\n\t\t\t\tlet = \"x\";\n\t\t\t\tif (data.getEffect() == 1)\n\t\t\t\t\tbor = inString(activatingBorderColor);\n\t\t\t\telse bor = inString(inhibitingBorderColor);\n\t\t\t}\n\t\t\telse if (data instanceof CNAData)\n\t\t\t{\n\t\t\t\tlet = \"d\";\n\t\t\t}\n\t\t\telse if (data instanceof RNAData)\n\t\t\t{\n\t\t\t\tlet = \"r\";\n\t\t\t}\n\t\t\telse if (data instanceof ActivityData)\n\t\t\t{\n\t\t\t\tlet = data.getChangeSign() > 0 ? \"!\" : \"i\";\n\t\t\t\tbor = inString(activatingBorderColor);\n\t\t\t}\n\n\t\t\tString siteID = data.id;\n\t\t\tString val = data.hasChangeDetector() ? data.getChangeValue() + \"\" : \"\";\n\n\t\t\tfor (String gene : data.getGeneSymbols())\n\t\t\t{\n\t\t\t\tif (nsc != null)\n\t\t\t\t{\n\t\t\t\t\tif (nsc.isDownstreamSignificant(gene))\n\t\t\t\t\t{\n\t\t\t\t\t\tFileUtil.writeln(\"node\\t\" + gene + \"\\tborderwidth\\t2\", writer2);\n\t\t\t\t\t}\n\t\t\t\t\tboolean act = false;\n\t\t\t\t\tboolean inh = false;\n\n\t\t\t\t\tif (nsc instanceof NSCForComparison)\n\t\t\t\t\t{\n\t\t\t\t\t\tact = ((NSCForComparison) nsc).isActivatingTargetsSignificant(gene);\n\t\t\t\t\t\tinh = ((NSCForComparison) nsc).isInhibitoryTargetsSignificant(gene);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (act && !inh) FileUtil.writeln(\"node\\t\" + gene + \"\\tbordercolor\\t\" + inString(activatingBorderColor), writer2);\n\t\t\t\t\telse if (!act && inh) FileUtil.writeln(\"node\\t\" + gene + \"\\tbordercolor\\t\" + inString(inhibitingBorderColor), writer2);\n\t\t\t\t\telse if (act /* && inh */) FileUtil.writeln(\"node\\t\" + gene + \"\\tbordercolor\\t\" + inString(doubleSignificanceBorderColor), writer2);\n\t\t\t\t\t//else FileUtil.writeln(\"node\\t\" + gene + \"\\tbordercolor\\t\" + inString(defaultBorderColor), writer2);\n\t\t\t\t}\n\n\t\t\t\tif (useGeneBGForTotalProtein && (let.equals(\"t\") || let.equals(\"c\")) && !totalProtUsedUp.contains(gene))\n\t\t\t\t{\n\t\t\t\t\tif (let.equals(\"c\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tFileUtil.writeln(\"node\\t\" + siteID + \"\\tcolor\\t\" + colS, writer2);\n\t\t\t\t\t\tFileUtil.writeln(\"node\\t\" + siteID + \"\\ttooltip\\t\" + gene + \", \" + val, writer2);\n\t\t\t\t\t\ttotalProtUsedUp.add(gene);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tFileUtil.writeln(\"node\\t\" + gene + \"\\tcolor\\t\" + colS, writer2);\n\t\t\t\t\t\tFileUtil.writeln(\"node\\t\" + gene + \"\\ttooltip\\t\" + siteID + \", \" + val, writer2);\n\t\t\t\t\t\ttotalProtUsedUp.add(gene);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tFileUtil.writeln(\"node\\t\" + gene + \"\\trppasite\\t\" + siteID.replaceAll(\"\\\\|\", \"-\") + \"|\" + let + \"|\" + colS + \"|\" + bor +\n\t\t\t\t\t\t\"|\" + val, writer2);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\twriter2.close();\n\t}\n\n\t/**\n\t * Converts color to a string.\n\t */\n\tprivate String inString(Color c)\n\t{\n\t\treturn c.getRed() + \" \" + c.getGreen() + \" \" + c.getBlue();\n\t}\n\n\t/**\n\t * Converts color to a JSON string.\n\t */\n\tprivate String inJSONString(Color c)\n\t{\n\t\treturn \"rgb(\" + c.getRed() + \",\" + c.getGreen() + \",\" + c.getBlue() + \")\";\n\t}\n\n\t/**\n\t * Generates a causality graph where each node is a measurement. In this graph, pathway relations can be displayed\n\t * more than once if the same relation can explain more than one data pairs.\n\t *\n\t * @param filename name of the output sif file\n\t * @param unitsMap The map from the inferred relations to the data that helped the inference.\n\t */\n\tpublic void writeSIFDataCentric(String filename, Map<Relation, Set<ExperimentData>> unitsMap) throws IOException\n\t{\n\t\tif (!filename.endsWith(\".sif\")) filename += \".sif\";\n\n\t\tSet<ExperimentData> used = new HashSet<>();\n\n\t\t// write relations\n\t\tBufferedWriter writer1 = new BufferedWriter(new FileWriter(filename));\n\t\tunitsMap.keySet().forEach(r ->\n\t\t{\n\t\t\tSet<ExperimentData> datas = unitsMap.get(r);\n\t\t\tSet<ExperimentData> sources = r.sourceData.getData().stream().filter(datas::contains)\n\t\t\t\t.collect(Collectors.toSet());\n\t\t\tSet<ExperimentData> targets = r.targetData.getData().stream().filter(datas::contains)\n\t\t\t\t.collect(Collectors.toSet());\n\n\t\t\tfor (ExperimentData source : sources)\n\t\t\t{\n\t\t\t\tfor (ExperimentData target : targets)\n\t\t\t\t{\n\t\t\t\t\tFileUtil.writeln(source.getId() + \"\\t\" + r.type.getName() + \"\\t\" + target.getId(), writer1);\n\t\t\t\t\tused.add(source);\n\t\t\t\t\tused.add(target);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\twriter1.close();\n\n\t\tfilename = filename.substring(0, filename.lastIndexOf(\".\")) + \".format\";\n\t\tBufferedWriter writer2 = new BufferedWriter(new FileWriter(filename));\n\t\twriter2.write(\"node\\tall-nodes\\tcolor\\t255 255 255\\n\");\n\t\tused.stream().forEach(data ->\n\t\t{\n\t\t\tif (data.hasChangeDetector())\n\t\t\t{\n\t\t\t\tFileUtil.writeln(\"node\\t\" + data.getId() + \"\\tcolor\\t\" + vtc.getColorInString(data.getChangeValue()),\n\t\t\t\t\twriter2);\n\t\t\t}\n\t\t\tif (data.getType() == DataType.PHOSPHOPROTEIN && data.getEffect() != 0)\n\t\t\t{\n\t\t\t\tFileUtil.writeln(\"node\\t\" + data.getId() + \"\\tbordercolor\\t\" +\n\t\t\t\t\tinString(data.getEffect() == -1 ? inhibitingBorderColor : activatingBorderColor), writer2);\n\t\t\t}\n\t\t});\n\t\twriter2.close();\n\t}\n\n\t/**\n\t * Writes the graph in JSON format, which can be viewed using the web-based proteomics analysis tool.\n\t */\n\tpublic void writeJSON(String filename) throws IOException\n\t{\n\t\tif (!filename.endsWith(\".json\")) filename += \".json\";\n\n\t\tMap<String, Object> map = new HashMap<>();\n\t\tList<Map> nodes = new ArrayList<>();\n\t\tList<Map> edges = new ArrayList<>();\n\t\tmap.put(\"nodes\", nodes);\n\t\tmap.put(\"edges\", edges);\n\n\t\tMap<String, Map> geneMap = new HashMap<>();\n\t\tSet<String> relMem = new HashSet<>();\n\n\t\trelations.forEach(rel ->\n\t\t{\n\t\t\tString src = rel.source.startsWith(\"CHEBI:\") ? rel.sourceData.getData().iterator().next().getId() : rel.source;\n\t\t\tString tgt = rel.target.startsWith(\"CHEBI:\") ? rel.targetData.getData().iterator().next().getId() : rel.target;\n\t\t\tString key = src + \"\\t\" + rel.type.getName() + \"\\t\" + tgt;\n\t\t\tif (relMem.contains(key)) return;\n\t\t\telse relMem.add(key);\n\n\t\t\tMap<String, Object> edge = new HashMap<>();\n\t\t\tedges.add(edge);\n\t\t\tMap<String, Object> dMap = new HashMap<>();\n\t\t\tedge.put(\"data\", dMap);\n\t\t\tdMap.put(\"source\", src);\n\t\t\tdMap.put(\"target\", tgt);\n\t\t\tdMap.put(\"edgeType\", rel.type.getName());\n\t\t\tdMap.put(\"tooltipText\", CollectionUtil.merge(rel.getTargetWithSites(0), \", \"));\n\n\t\t\tif (rel.getMediators() != null)\n\t\t\t{\n\t\t\t\tList<String> medList = Arrays.asList(rel.getMediators().split(\";| \"));\n\t\t\t\tif (!medList.isEmpty())\n\t\t\t\t{\n\t\t\t\t\tdMap.put(\"pcLinks\", medList);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tSet<String> totalProtUsedUp = new HashSet<>();\n\n\t\tSet<ExperimentData> dataInGraph = getExperimentDataToDraw();\n\n\t\tdataInGraph.forEach(data ->\n\t\t{\n\t\t\tString colS = \"255 255 255\";\n\n\t\t\tif (data.hasChangeDetector())\n\t\t\t{\n\t\t\t\tif (data.getChangeSign() != 0)\n\t\t\t\t{\n\t\t\t\t\tcolS = vtc.getColorInJSONString(data.getChangeValue());\n\t\t\t\t}\n\t\t\t\telse return;\n\t\t\t}\n\n\t\t\tString bor = inJSONString(defaultBorderColor);\n\t\t\tString let = \"?\";\n\n\t\t\tif (data instanceof SiteModProteinData)\n\t\t\t{\n\t\t\t\tSiteModProteinData pd = (SiteModProteinData) data;\n\t\t\t\tif (pd.getEffect() > 0) bor = inJSONString(activatingBorderColor);\n\t\t\t\telse if (pd.getEffect() < 0) bor = inJSONString(inhibitingBorderColor);\n\n\t\t\t\tlet = pd.getModification().toString().substring(0, 1).toLowerCase();\n\t\t\t}\n\t\t\telse if (data instanceof ProteinData)\n\t\t\t{\n\t\t\t\tlet = \"t\";\n\t\t\t}\n\t\t\telse if (data instanceof MetaboliteData)\n\t\t\t{\n\t\t\t\tlet = \"c\";\n\t\t\t}\n\t\t\telse if (data instanceof MutationData)\n\t\t\t{\n\t\t\t\tlet = \"x\";\n\t\t\t\tif (data.getEffect() == 1)\n\t\t\t\t\tbor = inJSONString(activatingBorderColor);\n\t\t\t\telse bor = inJSONString(inhibitingBorderColor);\n\t\t\t}\n\t\t\telse if (data instanceof CNAData)\n\t\t\t{\n\t\t\t\tlet = \"d\";\n\t\t\t}\n\t\t\telse if (data instanceof RNAData)\n\t\t\t{\n\t\t\t\tlet = \"r\";\n\t\t\t}\n\t\t\telse if (data instanceof ActivityData)\n\t\t\t{\n\t\t\t\tlet = data.getChangeSign() > 0 ? \"!\" : \"i\";\n\t\t\t\tbor = inJSONString(activatingBorderColor);\n\t\t\t}\n\n\t\t\tString siteID = data.id;\n\t\t\tString val = data.hasChangeDetector() ? data.getChangeValue() + \"\" : \"\";\n\n\t\t\tfor (String sym : data.getGeneSymbols())\n\t\t\t{\n\t\t\t\tString nodeText = let.equals(\"c\") ? siteID : sym;\n\t\t\t\tinitJsonNode(geneMap, nodes, nodeText);\n\n\t\t\t\tMap node = geneMap.get(nodeText);\n\n\t\t\t\tif (nsc != null)\n\t\t\t\t{\n\t\t\t\t\tif (nsc.isDownstreamSignificant(sym))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!node.containsKey(\"css\")) node.put(\"css\", new HashMap<>());\n\n\t\t\t\t\t\t((Map) node.get(\"css\")).put(\"borderWidth\", \"2px\");\n\t\t\t\t\t}\n\t\t\t\t\tboolean act = false;\n\t\t\t\t\tboolean inh = false;\n\n\t\t\t\t\tif (nsc instanceof NSCForComparison)\n\t\t\t\t\t{\n\t\t\t\t\t\tact = ((NSCForComparison) nsc).isActivatingTargetsSignificant(sym);\n\t\t\t\t\t\tinh = ((NSCForComparison) nsc).isInhibitoryTargetsSignificant(sym);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (act || inh && !node.containsKey(\"css\")) node.put(\"css\", new HashMap<>());\n\n\t\t\t\t\tif (act && !inh) ((Map) node.get(\"css\")).put(\"borderColor\", inJSONString(activatingBorderColor));\n\t\t\t\t\telse if (!act && inh) ((Map) node.get(\"css\")).put(\"borderColor\", inJSONString(inhibitingBorderColor));\n\t\t\t\t\telse if (act /** && inh **/) ((Map) node.get(\"css\")).put(\"borderColor\", inJSONString(doubleSignificanceBorderColor));\n\t\t\t\t}\n\n\t\t\t\tif (useGeneBGForTotalProtein && (let.equals(\"t\") || let.equals(\"c\")) && !totalProtUsedUp.contains(nodeText))\n\t\t\t\t{\n\t\t\t\t\tif (!node.containsKey(\"css\")) node.put(\"css\", new HashMap<>());\n\t\t\t\t\t((Map) node.get(\"css\")).put(\"backgroundColor\", colS);\n\t\t\t\t\tString tooltip = (let.equals(\"c\") ? sym : siteID) + (val.isEmpty() ? \"\" : \", \" + val);\n\t\t\t\t\t((Map) node.get(\"data\")).put(\"tooltipText\", tooltip);\n\t\t\t\t\ttotalProtUsedUp.add(nodeText);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tMap site = new HashMap();\n\t\t\t\t\t((List) ((Map) node.get(\"data\")).get(\"sites\")).add(site);\n\n\t\t\t\t\tsite.put(\"siteText\", let);\n\t\t\t\t\tsite.put(\"siteInfo\", siteID);\n\t\t\t\t\tsite.put(\"siteBackgroundColor\", colS);\n\t\t\t\t\tsite.put(\"siteBorderColor\", bor);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(filename));\n\t\tJsonUtils.writePrettyPrint(writer, map);\n\t\twriter.close();\n\t}\n\n\t/**\n\t * This method takes in a SIF graph defined by two files (.sif and .format), and generates a corresponding .json\n\t * file that the webserver can display.\n\t *\n\t * @param sifFileanme SIF filename\n\t * @param formatFilename Format filename\n\t * @param outJasonFilename JASON filename to produce\n\t */\n\tpublic static void convertSIFToJSON(String sifFileanme, String formatFilename, String outJasonFilename) throws IOException\n\t{\n\t\tMap<String, Object> map = new HashMap<>();\n\t\tList<Map> nodes = new ArrayList<>();\n\t\tList<Map> edges = new ArrayList<>();\n\t\tmap.put(\"nodes\", nodes);\n\t\tmap.put(\"edges\", edges);\n\n\t\tMap<String, Map> nodeMap = new HashMap<>();\n\t\tSet<String> relMem = new HashSet<>();\n\n\t\tFiles.lines(Paths.get(sifFileanme)).map(l -> l.split(\"\\t\")).forEach(t ->\n\t\t{\n\t\t\tif (t.length > 2)\n\t\t\t{\n\t\t\t\tString key = t[0] + \"\\t\" + t[1] + \"\\t\" + t[2];\n\t\t\t\tif (relMem.contains(key)) return;\n\t\t\t\telse relMem.add(key);\n\n\t\t\t\tMap<String, Object> edge = new HashMap<>();\n\t\t\t\tedges.add(edge);\n\t\t\t\tMap<String, Object> dMap = new HashMap<>();\n\t\t\t\tedge.put(\"data\", dMap);\n\t\t\t\tdMap.put(\"source\", t[0]);\n\t\t\t\tdMap.put(\"target\", t[2]);\n\t\t\t\tdMap.put(\"edgeType\", t[1]);\n\t\t\t\tif (t.length > 4 && !t[4].trim().isEmpty())\n\t\t\t\t{\n\t\t\t\t\tdMap.put(\"tooltipText\", t[2] + \"-\" + CollectionUtil.merge(Arrays.asList(t[4].split(\";\")), \"-\"));\n\t\t\t\t}\n\n\t\t\t\tif (t.length > 3 && !t[3].trim().isEmpty())\n\t\t\t\t{\n\t\t\t\t\tList<String> medList = Arrays.asList(t[3].split(\";| \"));\n\t\t\t\t\tif (!medList.isEmpty())\n\t\t\t\t\t{\n\t\t\t\t\t\tdMap.put(\"pcLinks\", medList);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tinitJsonNode(nodeMap, nodes, t[2]);\n\t\t\t}\n\n\t\t\tif (t.length > 0 && !t[0].isEmpty()) initJsonNode(nodeMap, nodes, t[0]);\n\t\t});\n\n\t\tMap<String, String> defaultColors = new HashMap<>();\n\t\tString defBGCKey = \"node BG color\";\n\t\tString defBorCKey = \"node border color\";\n\n\t\tFiles.lines(Paths.get(formatFilename)).map(l -> l.split(\"\\t\")).filter(t -> t.length > 3).forEach(t ->\n\t\t{\n\t\t\tif (t[1].equals(\"all-nodes\"))\n\t\t\t{\n\t\t\t\tif (t[2].equals(\"color\")) defaultColors.put(defBGCKey, jasonizeColor(t[3]));\n\t\t\t\telse if (t[2].equals(\"bordercolor\")) defaultColors.put(defBorCKey, jasonizeColor(t[3]));\n\t\t\t}\n\n\t\t\tif (t[0].equals(\"node\"))\n\t\t\t{\n\t\t\t\tString name = t[1];\n\t\t\t\tMap node = nodeMap.get(name);\n\t\t\t\tif (node != null)\n\t\t\t\t{\n\t\t\t\t\tif (!node.containsKey(\"css\")) node.put(\"css\", new HashMap<>());\n\n\t\t\t\t\tswitch (t[2])\n\t\t\t\t\t{\n\t\t\t\t\t\tcase \"rppasite\":\n\t\t\t\t\t\t\tString[] x = t[3].split(\"\\\\|\");\n\t\t\t\t\t\t\tMap site = new HashMap();\n\t\t\t\t\t\t\t((List) ((Map) node.get(\"data\")).get(\"sites\")).add(site);\n\t\t\t\t\t\t\tsite.put(\"siteText\", x[1]);\n\t\t\t\t\t\t\tsite.put(\"siteInfo\", x[0] + (x.length > 4 ? (\" \" + x[4]) : \"\"));\n\t\t\t\t\t\t\tsite.put(\"siteBackgroundColor\", jasonizeColor(x[2]));\n\t\t\t\t\t\t\tsite.put(\"siteBorderColor\", jasonizeColor(x[3]));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"color\":\n\t\t\t\t\t\t\t((Map) node.get(\"css\")).put(\"backgroundColor\", jasonizeColor(t[3]));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"bordercolor\":\n\t\t\t\t\t\t\t((Map) node.get(\"css\")).put(\"borderColor\", jasonizeColor(t[3]));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"borderwidth\":\n\t\t\t\t\t\t\t((Map) node.get(\"css\")).put(\"borderWidth\", t[3] + \"px\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"tooltip\":\n\t\t\t\t\t\t\t((Map) node.get(\"data\")).put(\"tooltipText\", t[3]);\n\t\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\n\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(outJasonFilename));\n\t\tJsonUtils.writePrettyPrint(writer, map);\n\t\twriter.close();\n\t}\n\n\tprivate static void initJsonNode(Map<String, Map> nodeMap, List<Map> nodes, String name)\n\t{\n\t\tif (!nodeMap.containsKey(name))\n\t\t{\n\t\t\tHashMap<String, Object> node = new HashMap<>();\n\t\t\tnodeMap.put(name, node);\n\t\t\tnodes.add(node);\n\t\t\tMap<String, Object> d = new HashMap<>();\n\t\t\tnode.put(\"data\", d);\n\t\t\td.put(\"id\", name);\n\t\t\td.put(\"text\", name);\n\t\t\tList<Map> sites = new ArrayList<>();\n\t\t\td.put(\"sites\", sites);\n\t\t}\n\t}\n\n\tprivate static String jasonizeColor(String c)\n\t{\n\t\tString[] t = c.split(\" \");\n\t\treturn \"rgb(\" + ArrayUtil.getString(\",\", t[0], t[1], t[2]) + \")\";\n\t}\n\n\tprivate Set<ExperimentData> getExperimentDataToDraw()\n\t{\n\t\tif (experimentDataToDraw != null) return experimentDataToDraw;\n\n\t\tSet<ExperimentData> datas = Stream.concat(\n\t\t\trelations.stream().map(r -> r.sourceData.getChangedData().keySet()).flatMap(Collection::stream),\n\t\t\trelations.stream().map(r -> r.targetData.getChangedData().keySet()).flatMap(Collection::stream))\n\t\t\t.collect(Collectors.toSet());\n\n\t\tif (otherGenesToShow != null)\n\t\t{\n\t\t\tdatas.addAll(otherGenesToShow.stream().map(GeneWithData::getData).flatMap(Collection::stream)\n\t\t\t\t.collect(Collectors.toSet()));\n\t\t}\n\n\t\treturn datas;\n\t}\n\n\tprivate Set<String> getGenesInGraph()\n\t{\n\t\treturn relations.stream().map(r -> new String[]{r.source, r.target}).flatMap(Arrays::stream)\n\t\t\t.collect(Collectors.toSet());\n\t}\n}", "public class Relation\n{\n\t/**\n\t * Source gene.\n\t */\n\tpublic String source;\n\n\t/**\n\t * Target gene.\n\t */\n\tpublic String target;\n\n\t/**\n\t * The type of the relation.\n\t */\n\tpublic RelationType type;\n\n\t/**\n\t * Set of experiment data associated with source gene.\n\t */\n\tpublic GeneWithData sourceData;\n\n\t/**\n\t * Set of experiment data associated with target gene.\n\t */\n\tpublic GeneWithData targetData;\n\n\t/**\n\t * Pathway Commons IDs of the mediator objects for the relation.\n\t */\n\tprivate String mediators;\n\n\t/**\n\t * A change detector that can evaluate pairs of experiment data to see if this relation can explain the causality\n\t * between them.\n\t */\n\tpublic TwoDataChangeDetector chDet;\n\n\t/**\n\t * Sites for the target. Needed when the relation is a phosphorylation or dephosphorylation.\n\t */\n\tpublic Set<ProteinSite> sites;\n\n\t/**\n\t * For performance reasons. This design assumes the proximityThreshold will not change during execution of the\n\t * program.\n\t */\n\tprivate Set<String> targetWithSites;\n\n\tpublic Relation(String source, String target, RelationType type, String mediators)\n\t{\n\t\tthis.source = source;\n\t\tthis.target = target;\n\t\tthis.type = type;\n\t\tthis.mediators = mediators;\n\t}\n\n\tpublic Relation(String line)\n\t{\n\t\tString[] token = line.split(\"\\t\");\n\t\tthis.source = token[0];\n\t\tthis.target = token[2];\n\t\tthis.type = RelationType.getType(token[1]);\n\t\tif (token.length > 3) this.mediators = token[3];\n\t\tif (token.length > 4)\n\t\t{\n\t\t\tsites = Arrays.stream(token[4].split(\";\")).map(s -> new ProteinSite(Integer.valueOf(s.substring(1)),\n\t\t\t\tString.valueOf(s.charAt(0)), 0)).collect(Collectors.toSet());\n\t\t}\n\t}\n\n\t/**\n\t * Sign of the relation.\n\t */\n\tpublic int getSign()\n\t{\n\t\treturn type.sign;\n\t}\n\n\tpublic String toString()\n\t{\n\t\treturn source + \"\\t\" + type.getName() + \"\\t\" + target + \"\\t\" + mediators + \"\\t\" + getSitesInString();\n\t}\n\n\tpublic String getMediators()\n\t{\n\t\treturn mediators;\n\t}\n\n\tpublic Set<String> getTargetWithSites(int proximityThr)\n\t{\n\t\tif (targetWithSites == null)\n\t\t{\n\t\t\ttargetWithSites = new HashSet<>();\n\n\t\t\tif (sites != null)\n\t\t\t{\n\t\t\t\tfor (ProteinSite site : sites)\n\t\t\t\t{\n\t\t\t\t\tfor (int i = 0; i <= proximityThr; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\ttargetWithSites.add(target + \"_\" + (site.getSite() + i));\n\t\t\t\t\t\ttargetWithSites.add(target + \"_\" + (site.getSite() - i));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn targetWithSites;\n\t}\n\n\tpublic String getSitesInString()\n\t{\n\t\treturn sites == null ? \"\" : CollectionUtil.merge(sites, \";\");\n\t}\n\n\tpublic Set<ExperimentData> getAllData()\n\t{\n\t\treturn CollectionUtil.getUnion(sourceData.getData(), targetData.getData());\n\t}\n\n\tpublic void setChDet(TwoDataChangeDetector chDet)\n\t{\n\t\tthis.chDet = chDet;\n\t}\n\n\t@Override\n\tpublic int hashCode()\n\t{\n\t\treturn source.hashCode() + target.hashCode() + type.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj)\n\t{\n\t\treturn obj instanceof Relation && ((Relation) obj).source.equals(source) &&\n\t\t\t((Relation) obj).target.equals(target) && ((Relation) obj).type.equals(type);\n\t}\n\n\tpublic Relation copy()\n\t{\n\t\tRelation cln = new Relation(source, target, type, mediators);\n\t\tcln.sites = sites;\n\t\treturn cln;\n\t}\n}", "public class NetworkLoader\n{\n\t/**\n\t * Reads 4 of the built-in resource networks.\n\t */\n\tpublic static Set<Relation> load()\n\t{\n\t\treturn load(new HashSet<>(Arrays.asList(ResourceType.PC, ResourceType.PhosphoSitePlus,\n\t\t\tResourceType.PhosphoNetworks, ResourceType.IPTMNet, ResourceType.TRRUST, ResourceType.TFactS, ResourceType.PCMetabolic)));\n\t}\n\n\t/**\n\t * Reads the selected built-in resource networks.\n\t */\n\tpublic static Set<Relation> load(Set<ResourceType> resourceTypes)\n\t{\n\t\tSet<Relation> relations = new HashSet<>();\n\n\t\tMap<SignedType, DirectedGraph> allGraphs = new HashMap<>();\n\n\t\t// Load signed directed graph from Pathway Commons\n\t\tif (resourceTypes.contains(ResourceType.PC))\n\t\t{\n\t\t\tmergeSecondMapIntoFirst(allGraphs, SignedPC.get().getAllGraphs());\n\t\t}\n\n\t\t// Add PhosphoSitePlus\n\t\tif (resourceTypes.contains(ResourceType.PhosphoSitePlus))\n\t\t{\n\t\t\tmergeSecondMapIntoFirst(allGraphs, PhosphoSitePlus.get().getAllGraphs());\n\t\t}\n\n\t\t// Add REACH\n\t\tif (resourceTypes.contains(ResourceType.REACH))\n\t\t{\n\t\t\tmergeSecondMapIntoFirst(allGraphs, SignedREACH.get().getAllGraphs());\n\t\t}\n\n\t\t// Add IPTMNet\n\t\tif (resourceTypes.contains(ResourceType.IPTMNet))\n\t\t{\n\t\t\tmergeSecondMapIntoFirst(allGraphs, IPTMNet.get().getAllGraphs());\n\t\t}\n\n\t\t// Add PhosphoNetworks\n\t\tif (resourceTypes.contains(ResourceType.PhosphoNetworks))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.PHOSPHORYLATES, PhosphoNetworks.get().getGraph());\n\t\t}\n\n\t\t// Add NetworKIN\n\t\tif (resourceTypes.contains(ResourceType.NetworKIN))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.PHOSPHORYLATES, NetworKIN.get().getGraph());\n\t\t}\n\n\t\t// Add Rho GEF\n\t\tif (resourceTypes.contains(ResourceType.RHOGEF))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.ACTIVATES_GTPASE, RhoGEF.get().getGraph());\n\t\t}\n\n\t\t// Experimental code!!!!!!!!!!!!!!!!!!!\n\t\tif (resourceTypes.contains(ResourceType.PCTCGAConsensus))\n\t\t{\n\t\t\tDirectedGraph posG = new DirectedGraph(\"Pos\", SignedType.UPREGULATES_EXPRESSION.getTag());\n\t\t\tDirectedGraph negG = new DirectedGraph(\"Neg\", SignedType.DOWNREGULATES_EXPRESSION.getTag());\n\t\t\tString file = \"/home/babur/Documents/PC/SignedByTCGAConsensusFiltered.sif\";\n\t\t\tposG.load(file, Collections.singleton(posG.getEdgeType()));\n\t\t\tnegG.load(file, Collections.singleton(negG.getEdgeType()));\n\t\t\taddGraph(allGraphs, SignedType.UPREGULATES_EXPRESSION, posG);\n\t\t\taddGraph(allGraphs, SignedType.DOWNREGULATES_EXPRESSION, negG);\n\t\t}\n\n\t\t// Add TRRUST\n\t\tif (resourceTypes.contains(ResourceType.TRRUST))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.UPREGULATES_EXPRESSION, TRRUST.get().getPositiveGraph());\n\t\t\taddGraph(allGraphs, SignedType.DOWNREGULATES_EXPRESSION, TRRUST.get().getNegativeGraph());\n\t\t}\n\n\t\t// Add TFactS\n\t\tif (resourceTypes.contains(ResourceType.TFactS))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.UPREGULATES_EXPRESSION, TFactS.get().getPositiveGraph());\n\t\t\taddGraph(allGraphs, SignedType.DOWNREGULATES_EXPRESSION, TFactS.get().getNegativeGraph());\n\t\t}\n\n\t\t// Add PC Metabolic\n\t\tif (resourceTypes.contains(ResourceType.PCMetabolic))\n\t\t{\n\t\t\taddGraph(allGraphs, SignedType.PRODUCES, SignedMetabolic.getGraph(SignedType.PRODUCES));\n\t\t\taddGraph(allGraphs, SignedType.CONSUMES, SignedMetabolic.getGraph(SignedType.CONSUMES));\n\t\t\taddGraph(allGraphs, SignedType.USED_TO_PRODUCE, SignedMetabolic.getGraph(SignedType.USED_TO_PRODUCE));\n\t\t}\n\n\t\t// Clean-up conflicts\n\t\tcleanUpConflicts(allGraphs);\n\n\t\t// Generate relations based on the network\n\n\t\tfor (SignedType signedType : allGraphs.keySet())\n\t\t{\n\t\t\tDirectedGraph graph = allGraphs.get(signedType);\n\t\t\tif (graph == null)\n\t\t\t{\n//\t\t\t\tSystem.out.println(\"Null graph for type: \" + signedType);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// take a subset of the network for debugging\n//\t\t\tgraph.crop(Arrays.asList(\"HCK\", \"CD247\"));\n\n\t\t\tfor (String source : graph.getOneSideSymbols(true))\n\t\t\t{\n\t\t\t\tfor (String target : graph.getDownstream(source))\n\t\t\t\t{\n\t\t\t\t\tRelationType type;\n\t\t\t\t\tswitch (signedType)\n\t\t\t\t\t{\n\t\t\t\t\t\tcase PHOSPHORYLATES: type = RelationType.PHOSPHORYLATES; break;\n\t\t\t\t\t\tcase DEPHOSPHORYLATES: type = RelationType.DEPHOSPHORYLATES; break;\n\t\t\t\t\t\tcase UPREGULATES_EXPRESSION: type = RelationType.UPREGULATES_EXPRESSION; break;\n\t\t\t\t\t\tcase DOWNREGULATES_EXPRESSION: type = RelationType.DOWNREGULATES_EXPRESSION; break;\n\t\t\t\t\t\tcase ACTIVATES_GTPASE: type = RelationType.ACTIVATES_GTPASE; break;\n\t\t\t\t\t\tcase INHIBITS_GTPASE: type = RelationType.INHIBITS_GTPASE; break;\n\t\t\t\t\t\tcase ACETYLATES: type = RelationType.ACETYLATES; break;\n\t\t\t\t\t\tcase DEACETYLATES: type = RelationType.DEACETYLATES; break;\n\t\t\t\t\t\tcase DEMETHYLATES: type = RelationType.DEMETHYLATES; break;\n\t\t\t\t\t\tcase METHYLATES: type = RelationType.METHYLATES; break;\n\t\t\t\t\t\tcase PRODUCES: type = RelationType.PRODUCES; break;\n\t\t\t\t\t\tcase CONSUMES: type = RelationType.CONSUMES; break;\n\t\t\t\t\t\tcase USED_TO_PRODUCE: type = RelationType.USED_TO_PRODUCE; break;\n\t\t\t\t\t\tdefault: throw new RuntimeException(\"Is there a new type??\");\n\t\t\t\t\t}\n\t\t\t\t\tRelation rel = new Relation(source, target, type, graph.getMediatorsInString(source, target));\n\n\t\t\t\t\tif (graph instanceof SiteSpecificGraph)\n\t\t\t\t\t{\n\t\t\t\t\t\tSiteSpecificGraph pGraph = (SiteSpecificGraph) graph;\n\t\t\t\t\t\tSet<String> sites = pGraph.getSites(source, target);\n\t\t\t\t\t\tif (sites != null && !sites.isEmpty())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trel.sites = new HashSet<>();\n\n\t\t\t\t\t\t\tfor (String site : sites)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (!site.isEmpty())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\trel.sites.add(new ProteinSite(Integer.parseInt(site.substring(1)),\n\t\t\t\t\t\t\t\t\t\tsite.substring(0, 1), 0));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\trelations.add(rel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// clean from non-HGNC\n\n\t\trelations = relations.stream().filter(r -> (r.source.startsWith(\"CHEBI:\") || HGNC.get().getSymbol(r.source) != null) &&\n\t\t\t(r.target.startsWith(\"CHEBI:\") || HGNC.get().getSymbol(r.target) != null)).collect(Collectors.toSet());\n\n\t\t// initiate source and target data\n\n\t\tinitSourceTargetData(relations);\n\n\t\treturn relations;\n\t}\n\n\tprivate static void check(Map<SignedType, DirectedGraph> allGraphs)\n\t{\n\t\tDirectedGraph graph = allGraphs.get(SignedType.DEPHOSPHORYLATES);\n\t\tif (graph != null)\n\t\t{\n\t\t\tSet<String> dwns = graph.getDownstream(\"ABL1\");\n\t\t\tif (dwns.contains(\"RB1\"))\n\t\t\t{\n\t\t\t\tSystem.out.println(\"Here it is!!!\");\n\t\t\t}\n\t\t\telse System.out.println(\"Nope\");\n\t\t}\n\t\telse System.out.println(\"No graph\");\n\t}\n\n\tpublic static Set<Relation> load(String customFile) throws IOException\n\t{\n\t\tSet<Relation> relations = Files.lines(Paths.get(customFile)).filter(l -> !l.isEmpty() && !l.startsWith(\"#\")).map(Relation::new)\n\t\t\t.collect(Collectors.toSet());\n\n\t\tinitSourceTargetData(relations);\n\n\t\treturn relations;\n\t}\n\n\tprivate static void initSourceTargetData(Set<Relation> relations)\n\t{\n\t\tSet<String> genes = relations.stream().map(r -> r.source).collect(Collectors.toSet());\n\t\tgenes.addAll(relations.stream().map(r -> r.target).collect(Collectors.toSet()));\n\n\t\tMap<String, GeneWithData> map = new HashMap<>();\n\t\tgenes.forEach(g -> map.put(g, new GeneWithData(g)));\n\n\t\tfor (Relation relation : relations)\n\t\t{\n\t\t\trelation.sourceData = map.get(relation.source);\n\t\t\trelation.targetData = map.get(relation.target);\n\t\t}\n\t}\n\n\tprivate static void mergeSecondMapIntoFirst(Map<SignedType, DirectedGraph> allGraphs, Map<SignedType, DirectedGraph> graphs)\n\t{\n\t\tfor (SignedType type : graphs.keySet())\n\t\t{\n\t\t\tif (allGraphs.containsKey(type)) allGraphs.get(type).merge(graphs.get(type));\n\t\t\telse allGraphs.put(type, graphs.get(type));\n\t\t}\n\t}\n\n\tprivate static void addGraph(Map<SignedType, DirectedGraph> allGraphs, SignedType type, DirectedGraph graph)\n\t{\n\t\tif (allGraphs.containsKey(type)) allGraphs.get(type).merge(graph);\n\t\telse allGraphs.put(type, graph);\n\t}\n\n\tprivate static void cleanUpConflicts(Map<SignedType, DirectedGraph> graphs)\n\t{\n\t\tcleanUpConflicts((SiteSpecificGraph) graphs.get(SignedType.PHOSPHORYLATES), (SiteSpecificGraph) graphs.get(SignedType.DEPHOSPHORYLATES));\n\t\tcleanUpConflicts((SiteSpecificGraph) graphs.get(SignedType.ACETYLATES), (SiteSpecificGraph) graphs.get(SignedType.DEACETYLATES));\n\t\tcleanUpConflicts((SiteSpecificGraph) graphs.get(SignedType.METHYLATES), (SiteSpecificGraph) graphs.get(SignedType.DEMETHYLATES));\n\t\tcleanUpConflicts(graphs.get(SignedType.UPREGULATES_EXPRESSION), graphs.get(SignedType.DOWNREGULATES_EXPRESSION));\n\t\tcleanUpConflicts(graphs.get(SignedType.ACTIVATES_GTPASE), graphs.get(SignedType.INHIBITS_GTPASE));\n\t}\n\n\tprivate static void cleanUpConflicts(DirectedGraph graph1, DirectedGraph graph2)\n\t{\n\t\tSet<String[]> rem1 = new HashSet<>();\n\t\tSet<String[]> rem2 = new HashSet<>();\n\n\t\tfor (String source : graph1.getOneSideSymbols(true))\n\t\t{\n\t\t\tfor (String target : graph1.getDownstream(source))\n\t\t\t{\n\t\t\t\tif (graph2.hasRelation(source, target))\n\t\t\t\t{\n\t\t\t\t\tString[] rel = new String[]{source, target};\n\t\t\t\t\tlong c1 = paperCnt(graph1.getMediators(source, target));\n\t\t\t\t\tlong c2 = paperCnt(graph2.getMediators(source, target));\n\n\t\t\t\t\tif (c1 >= c2) rem2.add(rel);\n\t\t\t\t\tif (c2 >= c1) rem1.add(rel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trem1.forEach(rel -> graph1.removeRelation(rel[0], rel[1]));\n\t\trem2.forEach(rel -> graph2.removeRelation(rel[0], rel[1]));\n\t}\n\n\tprivate static void cleanUpConflicts(SiteSpecificGraph graph1, SiteSpecificGraph graph2)\n\t{\n\t\tfor (String source : graph1.getOneSideSymbols(true))\n\t\t{\n\t\t\tfor (String target : graph1.getDownstream(source))\n\t\t\t{\n\t\t\t\tif (graph2.hasRelation(source, target))\n\t\t\t\t{\n\t\t\t\t\tSet<String> s1 = graph1.getSites(source, target);\n\t\t\t\t\tSet<String> s2 = graph1.getSites(source, target);\n\n\t\t\t\t\tSet<String> common = CollectionUtil.getIntersection(s1, s2);\n\n\t\t\t\t\tif (!common.isEmpty())\n\t\t\t\t\t{\n\t\t\t\t\t\tlong c1 = paperCnt(graph1.getMediators(source, target));\n\t\t\t\t\t\tlong c2 = paperCnt(graph2.getMediators(source, target));\n\n\t\t\t\t\t\tfor (String site : common)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (c1 >= c2) graph2.removeSite(source, target, site);\n\t\t\t\t\t\t\tif (c2 >= c1) graph1.removeSite(source, target, site);\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}\n\t}\n\n\tprivate static long paperCnt(Set<String> mediators)\n\t{\n\t\treturn mediators.stream().filter(s -> s.startsWith(\"PMID:\")).distinct().count();\n\t}\n\n\tpublic enum ResourceType\n\t{\n\t\tPC(\"Pathway Commons v9 for all kinds of relations.\"),\n\t\tPhosphoSitePlus(\"PhosphoSitePlus database for (de)phosphorylations, (de)acetylations and (de)methylations.\"),\n\t\tREACH(\"Network derived from REACH NLP extraction results for phosphorylation relations.\"),\n\t\tPhosphoNetworks(\"The PhosphoNetworks database for phosphorylations.\"),\n\t\tIPTMNet(\"The IPTMNet database for phosphorylations.\"),\n\t\tRHOGEF(\"The experimental Rho - GEF relations.\"),\n\t\tPCTCGAConsensus(\"Unsigned PC relations whose signs are inferred by TCGA studies.\"),\n\t\tTRRUST(\"The TRRUST database for expression relations.\"),\n\t\tTFactS(\"The TFactS database for expression relations.\"),\n\t\tNetworKIN(\"The NetworKIN database for phosphorylation relations.\"),\n\t\tPCMetabolic(\"Relations involving chemicals in PC\"),\n\t\t;\n\n\t\tString description;\n\n\t\tResourceType(String description)\n\t\t{\n\t\t\tthis.description = description;\n\t\t}\n\n\t\tpublic static Set<ResourceType> getSelectedResources(Set<String> names)\n\t\t{\n\t\t\tSet<ResourceType> set = new HashSet<>();\n\t\t\tfor (String res : names)\n\t\t\t{\n\t\t\t\tres = res.trim();\n\n\t\t\t\tif (!res.isEmpty())\n\t\t\t\t{\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tResourceType type = valueOf(res);\n\t\t\t\t\t\tset.add(type);\n\t\t\t\t\t} catch (IllegalArgumentException e)\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow new RuntimeException(\"Network resource not recognized: \" + res);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn set;\n\t\t}\n\n\t\tpublic static String getUsageInfo()\n\t\t{\n\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\tfor (ResourceType type : values())\n\t\t\t{\n\t\t\t\tsb.append(\"\\t\").append(type.name()).append(\": \").append(type.description).append(\"\\n\");\n\t\t\t}\n\t\t\treturn sb.toString();\n\t\t}\n\n\t\tpublic static Map getValuesAsJson()\n\t\t{\n\t\t\tList list = new ArrayList<>();\n\t\t\tfor (ResourceType type : values())\n\t\t\t{\n\t\t\t\tlist.add(type.toString());\n\t\t\t}\n\n\t\t\tMap map = new LinkedHashMap<>();\n\t\t\tmap.put(\"name\", \"ResourceType\");\n\t\t\tmap.put(\"values\", list);\n\t\t\treturn map;\n\t\t}\n\n\t}\n\n\n\tpublic static void main(String[] args) throws IOException\n\t{\n//\t\twriteSitesWithUpstream();\n\t\twriteRelations();\n\t}\n\n\tprivate static void writeRelations() throws IOException\n\t{\n\t\tSet<Relation> rels = NetworkLoader.load();\n\n\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(\"/Users/ozgun/Documents/Temp/causal-priors.txt\"));\n\n\t\tfor (Relation rel : rels)\n\t\t{\n\t\t\twriter.write(rel.toString() + \"\\n\");\n\t\t}\n\n\t\twriter.close();\n\t}\n\n\tpublic static void writeSitesWithUpstream() throws IOException\n\t{\n\t\tSet<Relation> rels = NetworkLoader.load(new HashSet<>(Arrays.asList(ResourceType.PC, ResourceType.PhosphoNetworks)));\n\t\tMap<String, Set<ProteinSite>> map = new HashMap<>();\n\t\tfor (Relation rel : rels)\n\t\t{\n\t\t\tif (rel.sites != null)\n\t\t\t{\n\t\t\t\tif (!map.containsKey(rel.target)) map.put(rel.target, new HashSet<>());\n\t\t\t\tmap.get(rel.target).addAll(rel.sites);\n\t\t\t}\n\t\t}\n\t\tBufferedWriter writer = Files.newBufferedWriter(Paths.get(\"/home/ozgun/Documents/Temp/gene-to-sites.txt\"));\n\n\t\tfor (String gene : map.keySet())\n\t\t{\n\t\t\tSet<ProteinSite> sites = map.get(gene);\n\t\t\twriter.write(\"\\n\" + gene + \"\\t\");\n\t\t\twriter.write(CollectionUtil.merge(sites, \" \"));\n\t\t}\n\n\t\twriter.close();\n\t}\n\n}", "public class TCGALoader\n{\n\t/**\n\t * Reader for copy number data.\n\t */\n\tprivate CNAReader cnaReader;\n\n\t/**\n\t * Reader for RNA expression data.\n\t */\n\tprivate ExpressionReader expReader;\n\n\t/**\n\t * Reader for mutation data.\n\t */\n\tprivate MutationReader mutReader;\n\n\t/**\n\t * Reader for RPPA data.\n\t */\n\tprivate RPPAReader rppaReader;\n\n\t// todo add methylation data\n\n\t/**\n\t * RPPA reader is different from other readers. A row may correspond to multiple gene symbols. This cache is used\n\t * to prevent duplicate creation of experiment data for the same row.\n\t */\n\tprivate Map<String, ProteinData> rppaCache;\n\n\t/**\n\t * When a data is already been read for a gene, this cache stores it so that creation of redundant data objects is\n\t * avoided on multiple access.\n\t */\n\tprivate Map<String, Set<ExperimentData>> dataCache;\n\n\t/**\n\t * This set of genes are used to ignore RNA expression, DNA_CNA or methylation data when there is a total protein\n\t * measurement exists.\n\t *\n\t */\n\tprivate Set<String> genesWithTotalProteinData;\n\n\t/**\n\t * Names of samples loaded.\n\t */\n\tprivate String[] samples;\n\n\tprivate Map<String, Integer> mutationEffectMap;\n\n\t// Names of data files under the TCGA data directory\n\n\tprivate static final String COPY_NUMBER_FILE = \"/copynumber.txt\";\n\tprivate static final String MUTATION_FILE = \"/mutation.maf\";\n\tprivate static final String EXPRESSION_FILE = \"/expression.txt\";\n\tprivate static final String RPPA_FILE = \"/rppa.txt\";\n\n\t// todo: Make loading parameterized by passing the types of desired data.\n\tpublic TCGALoader(String dir)\n\t{\n\t\tthis(dir, 12);\n\t}\n\n\tpublic TCGALoader(String dir, int idLength)\n\t{\n\t\ttry{cnaReader = new CNAReader(dir + COPY_NUMBER_FILE, null, false, 0, idLength);} catch (FileNotFoundException e){}\n\t\ttry{expReader = new ExpressionReader(dir + EXPRESSION_FILE, null, idLength);} catch (FileNotFoundException e){}\n\t\ttry{mutReader = new MutationReader(dir + MUTATION_FILE, idLength, null);} catch (IOException e){}\n\t\ttry{rppaReader = new RPPAReader(dir + RPPA_FILE, null, idLength);} catch (FileNotFoundException e){}\n\t\tthis.samples = getUnionSamples();\n\t\tif (rppaReader != null) rppaCache = new HashMap<>();\n\t\tdataCache = new HashMap<>();\n\t\tgenesWithTotalProteinData = findGenesWithTotalProteinData();\n\t}\n\n\tpublic void setSamples(String[] samples)\n\t{\n\t\tthis.samples = samples;\n\t}\n\n\tpublic void loadMutationEffectMap(String filename) throws IOException\n\t{\n\t\tthis.mutationEffectMap = Files.lines(Paths.get(filename)).skip(1).map(l -> l.split(\"\\t\"))\n\t\t\t.collect(Collectors.toMap(t -> t[0], t -> Integer.valueOf(t[1])));\n\t}\n\n\tpublic void setMutationEffectMap(Map<String, Integer> mutationEffectMap)\n\t{\n\t\tthis.mutationEffectMap = mutationEffectMap;\n\t}\n\n\t/**\n\t * Gets the set of experiment data for the given symbol.\n\t */\n\tpublic Set<ExperimentData> getData(String symbol)\n\t{\n\t\t// if asked before, return from cache\n\t\tif (dataCache.containsKey(symbol)) return dataCache.get(symbol);\n\n\t\tSet<ExperimentData> set = new HashSet<>();\n\n\t\tif (rppaReader != null)\n\t\t{\n\t\t\tSet<ProteomicsFileRow> rowSet = rppaReader.getAssociatedData(symbol, samples);\n\n\t\t\trowSet.stream().filter(row -> !rppaCache.containsKey(row.id)).forEach(row -> {\n\t\t\t\tProteinData d = row.isSiteSpecific() ? new SiteModProteinData(row) : new ProteinData(row);\n\t\t\t\trppaCache.put(d.id, d);\n\t\t\t});\n\n\t\t\trowSet.stream().map(rppa -> rppaCache.get(rppa.id)).forEach(set::add);\n\t\t}\n\n\t\tif (cnaReader != null)\n\t\t{\n\t\t\tint[] val = cnaReader.getGeneAlterationArray(symbol, samples);\n\t\t\tif (val != null)\n\t\t\t{\n\t\t\t\tCNAData d = new CNAData(symbol + \"-cna\", symbol);\n\t\t\t\td.data = new SingleCategoricalData[val.length];\n\t\t\t\tfor (int i = 0; i < val.length; i++)\n\t\t\t\t{\n\t\t\t\t\td.data[i] = new CNA(val[i]);\n\t\t\t\t}\n\t\t\t\tset.add(d);\n\t\t\t}\n\t\t}\n\n\t\tif (expReader != null)\n\t\t{\n\t\t\tdouble[] val = expReader.getGeneAlterationArray(symbol, samples);\n\t\t\tif (val != null)\n\t\t\t{\n\t\t\t\tRNAData d = new RNAData(symbol + \"-rna\", symbol);\n\t\t\t\td.vals = val;\n\t\t\t\tset.add(d);\n\t\t\t}\n\t\t}\n\n\t\tif (mutReader != null && mutationEffectMap != null && mutationEffectMap.containsKey(symbol))\n\t\t{\n\t\t\tMutationData d = getMutations(symbol, mutationEffectMap.get(symbol));\n\t\t\tif (d != null) set.add(d);\n\t\t}\n\n\t\tdataCache.put(symbol, set);\n\t\treturn set;\n\t}\n\n\t/**\n\t * Associated the related data to the given set of relations.\n\t */\n\tpublic void decorateRelations(Set<Relation> relations)\n\t{\n\t\trelations.stream().map(r -> new GeneWithData[]{r.sourceData, r.targetData}).flatMap(Arrays::stream).distinct()\n\t\t\t.forEach(d -> d.addAll(getData(d.getId())));\n\t}\n\n\t/**\n\t * Fetches the mutation data from the reader and prepares for analysis.\n\t * @param gene symbol\n\t * @param mutEffectSign is it activating (1) or inhibiting (-1) mutation\n\t */\n\tprivate MutationData getMutations(String gene, int mutEffectSign)\n\t{\n\t\tList<MutTuple>[] mutsList = mutReader.getMutations(gene, samples);\n\t\tif (mutsList == null) return null;\n\n\t\tMutationData mutData = new MutationData(gene + \"-mut\", gene, mutEffectSign);\n\t\tmutData.data = new SingleCategoricalData[samples.length];\n\n\t\tfor (int i = 0; i < mutsList.length; i++)\n\t\t{\n\t\t\tint categ = 0;\n\t\t\tif (mutsList[i] == null)\n\t\t\t{\n\t\t\t\tcateg = SingleCategoricalData.ABSENT;\n\t\t\t}\n\t\t\telse if (!mutsList[i].isEmpty())\n\t\t\t{\n\t\t\t\tcateg = 1;\n\t\t\t}\n\t\t\tmutData.data[i] = new Mutation(categ, mutsList[i]);\n\t\t}\n\t\treturn mutData;\n\t}\n\n\t/**\n\t * Gets all the samples that exists in at least one type of dataset.\n\t */\n\tpublic String[] getUnionSamples()\n\t{\n\t\tSet<String> set = new HashSet<>();\n\t\tif (cnaReader != null) set.addAll(cnaReader.getSamples());\n\t\tif (expReader != null) set.addAll(expReader.getSamples());\n\t\tif (mutReader != null) set.addAll(mutReader.getSamples());\n\t\tif (rppaReader != null) set.addAll(rppaReader.getSamples());\n\n\t\tList<String> list = new ArrayList<>(set);\n\t\tCollections.sort(list);\n\t\treturn list.toArray(new String[list.size()]);\n\t}\n\n\tpublic Set<String> getGenesWithTotalProteinData()\n\t{\n\t\treturn genesWithTotalProteinData;\n\t}\n\n\t/**\n\t * Gets the set of genes with total protein RPPA measurement.\n\t */\n\tprivate Set<String> findGenesWithTotalProteinData()\n\t{\n\t\tif (rppaReader == null) return Collections.emptySet();\n\n\t\tSet<String> genes = new HashSet<>();\n\t\tSet<String> sampleSet = rppaReader.getSamples();\n\t\tString[] samples = new String[]{sampleSet.iterator().next()};\n\n\t\trppaReader.getGenes().stream().forEach(gene ->\n\t\t\trppaReader.getAssociatedData(gene, samples).stream().filter(data -> !data.isSiteSpecific())\n\t\t\t\t.forEach(data -> genes.addAll(data.genes)));\n\n\t\treturn genes;\n\t}\n\n\t/**\n\t * Puts the given change detector to the data that is filtered by the given selector.\n\t */\n\tpublic void associateChangeDetector(OneDataChangeDetector chDet, DataSelector selector)\n\t{\n\t\tdataCache.values().stream().flatMap(Collection::stream).filter(selector::select).forEach(d -> d.setChDet(chDet));\n\t}\n\n\t/**\n\t * Function to filter experiment data.\n\t */\n\tpublic interface DataSelector\n\t{\n\t\tboolean select(ExperimentData data);\n\t}\n}" ]
import org.panda.causalpath.analyzer.CausalitySearcher; import org.panda.causalpath.analyzer.CorrelationDetector; import org.panda.causalpath.network.GraphWriter; import org.panda.causalpath.network.Relation; import org.panda.causalpath.resource.NetworkLoader; import org.panda.causalpath.resource.TCGALoader; import org.panda.utility.Kronometre; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set;
package org.panda.causalpath.run; /** * For finding recurrent causative correlations in TCGA RPPA data. */ public class TCGARecurrentCorrelationRun { public static void main(String[] args) throws IOException { Kronometre k = new Kronometre(); String base = "/home/babur/Documents/RPPA/TCGA/basic-correlation-rppa-mut/"; String single = base + "single/"; String recurrent = base + "recurrent/"; String tcgaDataDir = "/home/babur/Documents/TCGA"; if (!(new File(single).exists())) new File(single).mkdirs(); Map<Relation, Integer> relCnt = new HashMap<>(); for (File dir : new File(tcgaDataDir).listFiles()) { if (dir.getName().equals("PanCan")) continue; if (new File(dir.getPath() + "/rppa.txt").exists()) { String outFile = single + dir.getName() + ".sif"; Set<Relation> rels = NetworkLoader.load(); System.out.println("rels.size() = " + rels.size()); System.out.println("dir = " + dir.getName());
TCGALoader loader = new TCGALoader(dir.getPath());
4
semanticvectors/semanticvectors
src/main/java/pitt/search/semanticvectors/ESP.java
[ "public class SigmoidTable {\n\n\t private int maxExponent = 6; //maximum permitted exponent\n\t private int tableSize\t\t = 1000;\n\t private double[] sigmoidTable;\n\t \n\t /**\n\t * \n\t */\n\t \n\t public SigmoidTable(int maxExponent, int tableSize)\n\t\t {\n\t\t \tthis.maxExponent \t= maxExponent;\n\t\t \tthis.tableSize\t \t= tableSize;\n\t\t \tthis.sigmoidTable \t= new double[tableSize]; \n\t\t \n\t\t\tfor (int i = 0; i < tableSize; i++) {\n\t\t\t\tdouble j = maxExponent * (i+1) / (double) (tableSize); //proportion of max, quantized by 1000\n\t\t\t\t\tsigmoidTable[i] = Math.exp(-1*j); // e^-z\n\t\t\t\t\tsigmoidTable[i] = 1 / (1 + sigmoidTable[i]); // 1 / 1 + e^-z\n\t\t\t\n\t\n\t\t\t}\n\t\t}\n\t \n\t \n\t /**\n\t * Look up the sigmoid for an incoming value\n\t * @param scalarproduct\n\t * @return\n\t */\n\t\n\t public double sigmoid(double z)\n\t {\t\tdouble answer = 0;\n\t\t\tif (z >= maxExponent) \t\treturn 1;\n\t\t\telse if (z <= -maxExponent) return 0;\n\t\t\telse \n\t\t\t\t{\t\n\t\t\t\t\tdouble index \t= tableSize * Math.abs(z) / (double) maxExponent; \n\t\t\t\t\tanswer \t\t\t= sigmoidTable[(int) index];\n\t\t\t\t\tif (z < 0) answer = 1 - answer;\n\t\t\t\t}\n\t \treturn answer;\n\t }\n\n\n\n\npublic static void main(String[] args)\n{\n\tjava.util.Random random = new java.util.Random();\n\t\n\tSigmoidTable st = new SigmoidTable(6, 1000);\n\tfor (int q = -9; q < 10; q++)\n\t{\n\tdouble test = new Double(q).doubleValue()+random.nextDouble();\n\tSystem.out.println(test +\"\\t\"+st.sigmoid(test));\n\tSystem.out.print(test+\"\\t\");\n\ttest = Math.pow(Math.E, -1*test); // e^-z\n\ttest = 1 / (1 + test); // 1 / 1 + e^-z\n\tSystem.out.print(test+\"\\n\");\n\tSystem.out.println(\"---------------------------\");\n\t}\n\n}\n}", "public class BinaryVector implements Vector {\n \n\n /**\n * Enumeration of normalization options.\n */\n public enum BinaryNormalizationMethod {\n /**\n * Set to one if more ones than zeros recorded in the voting record for\n * this dimension (zeros are recorded implicitly, by counting total votes),\n * and split at random (50% chance of 1) if the same number of ones and zeros.\n * Otherwise zero.\n */\n SPATTERCODE,\n /**\n * The probability of a one is equal to the probability of the proportion of 1 to 0\n * votes for this dimension, assuming a Gaussian distribution\n */\n PROBABILISTIC\n }\n\n public static BinaryNormalizationMethod NORMALIZE_METHOD = BinaryNormalizationMethod.SPATTERCODE;\n public static void setNormalizationMethod(BinaryNormalizationMethod normalizationMethod) {\n logger.info(\"Globally setting binary vector NORMALIZATION_METHOD to: '\" + normalizationMethod + \"'\");\n NORMALIZE_METHOD = normalizationMethod;\n }\n\n public static final Logger logger = Logger.getLogger(BinaryVector.class.getCanonicalName());\n\n /** Returns {@link VectorType#BINARY} */\n public VectorType getVectorType() { return VectorType.BINARY; }\n\n // TODO: Determing proper interface for default constants.\n /**\n * Number of decimal places to consider in weighted superpositions of binary vectors.\n * Higher precision requires additional memory during training.\n */\n public static final int BINARY_VECTOR_DECIMAL_PLACES = 2;\n public static final boolean BINARY_BINDING_WITH_PERMUTE = false;\n\n\n private static int DEBUG_PRINT_LENGTH = 64;\n private Random random;\n private final int dimension;\n\n /**\n * Elemental representation for binary vectors. \n */\n protected FixedBitSet bitSet;\n private boolean isSparse;\n private AtomicBoolean unTallied = new AtomicBoolean(true);\n\n /**\n * Representation of voting record for superposition. Each FixedBitSet object contains one bit\n * of the count for the vote in each dimension. The count for any given dimension is derived from\n * all of the bits in that dimension across the FixedBitSets in the voting record.\n *\n * The precision of the voting record (in number of decimal places) is defined upon initialization.\n * By default, if the first weight added is an integer, rounding occurs to the nearest integer.\n * Otherwise, rounding occurs to the second binary place.\n */\n private ArrayList<FixedBitSet> votingRecord;\n\n /** BINARY_VECTOR_DECIMAL_PLACESum of the weights with which vectors have been added into the voting record */\n private AtomicLong totalNumberOfVotes = new AtomicLong(0);\n // TODO(widdows) Understand and comment this.\n private long minimum = 0;\n\n // Used only for temporary internal storage.\n private FixedBitSet tempSet;\n\n public BinaryVector(int dimension) {\n // Check \"multiple-of-64\" constraint, to facilitate permutation of 64-bit chunks\n if (dimension % 64 != 0) {\n throw new IllegalArgumentException(\"Dimension should be a multiple of 64: \"\n + dimension + \" will lead to trouble!\");\n }\n this.dimension = dimension;\n this.bitSet = new FixedBitSet(dimension);\n this.isSparse = true;\n this.random = new Random();\n\n }\n\n\n\n /**\n * Returns a new copy of this vector, in dense format.\n */\n @SuppressWarnings(\"unchecked\")\n public BinaryVector copy() {\n BinaryVector copy = new BinaryVector(dimension);\n copy.bitSet = (FixedBitSet) bitSet.clone();\n if (!isSparse)\n copy.votingRecord = (ArrayList<FixedBitSet>) votingRecord.clone();\n if (tempSet != null) {\n copy.tempSet = tempSet.clone();\n }\n copy.minimum = minimum;\n copy.totalNumberOfVotes = new AtomicLong(totalNumberOfVotes.longValue());\n copy.unTallied = new AtomicBoolean(unTallied.get());\n copy.isSparse = isSparse;\n\n return copy;\n }\n \n public String toString() {\n StringBuilder debugString = new StringBuilder(\"\");\n \n if (isSparse) {\n debugString.append(\" Sparse. First \" + DEBUG_PRINT_LENGTH + \" values are:\\n\");\n for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.get(x) ? \"1 \" : \"0 \");\n debugString.append(\"\\nCardinality \" + bitSet.cardinality()+\"\\n\");\n }\n else {\n\n debugString.append(\" Dense. First \" + DEBUG_PRINT_LENGTH + \" values are:\\n\");\n\n for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.get(x) ? \"1\" : \"0\");\n // output voting record for first DEBUG_PRINT_LENGTH dimension\n\n \n debugString.append(\"\\nVOTING RECORD: \\n\");\n for (int y =0; y < votingRecord.size(); y++)\n {\n for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(votingRecord.get(y).get(x) ? \"1 \" : \"0 \");\n debugString.append(\"\\n\");\n }\n \n // Calculate actual values for first 20 dimension\n double[] actualvals = new double[DEBUG_PRINT_LENGTH];\n debugString.append(\"COUNTS : \");\n\n for (int x =0; x < votingRecord.size(); x++) {\n for (int y = 0; y < DEBUG_PRINT_LENGTH; y++) {\n if (votingRecord.get(x).get(y)) actualvals[y] += Math.pow(2, x);\n }\n }\n\n for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) {\n debugString.append((long) ((minimum + actualvals[x]) / Math.pow(10, BINARY_VECTOR_DECIMAL_PLACES)) + \" \");\n }\n\n // TODO - output count from first DEBUG_PRINT_LENGTH dimension\n debugString.append(\"\\nNORMALIZED: \");\n this.normalize();\n for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.get(x) + \" \");\n debugString.append(\"\\n\");\n\n\n\n debugString.append(\"\\nCardinality \" + bitSet.cardinality()+\"\\n\");\n debugString.append(\"Votes \" + totalNumberOfVotes.get()+\"\\n\");\n debugString.append(\"Minimum \" + minimum + \"\\n\");\n \n debugString.append(\"\\n\");\n }\n return debugString.toString();\n }\n\n @Override\n public int getDimension() {\n return dimension;\n }\n\n public BinaryVector createZeroVector(int dimension) {\n // Check \"multiple-of-64\" constraint, to facilitate permutation of 64-bit chunks\n if (dimension % 64 != 0) {\n logger.severe(\"Dimension should be a multiple of 64: \"\n + dimension + \" will lead to trouble!\");\n }\n return new BinaryVector(dimension);\n }\n\n @Override\n public boolean isZeroVector() {\n if (isSparse)\n {\n return bitSet.cardinality() == 0;\n } else {\n return (votingRecord == null) || (votingRecord.size() == 0) || (votingRecord.size()==1 && votingRecord.get(0).cardinality() == 0);\n }\n }\n\n @Override\n /**\n * Generates a basic elemental vector with a given number of 1's and otherwise 0's.\n * For binary vectors, the numnber of 1's and 0's must be the same, half the dimension.\n *\n * @return representation of basic binary vector.\n */\n public BinaryVector generateRandomVector(int dimension, int numEntries, Random random) {\n // Check \"multiple-of-64\" constraint, to facilitate permutation of 64-bit chunks\n if (dimension % 64 != 0) {\n throw new IllegalArgumentException(\"Dimension should be a multiple of 64: \"\n + dimension + \" will lead to trouble!\");\n }\n // Check for balance between 1's and 0's\n if (numEntries != dimension / 2) {\n logger.severe(\"Attempting to create binary vector with unequal number of zeros and ones.\"\n + \" Unlikely to produce meaningful results. Therefore, seedlength has been set to \"\n + \" dimension/2, as recommended for binary vectors\");\n numEntries = dimension / 2;\n }\n\n BinaryVector randomVector = new BinaryVector(dimension);\n randomVector.bitSet = new FixedBitSet(dimension);\n\n ArrayList<Integer> dimensions = new ArrayList<Integer>();\n\n for (int q=0; q< dimension; q++)\n dimensions.add(q);\n\n Collections.shuffle(dimensions, random);\n\n for (int r=0; r < numEntries; r++)\n {\n int testPlace = dimensions.get(r);\n randomVector.bitSet.set(testPlace);\n }\n return randomVector;\n }\n \n\n\n @Override\n /**\n * Measures overlap of two vectors using 1 - normalized Hamming distance\n *\n * Causes this and other vector to be converted to dense representation.\n */\n public double measureOverlap(Vector other) {\n IncompatibleVectorsException.checkVectorsCompatible(this, other);\n if (isZeroVector()) return 0;\n BinaryVector binaryOther = (BinaryVector) other;\n if (binaryOther.isZeroVector()) return 0;\n\n // Calculate hamming distance in place. Have not checked if this is fastest performance.\n double hammingDistance = BinaryVectorUtils.xorCount(this.bitSet, binaryOther.bitSet);\n return 2*(0.5 - (hammingDistance / (double) dimension));\n }\n\n @Override\n /**\n * Adds the other vector to this one. If this vector was an elemental vector, the \n * \"semantic vector\" components (i.e. the voting record and temporary bitset) will be\n * initialized.\n *\n * Note that the precision of the voting record (in decimal places) is decided at this point:\n * if the initialization weight is an integer, rounding will occur to the nearest integer.\n * If not, rounding will occur to the second decimal place.\n *\n * This is an attempt to save space, as voting records can be prohibitively expansive\n * if not contained.\n */\n public synchronized void superpose(Vector other, double weight, int[] permutation) {\n IncompatibleVectorsException.checkVectorsCompatible(this, other);\n if (weight == 0d) return;\n if (other.isZeroVector()) return;\n \n BinaryVector binaryOther = (BinaryVector) other;\n boolean flippedBitSet = false; //for subtraction\n \n if (weight < 0) //subtraction\n {\n weight = Math.abs(weight);\n binaryOther.bitSet.flip(0, binaryOther.getDimension());\n flippedBitSet = true;\n }\n \n if (isSparse) {\n elementalToSemantic();\n }\n\n if (permutation != null) {\n // Rather than permuting individual dimensions, we permute 64 bit groups at a time.\n // This should be considerably quicker, and dimension/64 should allow for sufficient\n // permutations\n if (permutation.length != dimension / 64) {\n throw new IllegalArgumentException(\"Binary vector of dimension \" + dimension\n + \" must have permutation of length \" + dimension / 64\n + \" not \" + permutation.length);\n }\n //TODO permute in place and reverse, to avoid creating a new BinaryVector here\n BinaryVector temp = binaryOther.copy();\n temp.permute(permutation);\n superposeBitSet(temp.bitSet, weight);\n }\n else {\n superposeBitSet(binaryOther.bitSet, weight);\n }\n \n if (flippedBitSet) binaryOther.bitSet.flip(0, binaryOther.getDimension()); //return to original configuration\n unTallied.set(true); //there are votes that haven't been tallied yet\n \n }\n\n /**\n * This method is the first of two required to facilitate superposition. The underlying representation\n * (i.e. the voting record) is an ArrayList of FixedBitSet, each with dimension \"dimension\", which can\n * be thought of as an expanding 2D array of bits. Each column keeps count (in binary) for the respective\n * dimension, and columns are incremented in parallel by sweeping a bitset across the rows. In any dimension\n * in which the BitSet to be added contains a \"1\", the effect will be that 1's are changed to 0's until a\n * new 1 is added (e.g. the column '110' would become '001' and so forth).\n *\n * The first method deals with floating point issues, and accelerates superposition by decomposing\n * the task into segments.\n *\n * @param incomingBitSet\n * @param weight\n */\n protected synchronized void superposeBitSet(FixedBitSet incomingBitSet, double weight) {\n // If fractional weights are used, encode all weights as integers (1000 x double value).\n weight = (int) Math.round(weight * Math.pow(10, BINARY_VECTOR_DECIMAL_PLACES));\n if (weight == 0) return;\n\n // Keep track of number (or cumulative weight) of votes.\n totalNumberOfVotes.set(totalNumberOfVotes.get() + (int) weight);\n\n // Decompose superposition task such that addition of some power of 2 (e.g. 64) is accomplished\n // by beginning the process at the relevant row (e.g. 7) instead of starting multiple (e.g. 64)\n // superposition processes at the first row.\n int logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2)));\n\n if (logFloorOfWeight < votingRecord.size() - 1) {\n while (logFloorOfWeight > 0) {\n superposeBitSetFromRowFloor(incomingBitSet, logFloorOfWeight);\n weight = weight - (int) Math.pow(2,logFloorOfWeight);\n logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2)));\n }\n }\n\n // Add remaining component of weight incrementally.\n for (int x = 0; x < weight; x++)\n superposeBitSetFromRowFloor(incomingBitSet, 0);\n }\n\n /**\n * Performs superposition from a particular row by sweeping a bitset across the voting record\n * such that for any column in which the incoming bitset contains a '1', 1's are changed\n * to 0's until a new 1 can be added, facilitating incrementation of the\n * binary number represented in this column.\n *\n * @param incomingBitSet the bitset to be added\n * @param rowfloor the index of the place in the voting record to start the sweep at\n */\n protected synchronized void superposeBitSetFromRowFloor(FixedBitSet incomingBitSet, int rowfloor) {\n // Attempt to save space when minimum value across all columns > 0\n // by decrementing across the board and raising the minimum where possible.\n int max = getMaximumSharedWeight();\n\n if (max > 0) {\n decrement(max);\n }\n\n // Handle overflow: if any column that will be incremented\n // contains all 1's, add a new row to the voting record.\n tempSet.xor(tempSet);\n tempSet.xor(incomingBitSet);\n\n for (int x = rowfloor; x < votingRecord.size() && tempSet.cardinality() > 0; x++) {\n tempSet.and(votingRecord.get(x));\n }\n\n if (tempSet.cardinality() > 0) {\n votingRecord.add(new FixedBitSet(dimension));\n }\n\n // Sweep copy of bitset to be added across rows of voting record.\n // If a new '1' is added, this position in the copy is changed to zero\n // and will not affect future rows.\n // The xor step will transform 1's to 0's or vice versa for \n // dimension in which the temporary bitset contains a '1'.\n votingRecord.get(rowfloor).xor(incomingBitSet);\n\n tempSet.xor(tempSet);\n tempSet.xor(incomingBitSet);\n\n for (int x = rowfloor + 1; x < votingRecord.size(); x++) {\n tempSet.andNot(votingRecord.get(x-1)); //if 1 already added, eliminate dimension from tempSet\n votingRecord.get(x).xor(tempSet);\n // votingRecord.get(x).trimTrailingZeros(); //attempt to save in sparsely populated rows\n }\n }\n\n /**\n * Reverses a string - simplifies the decoding of the binary vector for the 'exact' method\n * although it wouldn't be difficult to reverse the counter instead\n */\n public static String reverse(String str) {\n if ((null == str) || (str.length() <= 1)) {\n return str;\n }\n return new StringBuffer(str).reverse().toString();\n }\n\n /**\n * Sets {@link #tempSet} to be a bitset with a \"1\" in the position of every dimension\n * in the {@link #votingRecord} that exactly matches the target number.\n */\n private synchronized void setTempSetToExactMatches(long target) {\n if (target == 0) {\n tempSet.set(0, dimension);\n tempSet.xor(votingRecord.get(0));\n for (int x = 1; x < votingRecord.size(); x++)\n tempSet.andNot(votingRecord.get(x));\n } else\n {\n String inbinary = reverse(Long.toBinaryString(target));\n tempSet.xor(tempSet);\n try {\n tempSet.xor(votingRecord.get(inbinary.indexOf(\"1\"))); //this requires error checking, it is throwing an index out of bounds exception\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n for (int q =0; q < votingRecord.size(); q++) {\n if (q < inbinary.length() && inbinary.charAt(q) == '1')\n tempSet.and(votingRecord.get(q));\n else\n tempSet.andNot(votingRecord.get(q));\n }\n }\n }\n\n /**\n * This method is used determine which dimension will receive 1 and which 0 when the voting\n * process is concluded. It produces an FixedBitSet in which\n * \"1\" is assigned to all dimension with a count > 50% of the total number of votes (i.e. more 1's than 0's added)\n * \"0\" is assigned to all dimension with a count < 50% of the total number of votes (i.e. more 0's than 1's added)\n * \"0\" or \"1\" are assigned to all dimension with a count = 50% of the total number of votes (i.e. equal 1's and 0's added)\n *\n * @return an FixedBitSet representing the superposition of all vectors added up to this point\n */\n protected synchronized FixedBitSet concludeVote() {\n if (votingRecord.size() == 0 || votingRecord.size() == 1 && votingRecord.get(0).cardinality() ==0) return new FixedBitSet(dimension);\n else return concludeVote(totalNumberOfVotes.get());\n }\n\n protected synchronized FixedBitSet concludeVote(long target) {\n long target2 = (long) Math.ceil((double) target / (double) 2);\n target2 = target2 - minimum;\n \n // Unlikely other than in testing: minimum more than half the votes\n if (target2 < 0) {\n FixedBitSet ans = new FixedBitSet(dimension);\n ans.set(0, dimension);\n return ans;\n }\n\n boolean even = (target % 2 == 0);\n FixedBitSet result = concludeVote(target2, votingRecord.size() - 1);\n\n if (even) {\n setTempSetToExactMatches(target2);\n boolean switcher = true;\n // 50% chance of being true with split vote.\n int q = tempSet.nextSetBit(0);\n while (q != DocIdSetIterator.NO_MORE_DOCS)\n {\n switcher = !switcher;\n if (switcher) tempSet.clear(q);\n if (q+1 >= tempSet.length()) q = DocIdSetIterator.NO_MORE_DOCS;\n else q = tempSet.nextSetBit(q+1);\n }\n result.andNot(tempSet);\n\n }\n return result;\n }\n\n protected synchronized FixedBitSet concludeVote(long target, int row_ceiling) {\n /**\n logger.info(\"Entering conclude vote, target \" + target + \" row_ceiling \" + row_ceiling +\n \"voting record \" + votingRecord.size() +\n \" minimum \"+ minimum + \" index \"+ Math.log(target)/Math.log(2) +\n \" vector\\n\" + toString());\n **/\n if (target == 0) {\n FixedBitSet atLeastZero = new FixedBitSet(dimension);\n atLeastZero.set(0, dimension);\n return atLeastZero;\n }\n\n double rowfloor = Math.log(target)/Math.log(2);\n int row_floor = (int) Math.floor(rowfloor); //for 0 index\n long remainder = target - (long) Math.pow(2, row_floor);\n\n //System.out.println(target+\"\\t\"+rowfloor+\"\\t\"+row_floor+\"\\t\"+remainder);\n\n if (row_floor >= votingRecord.size()) //In this instance, the number we are checking for is higher than the capacity of the voting record\n {\n return new FixedBitSet(dimension);\n }\n \n if (row_ceiling == 0 && target == 1) {\n return votingRecord.get(0);\n }\n\n if (remainder == 0) {\n // Simple case - the number we're looking for is 2^n, so anything with a \"1\" in row n or above is true.\n FixedBitSet definitePositives = new FixedBitSet(dimension);\n for (int q = row_floor; q <= row_ceiling; q++)\n definitePositives.or(votingRecord.get(q));\n return definitePositives;\n }\n else {\n // Simple part of complex case: first get anything with a \"1\" in a row above n (all true).\n FixedBitSet definitePositives = new FixedBitSet(dimension);\n for (int q = row_floor+1; q <= row_ceiling; q++)\n definitePositives.or(votingRecord.get(q));\n\n // Complex part of complex case: get those that have a \"1\" in the row of n.\n FixedBitSet possiblePositives = (FixedBitSet) votingRecord.get(row_floor).clone();\n FixedBitSet definitePositives2 = concludeVote(remainder, row_floor-1);\n\n possiblePositives.and(definitePositives2);\n definitePositives.or(possiblePositives);\n return definitePositives;\n }\n }\n\n /**\n * Decrement every dimension. Assumes at least one count in each dimension\n * i.e: no underflow check currently - will wreak havoc with zero counts\n */\n public synchronized void decrement() {\n tempSet.set(0, dimension);\n for (int q = 0; q < votingRecord.size(); q++) {\n votingRecord.get(q).xor(tempSet);\n tempSet.and(votingRecord.get(q));\n }\n }\n\n /**\n * Decrement every dimension by the number passed as a parameter. Again at least one count in each dimension\n * i.e: no underflow check currently - will wreak havoc with zero counts\n */\n public synchronized void decrement(int weight) {\n if (weight == 0) return;\n minimum+= weight;\n\n int logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2)));\n\n if (logfloor < votingRecord.size() - 1) {\n while (logfloor > 0) {\n selectedDecrement(logfloor);\n weight = weight - (int) Math.pow(2,logfloor);\n logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2)));\n }\n }\n\n for (int x = 0; x < weight; x++) {\n decrement();\n }\n }\n\n public synchronized void selectedDecrement(int floor) {\n tempSet.set(0, dimension);\n for (int q = floor; q < votingRecord.size(); q++) {\n votingRecord.get(q).xor(tempSet);\n tempSet.and(votingRecord.get(q));\n }\n }\n\n /**\n * Returns the highest value shared by all dimensions.\n */\n protected synchronized int getMaximumSharedWeight() {\n int thismaximum = 0;\n tempSet.xor(tempSet); // Reset tempset to zeros.\n for (int x = votingRecord.size() - 1; x >= 0; x--) {\n tempSet.or(votingRecord.get(x));\n if (tempSet.cardinality() == dimension) {\n thismaximum += (int) Math.pow(2, x);\n tempSet.xor(tempSet);\n }\n }\n return thismaximum;\n }\n\n /**\n * Implements binding using permutations and XOR. \n */\n public void bind(Vector other, int direction) {\n IncompatibleVectorsException.checkVectorsCompatible(this, other);\n BinaryVector binaryOther = (BinaryVector) other.copy();\n if (direction > 0) {\n //as per Kanerva 2009: bind(A,B) = perm+(A) XOR B = C\n //this also functions as the left inverse: left inverse (A,C) = perm+(A) XOR C = B \n this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, 1)); //perm+(A)\n this.bitSet.xor(binaryOther.bitSet); //perm+(A) XOR B\n\n } else {\n //as per Kanerva 2009: right inverse(C,B) = perm-(C XOR B) = perm-(perm+(A)) = A \n this.bitSet.xor(binaryOther.bitSet); //C XOR B\n this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, -1)); //perm-(C XOR B) = A\n }\n }\n\n /**\n * Implements inverse of binding using permutations and XOR. \n */\n public void release(Vector other, int direction) {\n if (!BINARY_BINDING_WITH_PERMUTE)\n bind(other);\n else\n bind (other, direction);\n }\n\n @Override\n /**\n * Implements binding using exclusive OR. \n */\n public void bind(Vector other) {\n IncompatibleVectorsException.checkVectorsCompatible(this, other);\n if (!BINARY_BINDING_WITH_PERMUTE) {\n BinaryVector binaryOther = (BinaryVector) other;\n this.bitSet.xor(binaryOther.bitSet);\n } else {\n bind(other, 1);\n }\n \n //cleanup - the voting record is erased upon \n //binding, so tallying the votes won't walk back \n //the bind\n votingRecord = new ArrayList<FixedBitSet>();\n votingRecord.add((FixedBitSet) bitSet.clone());\n totalNumberOfVotes.set(1);\n tempSet = new FixedBitSet(dimension);\n minimum = 0;\n }\n\n @Override\n /**\n * Implements inverse binding using exclusive OR. \n */\n public void release(Vector other) {\n\n if (!BINARY_BINDING_WITH_PERMUTE)\n bind(other);\n else\n bind(other, -1);\n }\n\n @Override\n /**\n * Normalizes the vector, converting sparse to dense representations in the process. This approach deviates from the \"majority rule\" \n * approach that is standard in the Binary Spatter Code(). Rather, the probability of assigning a one in a particular dimension \n * is a function of the probability of encountering the number of votes in the voting record in this dimension.\n *\n * This will be slower than normalizeBSC() below, but discards less information with positive effects on accuracy in preliminary experiments\n *\n * As a simple example to illustrate why this would be the case, consider the superposition of vectors for the terms \"jazz\",\"jazz\" and \"rock\" \n * With the BSC normalization, the vector produced is identical to \"jazz\" (as jazz wins the vote in each case). With probabilistic normalization,\n * the vector produced is somewhat similar to both \"jazz\" and \"rock\", with a similarity that is proportional to the weights assigned to the \n * superposition, e.g. 0.624000:jazz; 0.246000:rock\n */\n public synchronized void normalize() {\n if (votingRecord == null) return;\n if (votingRecord.size() == 1) {\n this.bitSet = votingRecord.get(0);\n return;\n }\n \n if (NORMALIZE_METHOD.equals(BinaryNormalizationMethod.SPATTERCODE))\n {\n //faster majority rule normalization\n this.bitSet = concludeVote();\n }\n else\n {\t//slower probabilistic normalization\n //clear bitset;\n this.bitSet.xor(this.bitSet);\n\n //Ensure that the same set of superposed vectors will always produce the same result\n long theSuperpositionSeed = 0;\n for (int q =0; q < votingRecord.size(); q++)\n theSuperpositionSeed += votingRecord.get(q).getBits()[0];\n\n random.setSeed(theSuperpositionSeed);\n\n //Determine value above the universal minimum for each dimension of the voting record\n long max = totalNumberOfVotes.get();\n\n //Determine the maximum possible votes on the voting record\n int maxpossiblevotesonrecord = 0;\n\n for (int q=0; q < votingRecord.size(); q++)\n maxpossiblevotesonrecord += Math.pow(2, q);\n\n //For each possible value on the record, get a BitSet with a \"1\" in the\n //position of the dimensions that match this value\n for (int x = 1; x <= maxpossiblevotesonrecord; x++) {\n this.setTempSetToExactMatches(x);\n\n //no exact matches\n if (this.tempSet.cardinality() == 0) continue;\n\n //For each y==1 on said BitSet (indicating votes in dimension[y] == x)\n int y = tempSet.nextSetBit(0);\n\n //determine total number of votes\n double votes = minimum+x;\n\n //calculate standard deviations above/below the mean of max/2\n double z = (votes - (max/2)) / (Math.sqrt(max)/2);\n\n //find proportion of data points anticipated within z standard deviations of the mean (assuming approximately normal distribution)\n double proportion = erf(z/Math.sqrt(2));\n\n //convert into a value between 0 and 1 (i.e. centered on 0.5 rather than centered on 0)\n proportion = (1+proportion) /2;\n\n while (y != DocIdSetIterator.NO_MORE_DOCS) {\n //probabilistic normalization\n if ((random.nextDouble()) <= proportion) this.bitSet.set(y);\n y++;\n if (y == this.dimension) break;\n y = tempSet.nextSetBit(y);\n }\n }\n }\n //housekeeping\n votingRecord = new ArrayList<FixedBitSet>();\n votingRecord.add((FixedBitSet) bitSet.clone());\n totalNumberOfVotes.set(1);\n tempSet = new FixedBitSet(dimension);\n minimum = 0;\n }\n\n\n /**\n * approximation of error function, equation 7.1.27 from\n * Abramowitz, M. and Stegun, I. A. (Eds.). \"Repeated Integrals of the Error Function.\" S 7.2 \n * in Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables, \n * 9th printing. New York: Dover, pp. 299-300, 1972.\n * error of approximation <= 5*10^-4\n */\n public double erf(double z) {\n //erf(-x) == -erf(x)\n double sign = Math.signum(z);\n z = Math.abs(z);\n\n double a1 = 0.278393, a2 = 0.230389, a3 = 0.000972, a4 = 0.078108;\n double sumterm = 1 + a1*z + a2*Math.pow(z,2) + a3*Math.pow(z,3) + a4*Math.pow(z,4);\n return sign * ( 1-1/(Math.pow(sumterm, 4)));\n }\n\n /**\n * Faster normalization according to the Binary Spatter Code's \"majority\" rule \n */\n public synchronized void normalizeBSC() {\n if (!isSparse)\n this.bitSet = concludeVote();\n\n votingRecord = new ArrayList<FixedBitSet>();\n votingRecord.add((FixedBitSet) bitSet.clone());\n totalNumberOfVotes.set(1);\n tempSet = new FixedBitSet(dimension);\n minimum = 0;\n }\n\n /**\n * Counts votes without normalizing vector (i.e. voting record is not altered). Used in SemanticVectorCollider.\n */\n public synchronized void tallyVotes() {\n if (isSparse) elementalToSemantic();\n if (unTallied.get()) //only count if there are votes since the last tally\n try { this.bitSet = concludeVote();\n unTallied.set(false); } catch (Exception e) {e.printStackTrace();}\n }\n\n @Override\n /**\n * Writes vector out to object output stream. Converts to dense format if necessary.\n */\n public void writeToLuceneStream(IndexOutput outputStream) {\n if (isSparse) {\n elementalToSemantic();\n }\n long[] bitArray = bitSet.getBits();\n\n for (int i = 0; i < bitArray.length; i++) {\n try {\n outputStream.writeLong(bitArray[i]);\n } catch (IOException e) {\n logger.severe(\"Couldn't write binary vector to lucene output stream.\");\n e.printStackTrace();\n }\n }\n }\n\n /**\n * Writes vector out to object output stream. Converts to dense format if necessary. Truncates to length k.\n */\n public void writeToLuceneStream(IndexOutput outputStream, int k) {\n if (isSparse) {\n elementalToSemantic();\n }\n long[] bitArray = bitSet.getBits();\n\n for (int i = 0; i < k/64; i++) {\n try {\n outputStream.writeLong(bitArray[i]);\n } catch (IOException e) {\n logger.severe(\"Couldn't write binary vector to lucene output stream.\");\n e.printStackTrace();\n }\n }\n }\n\n \n @Override\n /**\n * Reads a (dense) version of a vector from a Lucene input stream. \n */\n public void readFromLuceneStream(IndexInput inputStream) {\n long bitArray[] = new long[(dimension / 64)];\n\n for (int i = 0; i < dimension / 64; ++i) {\n try {\n bitArray[i] = inputStream.readLong();\n } catch (IOException e) {\n logger.severe(\"Couldn't read binary vector from lucene output stream.\");\n e.printStackTrace();\n }\n }\n this.bitSet = new FixedBitSet(bitArray, dimension);\n this.isSparse = true;\n }\n\n @Override\n /**\n * Writes vector to a string of the form 010 etc. (no delimiters). \n *\n * No terminating newline or delimiter.\n */\n public String writeToString() {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < dimension; ++i) {\n builder.append(this.bitSet.get(i) ? \"1\" : \"0\");\n }\n return builder.toString();\n }\n\n /**\n * Writes vector to a string of the form 010 etc. (no delimiters). \n *\n * No terminating newline or delimiter.\n */\n public String writeLongToString() {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < (bitSet.getBits().length); ++i) {\n builder.append(Long.toString(bitSet.getBits()[i])+\"|\");\n }\n return builder.toString();\n }\n\n @Override\n /**\n * Writes vector from a string of the form 01001 etc.\n */\n public void readFromString(String input) {\n if (input.length() != dimension) {\n throw new IllegalArgumentException(\"Found \" + (input.length()) + \" possible coordinates: \"\n + \"expected \" + dimension);\n }\n\n for (int i = 0; i < dimension; ++i) {\n if (input.charAt(i) == '1')\n bitSet.set(i);\n }\n }\n\n /**\n * Automatically translate elemental vector (no storage capacity) into \n * semantic vector (storage capacity initialized, this will occupy RAM)\n */\n protected void elementalToSemantic() {\n if (!isSparse) {\n logger.warning(\"Tried to transform an elemental vector which is not in fact elemental.\"\n + \"This may be a programming error.\");\n return;\n }\n votingRecord = new ArrayList<FixedBitSet>();\n tempSet = new FixedBitSet(dimension);\n if (bitSet.cardinality() != 0)\n this.superposeBitSet(bitSet.clone(), 1);\n isSparse = false;\n }\n\n /**\n * Permute the long[] array underlying the FixedBitSet binary representation\n */\n public void permute(int[] permutation) {\n if (permutation.length != getDimension() / 64) {\n throw new IllegalArgumentException(\"Binary vector of dimension \" + getDimension()\n + \" must have permutation of length \" + getDimension() / 64\n + \" not \" + permutation.length);\n }\n //TODO permute in place without creating additional long[] (if proves problematic at scale)\n long[] coordinates = bitSet.getBits();\n long[] newCoordinates = new long[coordinates.length];\n for (int i = 0; i < coordinates.length; ++i) {\n int positionToAdd = i;\n positionToAdd = permutation[positionToAdd];\n newCoordinates[i] = coordinates[positionToAdd];\n }\n bitSet = new FixedBitSet(newCoordinates, getDimension());\n }\n\n // Available for testing and copying.\n protected BinaryVector(FixedBitSet inSet) {\n this.dimension = (int) inSet.length();\n\n this.bitSet = inSet;\n }\n\n // Available for testing\n protected int bitLength() {\n return bitSet.getBits().length;\n }\n\n // Monitor growth of voting record.\n protected int numRows() {\n if (isSparse) return 0;\n return votingRecord.size();\n }\n\n //access bitset directly\n protected FixedBitSet getCoordinates() {\n // TODO Auto-generated method stub\n return this.bitSet;\n }\n\n //access bitset directly\n protected void setCoordinates(FixedBitSet incomingBitSet) {\n // TODO Auto-generated method stub\n this.bitSet = incomingBitSet;\n }\n\n //set DEBUG_PRINT_LENGTH\n public static void setDebugPrintLength(int length) {\n DEBUG_PRINT_LENGTH = length;\n }\n\n\n\n}", "public class ComplexVector implements Vector {\r\n public static final Logger logger = Logger.getLogger(ComplexVector.class.getCanonicalName());\r\n\r\n /** Returns {@link VectorType#COMPLEX} */\r\n public VectorType getVectorType() {\r\n return VectorType.COMPLEX;\r\n }\r\n\r\n /**\r\n * We use the 'MODE' enumeration to keep track of which mode the complex vector is in. By 'MODE'\r\n * we mean whether the vector is using POLAR_SPARSE, POLAR_DENSE or CARTESIAN coordinates.\r\n *\r\n * CARTESIAN uses two 32 bit floats for each element, one for the real coordinate\r\n * and one for the imaginary.\r\n */\r\n public static enum Mode {\r\n /** Uses a nonnegative 16 bit short for each phase angle. The value -1 is reserved for\r\n * representing the complex number zero, i.e., there is no entry in this dimension. */\r\n POLAR_DENSE,\r\n /** Uses a pair of 16 bit shorts for each (offset, phase angle) pair. */\r\n POLAR_SPARSE,\r\n /** Uses a pair of 32 bit floats for each (real, imaginary) complex coordinate. */\r\n CARTESIAN,\r\n /** As above, but with normalization to unit length and the hermitian scalar product\r\n * instead of the alternatives proposed by Plate */\r\n HERMITIAN\r\n }\r\n\r\n /**\r\n * The dominant mode used for normalizing and comparing vectors.\r\n */\r\n private static Mode DOMINANT_MODE = Mode.CARTESIAN;\r\n\r\n /**\r\n * Sets the dominant mode. {@link VectorType#COMPLEX} uses {@link Mode#POLAR_DENSE}\r\n * and {@link VectorType#COMPLEXFLAT} uses {@link Mode#CARTESIAN}.\r\n * More recent experiments have used {@link Mode#HERMITIAN}. Use with care!\r\n */\r\n public static void setDominantMode(Mode mode) {\r\n if (DOMINANT_MODE == mode) return;\r\n if (mode == Mode.POLAR_SPARSE) {\r\n throw new IllegalArgumentException(\"POLAR_SPARSE cannot be used as dominant mode.\");\r\n }\r\n logger.info(\"Globally setting complex DOMINANT_MODE to: '\" + mode + \"'\");\r\n DOMINANT_MODE = mode;\r\n }\r\n\r\n public static Mode getDominantMode() {\r\n return DOMINANT_MODE;\r\n }\r\n\r\n /**\r\n * The actual number of float coordinates is 'dimension' X 2 because of real and\r\n * imaginary components.\r\n */\r\n private final int dimension;\r\n /**\r\n * Dense Cartesian representation. Coordinates can be anything expressed by floats.\r\n */\r\n private float[] coordinates;\r\n /**\r\n * Dense Polar representation. Coordinates can be anything expressed by 16 bit chars.\r\n * The complex elements are assumed to all lie on the unit circle, ie. all amplitudes\r\n * equal 1.\r\n */\r\n private short[] phaseAngles;\r\n\r\n /**\r\n * Sparse representation using a 16 bit Java char for storing an offset (in position 2i)\r\n * and a corresponding phase angle (in position 2i + 1) for each element.\r\n * The offset is the index into the array and the phase angle is a random\r\n * value between 0 and 65535 representing angles between 0 and 2PI.\r\n * See also {@link #generateRandomVector}.\r\n */\r\n private short[] sparseOffsets;\r\n private Mode opMode;\r\n\r\n protected ComplexVector(int dimension, Mode opMode) {\r\n this.opMode = opMode;\r\n this.dimension = dimension;\r\n switch (opMode) {\r\n case POLAR_SPARSE:\r\n this.sparseOffsets = new short[0];\r\n return;\r\n case POLAR_DENSE:\r\n this.phaseAngles = new short[dimension];\r\n for (int i = 0; i < dimension; ++i) phaseAngles[i] = -1; // Initialize to complex zero vector.\r\n case CARTESIAN:\r\n this.coordinates = new float[2 * dimension];\r\n case HERMITIAN:\r\n this.coordinates = new float[2 * dimension];\r\n }\r\n }\r\n\r\n /**\r\n * Returns a new copy of this vector, in dense format.\r\n */\r\n public ComplexVector copy() {\r\n ComplexVector copy = new ComplexVector(dimension, opMode);\r\n switch (opMode) {\r\n case POLAR_SPARSE:\r\n copy.sparseOffsets = new short[sparseOffsets.length];\r\n for (int i = 0; i < sparseOffsets.length; ++i) {\r\n copy.sparseOffsets[i] = sparseOffsets[i];\r\n }\r\n copy.opMode = Mode.POLAR_SPARSE;\r\n break;\r\n case POLAR_DENSE:\r\n for (int i = 0; i < dimension; ++i) {\r\n copy.phaseAngles[i] = phaseAngles[i];\r\n }\r\n break;\r\n case CARTESIAN:\r\n for (int i = 0; i < 2 * dimension; ++i) {\r\n copy.coordinates[i] = coordinates[i];\r\n }\r\n break;\r\n case HERMITIAN:\r\n for (int i = 0; i < 2 * dimension; ++i) {\r\n copy.coordinates[i] = coordinates[i];\r\n }\r\n break;\r\n }\r\n return copy;\r\n }\r\n\r\n public String toString() {\r\n StringBuilder debugString = new StringBuilder(\"ComplexVector.\");\r\n switch (opMode) {\r\n case POLAR_SPARSE:\r\n debugString.append(\" Sparse polar. Offsets are:\\n\");\r\n for (short sparseOffset : sparseOffsets) debugString.append((int) sparseOffset).append(\" \");\r\n debugString.append(\"\\n\");\r\n break;\r\n case POLAR_DENSE:\r\n debugString.append(\" Dense polar. Coordinates are:\\n\");\r\n for (int coordinate : phaseAngles) debugString.append(coordinate).append(\" \");\r\n debugString.append(\"\\n\");\r\n break;\r\n case CARTESIAN:\r\n debugString.append(\" Cartesian. Coordinates are:\\n\");\r\n for (float coordinate : coordinates) debugString.append(coordinate).append(\" \");\r\n debugString.append(\"\\n\");\r\n break;\r\n case HERMITIAN:\r\n debugString.append(\" Hermitian. Coordinates are:\\n\");\r\n for (float coordinate : coordinates) debugString.append(coordinate).append(\" \");\r\n debugString.append(\"\\n\");\r\n break;\r\n }\r\n return debugString.toString();\r\n }\r\n\r\n @Override\r\n public boolean isZeroVector() {\r\n switch (opMode) {\r\n case POLAR_SPARSE:\r\n return sparseOffsets == null || sparseOffsets.length == 0;\r\n case POLAR_DENSE:\r\n return phaseAngles == null;\r\n case CARTESIAN:\r\n if (coordinates == null) return true;\r\n for (float coordinate : coordinates) {\r\n if (coordinate != 0) return false; // If this is ever buggy look for rounding errors.\r\n }\r\n return true;\r\n case HERMITIAN:\r\n if (coordinates == null) return true;\r\n for (float coordinate : coordinates) {\r\n if (coordinate != 0) return false; // If this is ever buggy look for rounding errors.\r\n }\r\n return true;\r\n }\r\n throw new IllegalArgumentException(\"Unrecognized mode: \" + opMode);\r\n }\r\n\r\n /**\r\n * Generates a basic sparse vector in Polar form with the format\r\n * { offset, phaseAngle, offset, phaseAngle, ... }\r\n * Consequently the length of the offsets array is 2 X {@code numEntries}.\r\n *\r\n * @return Sparse representation of vector in Polar form.\r\n */\r\n\r\n public ComplexVector generateRandomVector(int dimension, int numEntries, Random random) {\r\n\r\n //return dense form instead, if entries = dimension\r\n if (dimension == numEntries)\r\n return generateRandomVector(dimension, random);\r\n\r\n ComplexVector randomVector = new ComplexVector(dimension, Mode.POLAR_SPARSE);\r\n boolean[] occupiedPositions = new boolean[dimension];\r\n randomVector.sparseOffsets = new short[numEntries * 2];\r\n\r\n int testPlace, entryCount = 0, offsetIdx;\r\n short randomPhaseAngle;\r\n\r\n while (entryCount < numEntries) {\r\n testPlace = random.nextInt(dimension);\r\n randomPhaseAngle = (short) random.nextInt(CircleLookupTable.PHASE_RESOLUTION);\r\n if (!occupiedPositions[testPlace]) {\r\n offsetIdx = entryCount << 1;\r\n occupiedPositions[testPlace] = true;\r\n randomVector.sparseOffsets[offsetIdx] = (short) testPlace;\r\n randomVector.sparseOffsets[offsetIdx + 1] = randomPhaseAngle;\r\n entryCount++;\r\n }\r\n }\r\n return randomVector;\r\n }\r\n\r\n /**\r\n * Generates a basic dense vector in Polar form\r\n *\r\n * @return Dense representation of vector in Polar form.\r\n */\r\n\r\n public ComplexVector generateRandomVector(int dimension, Random random) {\r\n \r\n\tif (getDominantMode().equals(Mode.HERMITIAN))\r\n\t\treturn generateHermitianRandomVector(dimension, random);\r\n\t\r\n\t\r\n\tComplexVector randomVector = new ComplexVector(dimension, Mode.POLAR_DENSE);\r\n\r\n for (int d = 0; d < randomVector.phaseAngles.length; d++)\r\n randomVector.phaseAngles[d] = (short) random.nextInt(CircleLookupTable.PHASE_RESOLUTION);\r\n\r\n return randomVector;\r\n }\r\n\r\n /**\r\n * Generates a basic dense vector in Cartesian form. This is used in the hermitian mode, though,\r\n * hence the name.\r\n *\r\n * @return Dense representation of vector in Cartesian form.\r\n */\r\n public ComplexVector generateHermitianRandomVector(int dimension, Random random) {\r\n \tComplexVector randomVector = new ComplexVector(dimension, Mode.HERMITIAN);\r\n\t float[] coordinates = randomVector.getCoordinates();\r\n for (int d = 0; d < coordinates.length; d++) {\r\n coordinates[d] = (float) (random.nextFloat() - 0.5) / (float) coordinates.length;\r\n }\r\n return randomVector;\r\n }\r\n \r\n @Override\r\n /**\r\n * Implementation of measureOverlap that switches depending on {@code DOMINANT_MODE}.\r\n *\r\n * Transforms both vectors into {@code DOMINANT_MODE}.\r\n */\r\n public double measureOverlap(Vector other) {\r\n IncompatibleVectorsException.checkVectorsCompatible(this, other);\r\n if (isZeroVector()) return 0;\r\n ComplexVector complexOther = (ComplexVector) other;\r\n if (complexOther.isZeroVector()) return 0;\r\n switch (DOMINANT_MODE) {\r\n case HERMITIAN:\r\n return measureHermitianOverlap(complexOther);\r\n case CARTESIAN:\r\n return measureCartesianAngularOverlap(complexOther);\r\n case POLAR_DENSE:\r\n return measurePolarDenseOverlap(complexOther);\r\n case POLAR_SPARSE:\r\n throw new IllegalArgumentException(\"POLAR_SPARSE is not allowed as DOMINANT_MODE.\");\r\n default:\r\n return 0;\r\n }\r\n }\r\n\r\n /**\r\n * Measure overlap, again using the Hermitian / Euclidean scalar product.\r\n */\r\n protected double measureHermitianOverlap(ComplexVector other) {\r\n other.toCartesian();\r\n double result = 0;\r\n double norm1 = 0;\r\n double norm2 = 0;\r\n for (int i = 0; i < dimension * 2; ++i) {\r\n result += coordinates[i] * other.coordinates[i];\r\n norm1 += coordinates[i] * coordinates[i];\r\n norm2 += other.coordinates[i] * other.coordinates[i];\r\n }\r\n return result / Math.sqrt(norm1 * norm2);\r\n }\r\n\r\n /**\r\n * Measure overlap, again using the sum of cosines of phase angle difference.\r\n *\r\n * Note that this is different from the Hermitian scalar product.\r\n */\r\n protected double measureCartesianAngularOverlap(ComplexVector other) {\r\n toCartesian();\r\n other.toCartesian();\r\n double cumulativeCosine = 0;\r\n int nonZeroDimensionPairs = 0;\r\n for (int i = 0; i < dimension * 2; i += 2) {\r\n double resultThisPair = coordinates[i] * other.coordinates[i];\r\n resultThisPair += coordinates[i + 1] * other.coordinates[i + 1];\r\n\r\n double norm1 = coordinates[i] * coordinates[i];\r\n norm1 += coordinates[i + 1] * coordinates[i + 1];\r\n\r\n double norm2 = other.coordinates[i] * other.coordinates[i];\r\n norm2 += other.coordinates[i + 1] * other.coordinates[i + 1];\r\n\r\n norm1 = Math.sqrt(norm1);\r\n norm2 = Math.sqrt(norm2);\r\n\r\n if (norm1 > 0 && norm2 > 0) {\r\n cumulativeCosine += resultThisPair / (norm1 * norm2);\r\n ++nonZeroDimensionPairs;\r\n }\r\n }\r\n return (nonZeroDimensionPairs != 0) ? (cumulativeCosine / nonZeroDimensionPairs) : 0;\r\n }\r\n\r\n /**\r\n * Measures overlap of two vectors using mean cosine of difference\r\n * of phase angles.\r\n *\r\n * If either coordinate is empty (see {@link CircleLookupTable#ZERO_INDEX})\r\n * then nothing is added to the score. If both coordinates are empty, the\r\n * number of counted dimensions is unchanged (this is so that sparse vectors\r\n * are self-similar).\r\n *\r\n * Transforms this and other vector to POLAR_DENSE representations.\r\n */\r\n protected double measurePolarDenseOverlap(ComplexVector other) {\r\n toDensePolar();\r\n other.toDensePolar();\r\n int nonZeroEntries = 0;\r\n short[] phaseAnglesOther = other.getPhaseAngles();\r\n float sum = 0.0f;\r\n for (short i = 0; i < dimension; i++) {\r\n if (phaseAngles[i] != CircleLookupTable.ZERO_INDEX) {\r\n ++nonZeroEntries;\r\n if (phaseAnglesOther[i] != CircleLookupTable.ZERO_INDEX) {\r\n sum += CircleLookupTable.getRealEntry((short) Math.abs(phaseAngles[i] - phaseAnglesOther[i]));\r\n }\r\n }\r\n }\r\n return sum / nonZeroEntries;\r\n }\r\n\r\n @Override\r\n /**\r\n * Normalizes vector based on {@code DOMINANT_MODE}.\r\n */\r\n public void normalize() {\r\n if (isZeroVector()) return;\r\n switch (DOMINANT_MODE) {\r\n case HERMITIAN:\r\n normalizeHermitian();\r\n return;\r\n case CARTESIAN:\r\n normalizeCartesian();\r\n return;\r\n case POLAR_DENSE:\r\n toDensePolar();\r\n return;\r\n case POLAR_SPARSE:\r\n throw new IllegalArgumentException(\"POLAR_SPARSE is not allowed as DOMINANT_MODE.\");\r\n default:\r\n return;\r\n }\r\n }\r\n\r\n /**\r\n * Normalizes the cartesian form of the vector so that the vector formed by each real/imaginary pair has unit length\r\n */\r\n public void normalizeCartesian() {\r\n toDensePolar();\r\n toCartesian();\r\n }\r\n\r\n /**\r\n * Normalizes the cartesian form of the vector so that the vector formed by each real/imaginary pair has unit length\r\n */\r\n protected void normalizeHermitian() {\r\n float[] coords = this.getCoordinates();\r\n float norm = 0;\r\n\r\n for (int x = 0; x < coords.length; x++)\r\n norm += Math.pow(coords[x], 2);\r\n\r\n norm = (float) Math.sqrt(norm);\r\n\r\n for (int x = 0; x < coords.length; x++)\r\n coords[x] = coords[x] / norm;\r\n }\r\n\r\n @Override\r\n /**\r\n * Superposes other vector with this one, putting this vector into cartesian mode.\r\n */\r\n public void superpose(Vector other, double weight, int[] permutation) {\r\n IncompatibleVectorsException.checkVectorsCompatible(this, other);\r\n ComplexVector complexOther = (ComplexVector) other;\r\n if (opMode != Mode.CARTESIAN) {\r\n toCartesian();\r\n }\r\n\r\n switch (complexOther.opMode) {\r\n case HERMITIAN:\r\n case CARTESIAN:\r\n ComplexVectorUtils.superposeWithCoord(this, complexOther, (float) weight, permutation);\r\n break;\r\n case POLAR_SPARSE:\r\n ComplexVectorUtils.superposeWithSparseAngle(this, complexOther, (float) weight, permutation);\r\n break;\r\n case POLAR_DENSE:\r\n ComplexVectorUtils.superposeWithAngle(this, complexOther, (float) weight, permutation);\r\n break;\r\n }\r\n }\r\n\r\n /**\r\n * Transform from any mode to cartesian coordinates.\r\n */\r\n public void toCartesian() {\r\n switch (opMode) {\r\n case HERMITIAN:\r\n \treturn;\r\n case CARTESIAN:\r\n return; // Nothing to do.\r\n case POLAR_SPARSE:\r\n sparsePolarToCartesian();\r\n return;\r\n case POLAR_DENSE:\r\n densePolarToCartesian();\r\n }\r\n }\r\n\r\n private void sparsePolarToCartesian() {\r\n assert (opMode == Mode.POLAR_SPARSE);\r\n sparsePolarToDensePolar();\r\n densePolarToCartesian();\r\n }\r\n\r\n private void densePolarToCartesian() {\r\n assert (opMode == Mode.POLAR_DENSE);\r\n coordinates = new float[dimension * 2];\r\n for (int i = 0; i < dimension; i++) {\r\n coordinates[2 * i] = CircleLookupTable.getRealEntry(phaseAngles[i]);\r\n coordinates[2 * i + 1] = CircleLookupTable.getImagEntry(phaseAngles[i]);\r\n }\r\n opMode = Mode.CARTESIAN;\r\n phaseAngles = null;\r\n }\r\n\r\n /**\r\n * Transform from any mode to cartesian coordinates.\r\n */\r\n public void toDensePolar() {\r\n switch (opMode) {\r\n case POLAR_DENSE:\r\n return; // Nothing to do.\r\n case POLAR_SPARSE:\r\n sparsePolarToDensePolar();\r\n return;\r\n case CARTESIAN:\r\n cartesianToDensePolar();\r\n return; \r\n case HERMITIAN:\r\n \t cartesianToDensePolar();\r\n \t return;\r\n }\r\n }\r\n\r\n private void cartesianToDensePolar() {\r\n assert (opMode == Mode.CARTESIAN || opMode == Mode.HERMITIAN);\r\n opMode = Mode.POLAR_DENSE;\r\n phaseAngles = new short[dimension];\r\n for (int i = 0; i < dimension; i++) {\r\n phaseAngles[i] = CircleLookupTable.phaseAngleFromCartesianTrig(\r\n coordinates[2 * i], coordinates[2 * i + 1]);\r\n }\r\n coordinates = null; // Reclaim memory.\r\n }\r\n\r\n private void sparsePolarToDensePolar() {\r\n assert (opMode == Mode.POLAR_SPARSE);\r\n phaseAngles = new short[dimension];\r\n // Initialize to complex zero vector.\r\n for (int i = 0; i < dimension; ++i) phaseAngles[i] = CircleLookupTable.ZERO_INDEX;\r\n if (sparseOffsets == null) return;\r\n for (int i = 0; i < sparseOffsets.length; i += 2) {\r\n int positionToAdd = sparseOffsets[i];\r\n int phaseAngleIdx = i + 1;\r\n phaseAngles[positionToAdd] = sparseOffsets[phaseAngleIdx];\r\n }\r\n opMode = Mode.POLAR_DENSE;\r\n sparseOffsets = null; // Reclaim memory.\r\n }\r\n\r\n @Override\r\n /**\r\n * Implements binding using the {@link #convolve} method.\r\n */\r\n public void bind(Vector other) {\r\n IncompatibleVectorsException.checkVectorsCompatible(this, other);\r\n ComplexVector complexOther = (ComplexVector) other;\r\n this.convolve(complexOther, 1);\r\n }\r\n\r\n @Override\r\n /**\r\n * Implements release using the {@link #convolve} method.\r\n */\r\n public void release(Vector other) {\r\n IncompatibleVectorsException.checkVectorsCompatible(this, other);\r\n ComplexVector complexOther = (ComplexVector) other;\r\n this.convolve(complexOther, -1);\r\n }\r\n\r\n /**\r\n * Convolves this vector with the other. If the value of direction <= 0\r\n * then the correlation operation is performed, ie. convolution inverse\r\n */\r\n public void convolve(ComplexVector other, int direction) {\r\n IncompatibleVectorsException.checkVectorsCompatible(this, other);\r\n\r\n // to preserve coefficients for hermitian implementation, inclode the commented code below\r\n if (this.getOpMode().equals(Mode.HERMITIAN) && other.getOpMode().equals(Mode.HERMITIAN))\r\n convolveCartesian(other, direction);\r\n else {\r\n toDensePolar();\r\n ComplexVector otherCopy = other.copy();\r\n otherCopy.toDensePolar();\r\n short[] otherAngles = otherCopy.getPhaseAngles();\r\n\r\n for (int i = 0; i < dimension; i++) {\r\n if (otherAngles[i] == CircleLookupTable.ZERO_INDEX) {\r\n continue;\r\n }\r\n if (phaseAngles[i] == CircleLookupTable.ZERO_INDEX) {\r\n phaseAngles[i] = otherAngles[i];\r\n continue;\r\n }\r\n short angleToAdd = otherAngles[i];\r\n if (direction <= 0) {\r\n angleToAdd = (short) (CircleLookupTable.PHASE_RESOLUTION - angleToAdd);\r\n }\r\n phaseAngles[i] = (short) ((phaseAngles[i] + angleToAdd) % CircleLookupTable.PHASE_RESOLUTION);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Convolves this vector with the other. If the value of direction <= 0\r\n * then the correlation operation is performed, ie. convolution inverse\r\n */\r\n public void convolveCartesian(ComplexVector other, int direction) {\r\n IncompatibleVectorsException.checkVectorsCompatible(this, other);\r\n\r\n\r\n //same operation, but preserve length of circular components\r\n //get lengths of circular components\r\n float[] norms = new float[dimension];\r\n float[] otherNorms = new float[dimension];\r\n for (int q = 0; q < dimension; q++) {\r\n float norm = 0;\r\n float othernorm = 0;\r\n\r\n norm += Math.pow(this.coordinates[q * 2], 2);\r\n norm += Math.pow(this.coordinates[2 * q + 1], 2);\r\n othernorm += Math.pow(other.coordinates[q * 2], 2);\r\n othernorm += Math.pow(other.coordinates[2 * q + 1], 2);\r\n\r\n norm = (float) Math.sqrt(norm);\r\n othernorm = (float) Math.sqrt(othernorm);\r\n norms[q] = norm;\r\n otherNorms[q] = othernorm;\r\n }\r\n toDensePolar();\r\n \r\n ComplexVector otherCopy = other.copy();\r\n otherCopy.toDensePolar();\r\n short[] otherAngles = otherCopy.getPhaseAngles();\r\n\r\n for (int i = 0; i < dimension; i++) {\r\n if (otherAngles[i] == CircleLookupTable.ZERO_INDEX) {\r\n continue;\r\n }\r\n if (phaseAngles[i] == CircleLookupTable.ZERO_INDEX) {\r\n phaseAngles[i] = otherAngles[i];\r\n continue;\r\n }\r\n short angleToAdd = otherAngles[i];\r\n if (direction <= 0) {\r\n angleToAdd = (short) (CircleLookupTable.PHASE_RESOLUTION - angleToAdd);\r\n }\r\n phaseAngles[i] = (short) ((phaseAngles[i] + angleToAdd) % CircleLookupTable.PHASE_RESOLUTION);\r\n }\r\n\r\n toCartesian();\r\n opMode = Mode.HERMITIAN;\r\n double newNorm = 0;\r\n for (int q = 0; q < dimension; q++) {\r\n this.coordinates[q * 2] *= (norms[q] * otherNorms[q]);\r\n this.coordinates[q * 2 + 1] *= (norms[q] * otherNorms[q]);\r\n }\r\n normalizeHermitian();\r\n\r\n \r\n\r\n }\r\n\r\n\r\n /**\r\n * Transforms this vector into its complement.\r\n * Assumes vector is in dense polar form.\r\n */\r\n public void complement() {\r\n assert (opMode == Mode.POLAR_DENSE);\r\n char t = (char) (CircleLookupTable.PHASE_RESOLUTION / 2);\r\n for (int i = 0; i < dimension; i++) phaseAngles[i] += t;\r\n }\r\n\r\n @Override\r\n /**\r\n * Transforms vector to cartesian form and writes vector out in dense format.\r\n */\r\n public void writeToLuceneStream(IndexOutput outputStream) {\r\n toCartesian();\r\n for (int i = 0; i < dimension * 2; ++i) {\r\n try {\r\n outputStream.writeInt(Float.floatToIntBits(coordinates[i]));\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Transforms vector to cartesian form and writes vector out in dense format, truncating the\r\n * vectors to the assigned dimensionality\r\n */\r\n public void writeToLuceneStream(IndexOutput outputStream, int k) {\r\n toCartesian();\r\n for (int i = 0; i < k * 2; ++i) {\r\n try {\r\n outputStream.writeInt(Float.floatToIntBits(coordinates[i]));\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n \r\n \r\n /* DORMANT CODE!\r\n assert(opMode != MODE.POLAR_SPARSE);\r\n if (opMode == MODE.CARTESIAN) {\r\n cartesianToDensePolar();\r\n }\r\n for (int i = 0; i < dimension; ++i) {\r\n try {\r\n outputStream.writeInt((int)(phaseAngles[i]));\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n */\r\n }\r\n\r\n @Override\r\n /**\r\n * Reads a vector in Cartesian form from a Lucene input stream.\r\n */\r\n public void readFromLuceneStream(IndexInput inputStream) {\r\n opMode = Mode.CARTESIAN;\r\n coordinates = new float[dimension * 2];\r\n for (int i = 0; i < dimension * 2; ++i) {\r\n try {\r\n coordinates[i] = Float.intBitsToFloat(inputStream.readInt());\r\n } catch (IOException e) {\r\n logger.severe(\"Failed to parse vector from Lucene stream. This signifies a \"\r\n + \"programming or runtime error, e.g., a dimension mismatch.\");\r\n e.printStackTrace();\r\n }\r\n }\r\n\r\n /* DORMANT CODE!\r\n phaseAngles = new short[dimension];\r\n coordinates = null;\r\n for (int i = 0; i < dimension; ++i) {\r\n try {\r\n phaseAngles[i] = (short) inputStream.readInt();\r\n } catch (IOException e) {\r\n logger.severe(\"Failed to parse vector from Lucene stream. This signifies a \"\r\n + \"programming or runtime error, e.g., a dimension mismatch.\");\r\n e.printStackTrace();\r\n }\r\n }\r\n */\r\n }\r\n\r\n @Override\r\n /**\r\n * Writes vector as cartesian form to a string of the form x1|x2|x3| ... where the x's are the\r\n * (real) coordinates.\r\n *\r\n * No terminating newline or | symbol.\r\n */\r\n public String writeToString() {\r\n // TODO(widdows): Discuss whether cartesian should be the main serialization representation.\r\n // The toCartesian call renders the switching below redundant, so we should pick one.\r\n toCartesian();\r\n StringBuilder builder = new StringBuilder();\r\n for (int i = 0; i < coordinates.length; ++i) {\r\n builder.append(Float.toString(coordinates[i]));\r\n if (i != coordinates.length - 1) {\r\n builder.append(\"|\");\r\n }\r\n }\r\n\r\n /* DORMANT CODE!\r\n switch(opMode) {\r\n case CARTESIAN :\r\n for (int i = 0; i < coordinates.length; ++i) {\r\n builder.append(Float.toString(coordinates[i]));\r\n if (i != coordinates.length - 1) {\r\n builder.append(\"|\");\r\n }\r\n }\r\n break;\r\n case POLAR_SPARSE:\r\n for (int i = 0; i < sparseOffsets.length; ++i) {\r\n builder.append((int) sparseOffsets[i]);\r\n if (i != sparseOffsets.length - 1) {\r\n builder.append(\"|\");\r\n }\r\n }\r\n break;\r\n case POLAR_DENSE:\r\n for (int i = 0; i < phaseAngles.length; ++i) {\r\n builder.append((int) phaseAngles[i]);\r\n if (i != phaseAngles.length - 1) {\r\n builder.append(\"|\");\r\n }\r\n }\r\n }\r\n */\r\n return builder.toString();\r\n }\r\n\r\n @Override\r\n /**\r\n * Reads vector from a string of the form x1|x2|x3| ... where the x's are the coordinates.\r\n * No terminating newline or | symbol.\r\n *\r\n * Reads cartesian vector as floats.\r\n * Reads polar vector as 16 bit integers.\r\n */\r\n public void readFromString(String input) {\r\n toCartesian(); // Big assumption, renders some code below dormant.\r\n String[] entries = input.split(\"\\\\|\");\r\n\r\n switch (opMode) {\r\n case CARTESIAN:\r\n if (entries.length != dimension * 2) {\r\n throw new IllegalArgumentException(\"Found \" + (entries.length) + \" possible coordinates: \"\r\n + \"expected \" + dimension * 2);\r\n }\r\n if (coordinates.length == 0) coordinates = new float[dimension];\r\n for (int i = 0; i < coordinates.length; ++i) {\r\n coordinates[i] = Float.parseFloat(entries[i]);\r\n }\r\n break;\r\n case POLAR_DENSE:\r\n if (entries.length != dimension) {\r\n throw new IllegalArgumentException(\"Found \" + (entries.length) + \" possible coordinates: \"\r\n + \"expected \" + dimension);\r\n }\r\n if (phaseAngles == null || phaseAngles.length == 0) phaseAngles = new short[dimension];\r\n for (int i = 0; i < phaseAngles.length; ++i) {\r\n phaseAngles[i] = (short) Integer.parseInt(entries[i]);\r\n }\r\n break;\r\n case POLAR_SPARSE:\r\n logger.info(\"Reading sparse complex vector from string is not supported.\");\r\n break;\r\n }\r\n }\r\n\r\n //Available for testing and copying.\r\n protected ComplexVector(float[] coordinates) {\r\n this.dimension = coordinates.length / 2;\r\n this.coordinates = coordinates;\r\n this.opMode = Mode.CARTESIAN;\r\n }\r\n\r\n //Available for testing and copying.\r\n protected ComplexVector(short[] phaseAngles) {\r\n this.dimension = phaseAngles.length;\r\n this.phaseAngles = phaseAngles;\r\n this.opMode = Mode.POLAR_DENSE;\r\n }\r\n\r\n public float[] getCoordinates() {\r\n\treturn coordinates;\r\n }\r\n\r\n public void setCoordinates(float[] coordinates) {\r\n this.coordinates = coordinates;\r\n }\r\n\r\n public short[] getPhaseAngles() {\r\n return phaseAngles;\r\n }\r\n\r\n protected void setPhaseAngles(short[] phaseAngles) {\r\n this.phaseAngles = phaseAngles;\r\n }\r\n\r\n protected short[] getSparseOffsets() {\r\n return sparseOffsets;\r\n }\r\n\r\n protected void setSparseOffsets(short[] sparseOffsets) {\r\n this.sparseOffsets = sparseOffsets;\r\n }\r\n\r\n @Override\r\n public int getDimension() {\r\n return dimension;\r\n }\r\n\r\n protected Mode getOpMode() {\r\n return opMode;\r\n }\r\n\r\n protected void setOpMode(Mode opMode) {\r\n this.opMode = opMode;\r\n }\r\n}\r", "public static enum Mode {\r\n /** Uses a nonnegative 16 bit short for each phase angle. The value -1 is reserved for\r\n * representing the complex number zero, i.e., there is no entry in this dimension. */\r\n POLAR_DENSE,\r\n /** Uses a pair of 16 bit shorts for each (offset, phase angle) pair. */\r\n POLAR_SPARSE,\r\n /** Uses a pair of 32 bit floats for each (real, imaginary) complex coordinate. */\r\n CARTESIAN,\r\n /** As above, but with normalization to unit length and the hermitian scalar product\r\n * instead of the alternatives proposed by Plate */\r\n HERMITIAN\r\n}\r", "public class VectorFactory {\n private static final BinaryVector binaryInstance = new BinaryVector(0);\n private static final RealVector realInstance = new RealVector(0);\n private static final ComplexVector complexInstance =\n new ComplexVector(0, ComplexVector.Mode.POLAR_SPARSE);\n private static final ComplexVector complexFlatInstance =\n new ComplexVector(0, ComplexVector.Mode.CARTESIAN);\n\n /**\n * createZeroVector returns a vector set to zero. It can be used externally, but\n * be careful particularly with Complex Vectors to make sure that polar / cartesian / hermitian\n * modes are set correctly especially if you try to set coordinates manually after that.\n */\n public static Vector createZeroVector(VectorType type, int dimension) {\n switch (type) {\n case BINARY:\n return new BinaryVector(dimension);\n case REAL:\n return new RealVector(dimension);\n case COMPLEX:\n return new ComplexVector(dimension, Mode.POLAR_SPARSE);\n case COMPLEXFLAT:\n return new ComplexVector(dimension, Mode.POLAR_SPARSE);\n case PERMUTATION:\n \treturn new PermutationVector(dimension);\n default:\n throw new IllegalArgumentException(\"Unrecognized VectorType: \" + type);\n }\n }\n \n /**\n * Generates an appropriate random vector.\n * \n * @param type one of the recognized vector types\n * @param dimension number of dimensions in the generated vector\n * @param numEntries total number of non-zero entries; must be no greater than half of dimension\n * @param random random number generator; passed in to enable deterministic testing\n * @return vector generated with appropriate type, dimension and number of nonzero entries\n */\n public static Vector generateRandomVector(\n VectorType type, int dimension, int numEntries, Random random) {\n\t \n\t if (2 * numEntries > dimension && !type.equals(VectorType.COMPLEX) && !(numEntries == dimension)) {\n throw new RuntimeException(\"Requested \" + numEntries + \" to be filled in sparse \"\n + \"vector of dimension \" + dimension + \". This is not sparse and may cause problems.\");\n }\n switch (type) {\n case BINARY:\n return binaryInstance.generateRandomVector(dimension, numEntries, random);\n case REAL:\n return realInstance.generateRandomVector(dimension, numEntries, random);\n case COMPLEX:\n if (!ComplexVector.getDominantMode().equals(Mode.HERMITIAN)) \n \t ComplexVector.setDominantMode(Mode.POLAR_DENSE);\n return complexInstance.generateRandomVector(dimension, numEntries, random);\n case COMPLEXFLAT:\n ComplexVector.setDominantMode(Mode.CARTESIAN);\n return complexInstance.generateRandomVector(dimension, numEntries, random);\n default:\n throw new IllegalArgumentException(\"Unrecognized VectorType: \" + type);\n }\n }\n\n /**\n * Returns the size in bytes expected to be taken up by the serialization\n * of this vector in Lucene format.\n */\n public static int getLuceneByteSize(VectorType vectorType, int dimension) {\n switch (vectorType) {\n case BINARY:\n return 8 * ((dimension / 64) );\n case REAL:\n return 4 * dimension;\n case COMPLEX:\n case COMPLEXFLAT:\n return 8 * dimension;\n default:\n throw new IllegalArgumentException(\"Unrecognized VectorType: \" + vectorType);\n }\n }\n}", "public enum VectorType {\n /**\n * Uses binary-valued vectors. May be slower for some operations, but highly accurate.\n */\n BINARY,\n /**\n * \"Standard\" real-valued vectors. Performs well for many operations though bind and release\n * are (in some cases) either lossy with respect to argument structure and binding, or\n * inexact with respect to inverse.\n */\n REAL,\n /**\n * Complex-valued vectors, default \"polar\" version, normalized to coordinates on the unit circle,\n * and compared using angular differences.\n */\n COMPLEX,\n /**\n * Complex-valued vectors, normalized and compared using a hermitian scalar product.\n */\n COMPLEXFLAT,\n /**\n * Vector of integer values, describing a permutation\n */\n PERMUTATION\n}", "public class VectorUtils {\n @SuppressWarnings(\"unused\")\n private static final Logger logger = Logger.getLogger(VectorUtils.class.getCanonicalName());\n\n /**\n * Get nearest vector from list of candidates.\n * @param vector The vector whose nearest neighbor is to be found.\n * @param candidates The list of vectors from whoe the nearest is to be chosen.\n * @return Integer value referencing the position in the candidate list of the nearest vector.\n */\n public static int getNearestVector(Vector vector, Vector[] candidates) {\n int nearest = 0;\n double maxSim = vector.measureOverlap(candidates[0]);\n for (int i = 1; i < candidates.length; ++i) {\n double thisDist = vector.measureOverlap(candidates[i]);\n if (thisDist > maxSim) {\n maxSim = thisDist;\n nearest = i;\n }\n }\n return nearest;\n }\n\n /**\n * Returns the sum overlap of the testVector with the subspace generated by the vectors,\n * which are presumed to be orthogonal.\n * See also {@link BinaryVectorUtils#compareWithProjection} for the binary case.\n */\n public static double compareWithProjection(Vector testVector, ArrayList<Vector> vectors) {\n\n float score = 0;\n for (int i = 0; i < vectors.size(); ++i) {\n score += Math.pow(testVector.measureOverlap(vectors.get(i)), 2);\n }\n return (float) Math.sqrt(score);\n\n }\n\n /**\n * The orthogonalize function takes an array of vectors and\n * orthogonalizes them using the Gram-Schmidt process. The vectors\n * are orthogonalized in place, so there is no return value. Note\n * that the output of this function is order dependent, in\n * particular, the jth vector in the array will be made orthogonal\n * to all the previous vectors. Since this means that the last\n * vector is orthogonal to all the others, this can be used as a\n * negation function to give an vector for\n * vectors[last] NOT (vectors[0] OR ... OR vectors[last - 1].\n *\n * @param list vectors to be orthogonalized in place.\n */\n public static void orthogonalizeVectors(List<Vector> list) {\n switch (list.get(0).getVectorType()) {\n case REAL:\n RealVectorUtils.orthogonalizeVectors(list);\n break;\n case COMPLEX:\n ComplexVectorUtils.orthogonalizeVectors(list);\n break;\n case BINARY:\n BinaryVectorUtils.orthogonalizeVectors(list);\n break;\n default:\n throw new IncompatibleVectorsException(\"Type not recognized: \" + list.get(0).getVectorType());\n }\n }\n\n /**\n * Returns a superposition of the form leftWeight*left + rightWeight*right.\n */\n public static Vector weightedSuperposition(\n Vector left, double leftWeight, Vector right, double rightWeight) {\n if ((left.getVectorType() != right.getVectorType())\n || (left.getDimension() != right.getDimension())) {\n throw new IncompatibleVectorsException(\n String.format(\"Incompatible vectors:\\n%s\\n%s\", left.toString(), right.toString()));\n }\n switch (left.getVectorType()) {\n case REAL:\n case COMPLEX:\n Vector superposition = VectorFactory.createZeroVector(\n left.getVectorType(), left.getDimension());\n superposition.superpose(left, leftWeight, null);\n superposition.superpose(right, rightWeight, null);\n superposition.normalize();\n return superposition;\n case BINARY:\n return BinaryVectorUtils.weightedSuperposition(\n (BinaryVector) left, leftWeight, (BinaryVector) right, rightWeight);\n default:\n throw new IncompatibleVectorsException(\"Type not recognized: \" + left.getVectorType());\n }\n }\n\n /**\n * Generates a basic sparse vector\n * with mainly zeros and some 1 and -1 entries (seedLength/2 of each)\n * each vector is an array of length seedLength containing 1+ the index of a non-zero\n * value, signed according to whether this is a + or -1.\n * <br>\n * e.g. +20 would indicate a +1 in position 19, +1 would indicate a +1 in position 0.\n * -20 would indicate a -1 in position 19, -1 would indicate a -1 in position 0.\n * <br>\n * The extra offset of +1 is because position 0 would be unsigned,\n * and would therefore be wasted. Consequently we've chosen to make\n * the code slightly more complicated to make the implementation\n * slightly more space efficient.\n *\n * @return Sparse representation of basic ternary vector. Array of\n * short signed integers, indices to the array locations where a\n * +/-1 entry is located.\n */\n public static short[] generateRandomVector(int seedLength, int dimension, Random random) {\n boolean[] randVector = new boolean[dimension];\n short[] randIndex = new short[seedLength];\n\n int testPlace, entryCount = 0;\n\n /* put in +1 entries */\n while (entryCount < seedLength / 2) {\n testPlace = random.nextInt(dimension);\n if (!randVector[testPlace]) {\n randVector[testPlace] = true;\n randIndex[entryCount] = new Integer(testPlace + 1).shortValue();\n entryCount++;\n }\n }\n\n /* put in -1 entries */\n while (entryCount < seedLength) {\n testPlace = random.nextInt(dimension);\n if (!randVector[testPlace]) {\n randVector[testPlace] = true;\n randIndex[entryCount] = new Integer((1 + testPlace) * -1).shortValue();\n entryCount++;\n }\n }\n\n return randIndex;\n }\n\n /**\n * Utility method to compute scalar product (hopefully) quickly using BLAS routines\n * Arguably, this should be disseminated across the individual Vector classes\n */\n public static double scalarProduct(Vector v1, Vector v2, FlagConfig flagConfig, BLAS blas) throws IncompatibleVectorsException {\n if (!v1.getVectorType().equals(v2.getVectorType()))\n throw new IncompatibleVectorsException();\n\n switch (v1.getVectorType()) {\n case REAL:\n return blas.sdot(v1.getDimension(), ((RealVector) v1).getCoordinates(), 1, ((RealVector) v2).getCoordinates(), 1);\n case COMPLEX: //hermitian scalar product\n return blas.sdot(v1.getDimension()*2, ((ComplexVector) v1).getCoordinates(), 1, ((ComplexVector) v2).getCoordinates(), 1);\n case BINARY:\n ((BinaryVector) v1).tallyVotes();\n ((BinaryVector) v2).tallyVotes();\n return v1.measureOverlap(v2); \n default:\n return 0;\n\n }\n }\n\n \n /**\n * Utility method to compute scalar product (hopefully) quickly using BLAS routines\n * Arguably, this should be disseminated across the individual Vector classes\n */\n public static double scalarProduct(Vector v1, Vector v2, FlagConfig flagConfig, BLAS blas, int[] permutations) throws IncompatibleVectorsException {\n \n\t if (permutations == null)\n\t\t return scalarProduct(v1, v2, flagConfig, blas);\n\t \n\t if (!v1.getVectorType().equals(v2.getVectorType()) || !v1.getVectorType().equals(VectorType.REAL))\n throw new IncompatibleVectorsException();\n \n\t \tdouble score = 0;\n \n \t for (int q=0; q < v1.getDimension(); q++)\n \t\t score += ((RealVector) v1).getCoordinates()[permutations[q]] * \n \t\t\t\t ((RealVector) v2).getCoordinates()[q];\n \t\t\n return score;\n }\n \n public static void superposeInPlace(Vector toBeAdded, Vector toBeAltered, FlagConfig flagConfig, BLAS blas, double weight, int[] permutation) throws IncompatibleVectorsException {\n\t \n\t if (permutation == null)\n\t\t superposeInPlace(toBeAdded, toBeAltered, flagConfig, blas, weight);\n\t\t else\n\t\t {\n\t\t \n\t if (!toBeAdded.getVectorType().equals(toBeAltered.getVectorType()) || !toBeAdded.getVectorType().equals(VectorType.REAL))\n\t throw new IncompatibleVectorsException();\n\t \n\t \t for (int q=0; q < toBeAdded.getDimension(); q++)\n\t \t \t ((RealVector) toBeAltered).getCoordinates()[permutation[q]]\n\t \t \t\t\t += ((RealVector) toBeAdded).getCoordinates()[q]*weight;\n\t \t\t\n\t }\n }\n \n\n /**\n * Utility method to perform superposition (hopefully) quickly using BLAS routines\n * Arguably, this should be disseminated across the individual Vector classes\n *\n *\n * @param toBeAdded\n * @param toBeAltered\n * @param blas\n * @return\n */\n public static void superposeInPlace(Vector toBeAdded, Vector toBeAltered, FlagConfig flagConfig, BLAS blas, double weight) throws IncompatibleVectorsException {\n if (!toBeAdded.getVectorType().equals(toBeAltered.getVectorType()))\n throw new IncompatibleVectorsException();\n\n switch (toBeAdded.getVectorType()) {\n case REAL:\n blas.saxpy(flagConfig.dimension(), (float) weight, ((RealVector) toBeAdded).getCoordinates(), 1, ((RealVector) toBeAltered).getCoordinates(), 1);\n break;\n case COMPLEX:\n blas.saxpy(flagConfig.dimension()*2, (float) weight, ((ComplexVector) toBeAdded).getCoordinates(), 1, ((ComplexVector) toBeAltered).getCoordinates(), 1);\n break;\n case BINARY: //first attempt at this - add the results of the election multiplied by the number of votes to date\n ((BinaryVector) toBeAdded).tallyVotes();\n toBeAltered.superpose(toBeAdded, weight, null);\n break;\n default:\n break;\n\n }\n\n\n }\n\n\n /**\n * quick check for NaNs in real and complex vectors (returns false for binary vectors)\n * @param toTest\n * @return\n */\n public static boolean containsNaN(Vector toTest)\n {\n\t if (toTest.getVectorType().equals(VectorType.BINARY)) return false;\n\t \n\t float[] coords = new float[0];\n\t \n\t if (toTest.getVectorType().equals(VectorType.REAL)) \n\t\t coords = ((RealVector) toTest).getCoordinates();\n\t else if (toTest.getVectorType().equals(VectorType.COMPLEX)) \n\t\t coords = ((ComplexVector) toTest).getCoordinates();\n\n\t for (float x:coords)\n\t\t if (Float.isNaN(x)) return true;\n\t \n\t return false;\n\t \n }\n \n \n}" ]
import org.apache.lucene.document.Document; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.BytesRef; import org.netlib.blas.BLAS; import pitt.search.semanticvectors.ElementalVectorStore.ElementalGenerationMethod; import pitt.search.semanticvectors.utils.Bobcat; import pitt.search.semanticvectors.utils.SigmoidTable; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.BinaryVector; import pitt.search.semanticvectors.vectors.ComplexVector; import pitt.search.semanticvectors.vectors.ComplexVector.Mode; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; import pitt.search.semanticvectors.vectors.VectorType; import pitt.search.semanticvectors.vectors.VectorUtils; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.FileSystems; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Logger;
int qb = randomStartpoints.poll(); //the index number of the first predication-document to be drawn int qe = qb + (100000); //the index number of the last predication-document to be drawn int qplus = 0; //the number of predication-documents added to the queue for (int qc=qb; qc < qe && qc < luceneUtils.getNumDocs() && dc.get() < luceneUtils.getNumDocs()-1; qc++) { try { Document nextDoc = luceneUtils.getDoc(qc); dc.incrementAndGet(); if (nextDoc != null) { theQ.add(nextDoc); qplus++; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } VerbatimLogger.info("\nAdded "+qplus+" documents to queue, now carrying "+theQ.size()); if (qplus == 0) return -1; else return qplus; } /** * Performs training by iterating over predications. Assumes that elemental vector stores are populated. * * @throws IOException */ private void trainIncrementalESPVectors() throws IOException { // For BINARY vectors, assign higher learning rates on account of the limited floating point precision of the voting record if (flagConfig.vectortype().equals(VectorType.BINARY)) { initial_alpha = 0.25; alpha = 0.25; min_alpha = 0.001; } //loop through the number of assigned epochs for (tc=0; tc <= flagConfig.trainingcycles(); tc++) { initializeRandomizationStartpoints(); theQ = new ConcurrentLinkedQueue<Document>(); dc.set(0); populateQueue(); double time = System.currentTimeMillis(); int numthreads = flagConfig.numthreads(); ExecutorService executor = Executors.newFixedThreadPool(numthreads); for (int q = 0; q < numthreads; q++) { executor.execute(new TrainPredThread(q)); } executor.shutdown(); // Wait until all threads are finish while (!executor.isTerminated()) { if (theQ.size() < 50000) populateQueue(); } int mp = flagConfig.mutablepredicatevectors() ? 1 : 0; double num_updates = pc.get() * (1 + flagConfig.negsamples()) * (4 + 2*mp); double lo = raw_loss.sumThenReset(); double ave_loss = lo / num_updates; VerbatimLogger.info("\nTime for cycle "+tc+" : "+((System.currentTimeMillis() - time) / (1000*60)) +" minutes"); VerbatimLogger.info("\nSummed loss = "+lo); VerbatimLogger.info("\nMean loss = "+ave_loss); VerbatimLogger.info("\nProcessed "+pc.get()+" total predications (total on disk = "+luceneUtils.getNumDocs()+")"); //normalization with each epoch if the vectors are not binary vectors if (!flagConfig.vectortype().equals(VectorType.BINARY)) { Enumeration<ObjectVector> semanticVectorEnumeration = semanticItemVectors.getAllVectors(); Enumeration<ObjectVector> elementalVectorEnumeration = elementalItemVectors.getAllVectors(); while (semanticVectorEnumeration.hasMoreElements()) { semanticVectorEnumeration.nextElement().getVector().normalize(); elementalVectorEnumeration.nextElement().getVector().normalize(); } } } // Finished all epochs Enumeration<ObjectVector> e = null; if (flagConfig.semtypesandcuis()) //write out cui vectors and normalize semantic vectors { // Also write out cui version of semantic vectors File vectorFile = new File("cuivectors.bin"); java.nio.file.Files.deleteIfExists(vectorFile.toPath()); String parentPath = vectorFile.getParent(); if (parentPath == null) parentPath = ""; FSDirectory fsDirectory = FSDirectory.open(FileSystems.getDefault().getPath(parentPath)); IndexOutput outputStream = fsDirectory.createOutput(vectorFile.getName(), IOContext.DEFAULT); outputStream.writeString(VectorStoreWriter.generateHeaderString(flagConfig)); // Tally votes of semantic vectors and write out. e = semanticItemVectors.getAllVectors(); while (e.hasMoreElements()) { ObjectVector ov = e.nextElement(); if (flagConfig.vectortype().equals(VectorType.BINARY))
((BinaryVector) ov.getVector()).tallyVotes();
1
DigiArea/es5-model
com.digiarea.es5/src/com/digiarea/es5/Project.java
[ "public abstract class Node {\r\n\r\n\t/**\r\n\t * The JSDoc comment.\r\n\t */\r\n\tprotected JSDocComment jsDocComment = null;\r\n\r\n\t/**\r\n\t * The position begin.\r\n\t */\r\n\tprotected int posBegin = 0;\r\n\r\n\t/**\r\n\t * The position end.\r\n\t */\r\n\tprotected int posEnd = 0;\r\n\r\n\tpublic JSDocComment getJsDocComment() {\r\n\t\treturn jsDocComment;\r\n\t}\r\n\r\n\tpublic void setJsDocComment(JSDocComment jsDocComment) {\r\n\t\tthis.jsDocComment = jsDocComment;\r\n\t}\r\n\r\n\tpublic int getPosBegin() {\r\n\t\treturn posBegin;\r\n\t}\r\n\r\n\tpublic void setPosBegin(int posBegin) {\r\n\t\tthis.posBegin = posBegin;\r\n\t}\r\n\r\n\tpublic int getPosEnd() {\r\n\t\treturn posEnd;\r\n\t}\r\n\r\n\tpublic void setPosEnd(int posEnd) {\r\n\t\tthis.posEnd = posEnd;\r\n\t}\r\n\r\n\tNode() {\r\n\t\tsuper();\r\n\t}\r\n\r\n\tNode(JSDocComment jsDocComment, int posBegin, int posEnd) {\r\n\t\tsuper();\r\n\t\tthis.jsDocComment = jsDocComment;\r\n\t\tthis.posBegin = posBegin;\r\n\t\tthis.posEnd = posEnd;\r\n\t}\r\n\r\n\tpublic abstract <C> void accept(VoidVisitor<C> v, C ctx) throws Exception;\r\n\r\n\tpublic abstract <R, C> R accept(GenericVisitor<R, C> v, C ctx)\r\n\t\t\tthrows Exception;\r\n\r\n\tprivate static final CloneVisitor<Void> CLONE = new CloneVisitor<Void>();\r\n\r\n\t@Override\r\n\tpublic final Node clone() throws CloneNotSupportedException {\r\n\t\ttry {\r\n\t\t\treturn accept(CLONE, null);\r\n\t\t} catch (final Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic final boolean equals(Object obj) {\r\n\t\ttry {\r\n\t\t\treturn EqualsVisitor.equals(this, (Node) obj);\r\n\t\t} catch (Exception e) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static final String ENCODING = \"UTF-8\";\r\n\r\n\tprivate static final PrinterVisitor PRINTER = new PrinterVisitor();\r\n\r\n\t@Override\r\n\tpublic final String toString() {\r\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\r\n\t\tString result = null;\r\n\t\ttry {\r\n\t\t\taccept(PRINTER, new SourcePrinter(out, ENCODING));\r\n\t\t\tresult = out.toString(ENCODING);\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprivate static final TracePrinter TRACE_PRINTER = new TracePrinter();\r\n\r\n\t@Override\r\n\tpublic final int hashCode() {\r\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\r\n\t\tString result = null;\r\n\t\ttry {\r\n\t\t\taccept(TRACE_PRINTER, new SourcePrinter(out, ENCODING));\r\n\t\t\tresult = out.toString(ENCODING);\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn result.hashCode();\r\n\t}\r\n\r\n\tprivate static final String CRYPTO = \"SHA-256\";\r\n\r\n\tpublic final String trace() {\r\n\t\ttry {\r\n\t\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\r\n\t\t\taccept(TRACE_PRINTER, new SourcePrinter(out, ENCODING));\r\n\t\t\tMessageDigest md = java.security.MessageDigest.getInstance(CRYPTO);\r\n\t\t\tmd.update(out.toByteArray());\r\n\t\t\tbyte byteData[] = md.digest();\r\n\t\t\tStringBuffer sb = new StringBuffer();\r\n\t\t\tfor (int i = 0; i < byteData.length; i++) {\r\n\t\t\t\tsb.append(java.lang.Integer.toString(\r\n\t\t\t\t\t\t(byteData[i] & 0xff) + 0x100, 16).substring(1));\r\n\t\t\t}\r\n\t\t\treturn sb.toString();\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n}\r", "public class CompilationUnit extends Node {\r\n\r\n /** \r\n * The elements.\r\n */\r\n private NodeList<Statement> elements;\r\n\r\n /** \r\n * The comments.\r\n */\r\n private NodeList<Comment> comments;\r\n\r\n /** \r\n * The name.\r\n */\r\n private String name;\r\n\r\n public NodeList<Statement> getElements() {\r\n return elements;\r\n }\r\n\r\n public void setElements(NodeList<Statement> elements) {\r\n this.elements = elements;\r\n }\r\n\r\n public NodeList<Comment> getComments() {\r\n return comments;\r\n }\r\n\r\n public void setComments(NodeList<Comment> comments) {\r\n this.comments = comments;\r\n }\r\n\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n public void setName(String name) {\r\n this.name = name;\r\n }\r\n\r\n CompilationUnit() {\r\n super();\r\n }\r\n\r\n CompilationUnit(NodeList<Statement> elements, NodeList<Comment> comments, String name, JSDocComment jsDocComment, int posBegin, int posEnd) {\r\n super(jsDocComment, posBegin, posEnd);\r\n this.elements = elements;\r\n this.comments = comments;\r\n this.name = name;\r\n }\r\n\r\n @Override\r\n public <C> void accept(VoidVisitor<C> v, C ctx) throws Exception {\r\n v.visit(this, ctx);\r\n }\r\n\r\n @Override\r\n public <R, C> R accept(GenericVisitor<R, C> v, C ctx) throws Exception {\r\n return v.visit(this, ctx);\r\n }\r\n\r\n}\r", "public class NodeList<E extends Node> extends Node implements List<E> {\r\n\r\n /** \r\n * The nodes.\r\n */\r\n private List<E> nodes = null;\r\n\r\n public Iterator<E> iterator() {\r\n if (nodes != null) {\r\n return nodes.iterator();\r\n }\r\n return null;\r\n }\r\n\r\n public int size() {\r\n return nodes.size();\r\n }\r\n\r\n public boolean isEmpty() {\r\n return nodes.isEmpty();\r\n }\r\n\r\n public boolean contains(Object o) {\r\n return nodes.contains(o);\r\n }\r\n\r\n public Object[] toArray() {\r\n return nodes.toArray();\r\n }\r\n\r\n public <T> T[] toArray(T[] a) {\r\n return nodes.toArray(a);\r\n }\r\n\r\n public boolean add(E e) {\r\n return nodes.add(e);\r\n }\r\n\r\n public boolean remove(Object o) {\r\n return nodes.remove(o);\r\n }\r\n\r\n public boolean containsAll(Collection<?> c) {\r\n return nodes.containsAll(c);\r\n }\r\n\r\n public boolean addAll(Collection<? extends E> c) {\r\n return nodes.addAll(c);\r\n }\r\n\r\n public boolean addAll(int index, Collection<? extends E> c) {\r\n return nodes.addAll(index, c);\r\n }\r\n\r\n public boolean removeAll(Collection<?> c) {\r\n return nodes.removeAll(c);\r\n }\r\n\r\n public boolean retainAll(Collection<?> c) {\r\n return nodes.retainAll(c);\r\n }\r\n\r\n public void clear() {\r\n nodes.clear();\r\n }\r\n\r\n public E get(int index) {\r\n return nodes.get(index);\r\n }\r\n\r\n public E set(int index, E element) {\r\n return nodes.set(index, element);\r\n }\r\n\r\n public void add(int index, E element) {\r\n nodes.add(index, element);\r\n }\r\n\r\n public E remove(int index) {\r\n return nodes.remove(index);\r\n }\r\n\r\n public int indexOf(Object o) {\r\n return nodes.indexOf(o);\r\n }\r\n\r\n public int lastIndexOf(Object o) {\r\n return nodes.lastIndexOf(o);\r\n }\r\n\r\n public ListIterator<E> listIterator() {\r\n return nodes.listIterator();\r\n }\r\n\r\n public ListIterator<E> listIterator(int index) {\r\n return nodes.listIterator(index);\r\n }\r\n\r\n public List<E> subList(int fromIndex, int toIndex) {\r\n return nodes.subList(fromIndex, toIndex);\r\n }\r\n\r\n public boolean addNodes(E nodes) {\r\n boolean res = getNodes().add(nodes);\r\n if (res) {\r\n }\r\n return res;\r\n }\r\n\r\n public boolean removeNodes(E nodes) {\r\n boolean res = getNodes().remove(nodes);\r\n if (res) {\r\n }\r\n return res;\r\n }\r\n\r\n public List<E> getNodes() {\r\n return nodes;\r\n }\r\n\r\n public void setNodes(List<E> nodes) {\r\n this.nodes = nodes;\r\n }\r\n\r\n NodeList() {\r\n super();\r\n }\r\n\r\n NodeList(List<E> nodes, JSDocComment jsDocComment, int posBegin, int posEnd) {\r\n super(jsDocComment, posBegin, posEnd);\r\n this.nodes = nodes;\r\n }\r\n\r\n @Override\r\n public <C> void accept(VoidVisitor<C> v, C ctx) throws Exception {\r\n v.visit(this, ctx);\r\n }\r\n\r\n @Override\r\n public <R, C> R accept(GenericVisitor<R, C> v, C ctx) throws Exception {\r\n return v.visit(this, ctx);\r\n }\r\n\r\n}\r", "public final class JSDocComment extends Comment {\r\n\r\n JSDocComment() {\r\n super();\r\n }\r\n\r\n JSDocComment(String content, JSDocComment jsDocComment, int posBegin, int posEnd) {\r\n super(content, jsDocComment, posBegin, posEnd);\r\n }\r\n\r\n @Override\r\n public <C> void accept(VoidVisitor<C> v, C ctx) throws Exception {\r\n v.visit(this, ctx);\r\n }\r\n\r\n @Override\r\n public <R, C> R accept(GenericVisitor<R, C> v, C ctx) throws Exception {\r\n return v.visit(this, ctx);\r\n }\r\n\r\n}\r", "public interface VoidVisitor<C> {\r\n\r\n public void visit(AllocationExpression n, C ctx) throws Exception;\r\n\r\n public void visit(ArrayAccessExpression n, C ctx) throws Exception;\r\n\r\n public void visit(ArrayLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(AssignmentExpression n, C ctx) throws Exception;\r\n\r\n public void visit(AssignOperator n, C ctx) throws Exception;\r\n\r\n public void visit(BinaryExpression n, C ctx) throws Exception;\r\n\r\n public void visit(BinaryOperator n, C ctx) throws Exception;\r\n\r\n public void visit(Block n, C ctx) throws Exception;\r\n\r\n public void visit(BlockComment n, C ctx) throws Exception;\r\n\r\n public void visit(BooleanLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(BreakStatement n, C ctx) throws Exception;\r\n\r\n public void visit(CallExpression n, C ctx) throws Exception;\r\n\r\n public void visit(CaseBlock n, C ctx) throws Exception;\r\n\r\n public void visit(CaseClause n, C ctx) throws Exception;\r\n\r\n public void visit(CatchClause n, C ctx) throws Exception;\r\n\r\n public void visit(CompilationUnit n, C ctx) throws Exception;\r\n\r\n public void visit(ConditionalExpression n, C ctx) throws Exception;\r\n\r\n public void visit(ConstantStatement n, C ctx) throws Exception;\r\n\r\n public void visit(ContinueStatement n, C ctx) throws Exception;\r\n\r\n public void visit(DebuggerStatement n, C ctx) throws Exception;\r\n\r\n public void visit(DecimalLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(DefaultClause n, C ctx) throws Exception;\r\n\r\n public void visit(DoWhileStatement n, C ctx) throws Exception;\r\n\r\n public void visit(EmptyLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(EmptyStatement n, C ctx) throws Exception;\r\n\r\n public void visit(EnclosedExpression n, C ctx) throws Exception;\r\n\r\n public void visit(ExpressionStatement n, C ctx) throws Exception;\r\n\r\n public void visit(FieldAccessExpression n, C ctx) throws Exception;\r\n\r\n public void visit(FloatLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(ForeachStatement n, C ctx) throws Exception;\r\n\r\n public void visit(ForStatement n, C ctx) throws Exception;\r\n\r\n public void visit(FunctionDeclaration n, C ctx) throws Exception;\r\n\r\n public void visit(FunctionExpression n, C ctx) throws Exception;\r\n\r\n public void visit(GetAssignment n, C ctx) throws Exception;\r\n\r\n public void visit(HexIntegerLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(IdentifierName n, C ctx) throws Exception;\r\n\r\n public void visit(IfStatement n, C ctx) throws Exception;\r\n\r\n public void visit(ImportStatement n, C ctx) throws Exception;\r\n\r\n public void visit(JSDocComment n, C ctx) throws Exception;\r\n\r\n public void visit(LabelledStatement n, C ctx) throws Exception;\r\n\r\n public void visit(LetDefinition n, C ctx) throws Exception;\r\n\r\n public void visit(LetExpression n, C ctx) throws Exception;\r\n\r\n public void visit(LetStatement n, C ctx) throws Exception;\r\n\r\n public void visit(LineComment n, C ctx) throws Exception;\r\n\r\n public void visit(NewExpression n, C ctx) throws Exception;\r\n\r\n public <E extends Node> void visit(NodeList<E> n, C ctx) throws Exception;\r\n\r\n public void visit(NullLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(ObjectLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(OctalLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(Parameter n, C ctx) throws Exception;\r\n\r\n public void visit(Project n, C ctx) throws Exception;\r\n\r\n public void visit(PutAssignment n, C ctx) throws Exception;\r\n\r\n public void visit(RegexpLiteral n, C ctx) throws Exception;\r\n\r\n public void visit(ReturnStatement n, C ctx) throws Exception;\r\n\r\n public void visit(SequenceExpression n, C ctx) throws Exception;\r\n\r\n public void visit(SetAssignment n, C ctx) throws Exception;\r\n\r\n public void visit(StringLiteralDouble n, C ctx) throws Exception;\r\n\r\n public void visit(StringLiteralSingle n, C ctx) throws Exception;\r\n\r\n public void visit(SuperExpression n, C ctx) throws Exception;\r\n\r\n public void visit(SwitchStatement n, C ctx) throws Exception;\r\n\r\n public void visit(ThisExpression n, C ctx) throws Exception;\r\n\r\n public void visit(ThrowStatement n, C ctx) throws Exception;\r\n\r\n public void visit(TryStatement n, C ctx) throws Exception;\r\n\r\n public void visit(UnaryExpression n, C ctx) throws Exception;\r\n\r\n public void visit(UnaryOperator n, C ctx) throws Exception;\r\n\r\n public void visit(VariableDeclaration n, C ctx) throws Exception;\r\n\r\n public void visit(VariableExpression n, C ctx) throws Exception;\r\n\r\n public void visit(VariableStatement n, C ctx) throws Exception;\r\n\r\n public void visit(WhileStatement n, C ctx) throws Exception;\r\n\r\n public void visit(WithStatement n, C ctx) throws Exception;\r\n\r\n}\r", "public interface GenericVisitor<R, C> {\r\n\r\n public R visit(AllocationExpression n, C ctx) throws Exception;\r\n\r\n public R visit(ArrayAccessExpression n, C ctx) throws Exception;\r\n\r\n public R visit(ArrayLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(AssignmentExpression n, C ctx) throws Exception;\r\n\r\n public R visit(AssignOperator n, C ctx) throws Exception;\r\n\r\n public R visit(BinaryExpression n, C ctx) throws Exception;\r\n\r\n public R visit(BinaryOperator n, C ctx) throws Exception;\r\n\r\n public R visit(Block n, C ctx) throws Exception;\r\n\r\n public R visit(BlockComment n, C ctx) throws Exception;\r\n\r\n public R visit(BooleanLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(BreakStatement n, C ctx) throws Exception;\r\n\r\n public R visit(CallExpression n, C ctx) throws Exception;\r\n\r\n public R visit(CaseBlock n, C ctx) throws Exception;\r\n\r\n public R visit(CaseClause n, C ctx) throws Exception;\r\n\r\n public R visit(CatchClause n, C ctx) throws Exception;\r\n\r\n public R visit(CompilationUnit n, C ctx) throws Exception;\r\n\r\n public R visit(ConditionalExpression n, C ctx) throws Exception;\r\n\r\n public R visit(ConstantStatement n, C ctx) throws Exception;\r\n\r\n public R visit(ContinueStatement n, C ctx) throws Exception;\r\n\r\n public R visit(DebuggerStatement n, C ctx) throws Exception;\r\n\r\n public R visit(DecimalLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(DefaultClause n, C ctx) throws Exception;\r\n\r\n public R visit(DoWhileStatement n, C ctx) throws Exception;\r\n\r\n public R visit(EmptyLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(EmptyStatement n, C ctx) throws Exception;\r\n\r\n public R visit(EnclosedExpression n, C ctx) throws Exception;\r\n\r\n public R visit(ExpressionStatement n, C ctx) throws Exception;\r\n\r\n public R visit(FieldAccessExpression n, C ctx) throws Exception;\r\n\r\n public R visit(FloatLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(ForeachStatement n, C ctx) throws Exception;\r\n\r\n public R visit(ForStatement n, C ctx) throws Exception;\r\n\r\n public R visit(FunctionDeclaration n, C ctx) throws Exception;\r\n\r\n public R visit(FunctionExpression n, C ctx) throws Exception;\r\n\r\n public R visit(GetAssignment n, C ctx) throws Exception;\r\n\r\n public R visit(HexIntegerLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(IdentifierName n, C ctx) throws Exception;\r\n\r\n public R visit(IfStatement n, C ctx) throws Exception;\r\n\r\n public R visit(ImportStatement n, C ctx) throws Exception;\r\n\r\n public R visit(JSDocComment n, C ctx) throws Exception;\r\n\r\n public R visit(LabelledStatement n, C ctx) throws Exception;\r\n\r\n public R visit(LetDefinition n, C ctx) throws Exception;\r\n\r\n public R visit(LetExpression n, C ctx) throws Exception;\r\n\r\n public R visit(LetStatement n, C ctx) throws Exception;\r\n\r\n public R visit(LineComment n, C ctx) throws Exception;\r\n\r\n public R visit(NewExpression n, C ctx) throws Exception;\r\n\r\n public <E extends Node> R visit(NodeList<E> n, C ctx) throws Exception;\r\n\r\n public R visit(NullLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(ObjectLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(OctalLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(Parameter n, C ctx) throws Exception;\r\n\r\n public R visit(Project n, C ctx) throws Exception;\r\n\r\n public R visit(PutAssignment n, C ctx) throws Exception;\r\n\r\n public R visit(RegexpLiteral n, C ctx) throws Exception;\r\n\r\n public R visit(ReturnStatement n, C ctx) throws Exception;\r\n\r\n public R visit(SequenceExpression n, C ctx) throws Exception;\r\n\r\n public R visit(SetAssignment n, C ctx) throws Exception;\r\n\r\n public R visit(StringLiteralDouble n, C ctx) throws Exception;\r\n\r\n public R visit(StringLiteralSingle n, C ctx) throws Exception;\r\n\r\n public R visit(SuperExpression n, C ctx) throws Exception;\r\n\r\n public R visit(SwitchStatement n, C ctx) throws Exception;\r\n\r\n public R visit(ThisExpression n, C ctx) throws Exception;\r\n\r\n public R visit(ThrowStatement n, C ctx) throws Exception;\r\n\r\n public R visit(TryStatement n, C ctx) throws Exception;\r\n\r\n public R visit(UnaryExpression n, C ctx) throws Exception;\r\n\r\n public R visit(UnaryOperator n, C ctx) throws Exception;\r\n\r\n public R visit(VariableDeclaration n, C ctx) throws Exception;\r\n\r\n public R visit(VariableExpression n, C ctx) throws Exception;\r\n\r\n public R visit(VariableStatement n, C ctx) throws Exception;\r\n\r\n public R visit(WhileStatement n, C ctx) throws Exception;\r\n\r\n public R visit(WithStatement n, C ctx) throws Exception;\r\n\r\n}\r" ]
import com.digiarea.es5.Node; import com.digiarea.es5.CompilationUnit; import com.digiarea.es5.NodeList; import com.digiarea.es5.JSDocComment; import com.digiarea.es5.visitor.VoidVisitor; import com.digiarea.es5.visitor.GenericVisitor;
package com.digiarea.es5; /** * The Class Project. */ public class Project extends Node { /** * The compilation units. */ private NodeList<CompilationUnit> compilationUnits = null; public NodeList<CompilationUnit> getCompilationUnits() { return compilationUnits; } public void setCompilationUnits(NodeList<CompilationUnit> compilationUnits) { this.compilationUnits = compilationUnits; } Project() { super(); } Project(NodeList<CompilationUnit> compilationUnits, JSDocComment jsDocComment, int posBegin, int posEnd) { super(jsDocComment, posBegin, posEnd); this.compilationUnits = compilationUnits; } @Override
public <C> void accept(VoidVisitor<C> v, C ctx) throws Exception {
4
gonmarques/cdi-properties
cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java
[ "public class LocaleThreadLocal {\n\n public static final ThreadLocal<LocaleThreadLocal> localeThreadLocal = new ThreadLocal<>();\n private final Locale locale;\n\n public LocaleThreadLocal(Locale locale) {\n this.locale = locale;\n }\n\n public Locale getLocale() {\n return locale;\n }\n\n}", "@WebServlet(urlPatterns = \"/testservlet\")\npublic class TestServlet extends HttpServlet {\n\n private static final long serialVersionUID = 1L;\n\n @EJB\n private OtherService otherService;\n\n @Override\n protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {\n Assert.assertEquals(Integer.class, otherService.getInteger().getClass());\n Assert.assertEquals(new Integer(2), otherService.getInteger());\n req.setAttribute(\"result\", otherService.getText());\n req.setAttribute(\"integer\", otherService.getInteger());\n req.getRequestDispatcher(\"test.jsp\").forward(req, resp);\n }\n\n}", "public static class DeploymentAppenderFactory {\n\n private DeploymentAppenderFactory() {\n }\n\n public static WebDeploymentAppender create(WebArchive archive) {\n return new WebDeploymentAppender(archive);\n }\n\n public static JavaDeploymentAppender create(JavaArchive archive) {\n return new JavaDeploymentAppender(archive);\n }\n\n public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {\n return new EnterpriseDeploymentAppender(archive);\n }\n}", "@Local\npublic interface OtherService extends Serializable {\n\n String getText();\n\n Integer getInteger();\n\n}", "@Stateless\npublic class OtherServiceBean implements OtherService {\n\n private static final long serialVersionUID = 1L;\n\n @Property(\"hello.world\")\n private String text;\n\n @Property(\"some.integer\")\n private Integer integer;\n\n @Override\n public String getText() {\n return text;\n }\n\n @Override\n public Integer getInteger() {\n return integer;\n }\n\n}", "@ApplicationScoped\npublic class ProvidedLocaleMethodResolverThreadLocal implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @LocaleResolver\n public Locale resolveLocale() {\n return LocaleThreadLocal.localeThreadLocal.get().getLocale();\n }\n\n}" ]
import java.io.IOException; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import com.byteslounge.cdi.test.common.LocaleThreadLocal; import com.byteslounge.cdi.test.common.servlet.TestServlet; import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory; import com.byteslounge.cdi.test.wpm.OtherService; import com.byteslounge.cdi.test.wpm.OtherServiceBean; import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverThreadLocal;
/* * Copyright 2015 byteslounge.com (Gonçalo Marques). * * 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.byteslounge.cdi.test.it.common; /** * Base class for Integration Tests which resolve the current locale from a ThreadLocal variable * * @author Gonçalo Marques * @since 1.1.0 */ public abstract class AbstractWarProvidedLocaleMethodThreadLocal { protected static WebArchive createArchive() throws IOException { WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses( ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class,
TestServlet.class, LocaleThreadLocal.class);
1
alexandre-normand/blood-shepherd
dexcom-receiver/src/test/java/org/glukit/dexcom/sync/TestDexcomAdapterService.java
[ "public class DexcomG4Constants {\n\n public static final int DATA_BITS = 8;\n public static final int STOP_BITS = 1;\n public static final int NO_PARITY = 0;\n public static final int FIRMWARE_BAUD_RATE = 0x9600;\n public static final Instant DEXCOM_EPOCH = Instant.from(ZonedDateTime.of(2009, 1, 1, 0, 0, 0, 0, ZoneId.of(\"UTC\")));\n}", "@ToString\n@EqualsAndHashCode\npublic class DexcomSyncData implements ReceiverSyncData {\n private List<GlucoseReadRecord> glucoseReads;\n private List<UserEventRecord> userEvents;\n private ManufacturingParameters manufacturingParameters;\n private Instant syncTime;\n\n public DexcomSyncData(List<GlucoseReadRecord> glucoseReads,\n List<UserEventRecord> userEvents,\n ManufacturingParameters manufacturingParameters) {\n this.glucoseReads = glucoseReads;\n this.userEvents = userEvents;\n this.manufacturingParameters = manufacturingParameters;\n this.syncTime = Instant.now();\n }\n\n public DexcomSyncData(List<GlucoseReadRecord> glucoseReads,\n List<UserEventRecord> userEvents,\n ManufacturingParameters manufacturingParameters,\n Instant updateTime) {\n this.glucoseReads = glucoseReads;\n this.userEvents = userEvents;\n this.manufacturingParameters = manufacturingParameters;\n this.syncTime = updateTime;\n }\n\n public List<GlucoseReadRecord> getGlucoseReads() {\n return glucoseReads;\n }\n\n public ManufacturingParameters getManufacturingParameters() {\n return manufacturingParameters;\n }\n\n public List<UserEventRecord> getUserEvents() {\n return userEvents;\n }\n\n @Override\n public Instant getUpdateTime() {\n return syncTime;\n }\n}", "@EqualsAndHashCode\n@ToString\npublic class GlucoseReadRecord {\n public static final int RECORD_LENGTH = 13;\n\n private long internalSecondsSinceDexcomEpoch;\n private long localSecondsSinceDexcomEpoch;\n private int glucoseValueWithFlags;\n private byte trendArrowAndNoise;\n private long recordNumber;\n private long pageNumber;\n\n public GlucoseReadRecord(long internalSecondsSinceDexcomEpoch,\n long localSecondsSinceDexcomEpoch,\n int glucoseValueWithFlags,\n byte trendArrowAndNoise,\n long recordNumber,\n long pageNumber) {\n this.internalSecondsSinceDexcomEpoch = internalSecondsSinceDexcomEpoch;\n this.localSecondsSinceDexcomEpoch = localSecondsSinceDexcomEpoch;\n this.glucoseValueWithFlags = glucoseValueWithFlags;\n this.trendArrowAndNoise = trendArrowAndNoise;\n this.recordNumber = recordNumber;\n this.pageNumber = pageNumber;\n }\n\n public long getInternalSecondsSinceDexcomEpoch() {\n return internalSecondsSinceDexcomEpoch;\n }\n\n public long getLocalSecondsSinceDexcomEpoch() {\n return localSecondsSinceDexcomEpoch;\n }\n\n public int getGlucoseValueWithFlags() {\n return glucoseValueWithFlags;\n }\n\n public byte getTrendArrowAndNoise() {\n return trendArrowAndNoise;\n }\n\n public long getRecordNumber() {\n return recordNumber;\n }\n\n public long getPageNumber() {\n return pageNumber;\n }\n}", "public class ManufacturingParameters {\n @JacksonXmlProperty(isAttribute=true, localName = \"SerialNumber\")\n private String serialNumber;\n @JacksonXmlProperty(isAttribute=true, localName = \"HardwarePartNumber\")\n private String hardwarePartNumber;\n @JacksonXmlProperty(isAttribute=true, localName = \"HardwareRevision\")\n private String hardwareRevision;\n @JacksonXmlProperty(isAttribute=true, localName = \"DateTimeCreated\")\n private String dateTimeCreated;\n @JacksonXmlProperty(isAttribute=true, localName = \"HardwareId\")\n private String hardwareId;\n\n public ManufacturingParameters() {\n }\n\n public ManufacturingParameters(String serialNumber,\n String hardwarePartNumber,\n String hardwareRevision,\n String dateTimeCreated,\n String hardwareId) {\n this.serialNumber = serialNumber;\n this.hardwarePartNumber = hardwarePartNumber;\n this.hardwareRevision = hardwareRevision;\n this.dateTimeCreated = dateTimeCreated;\n this.hardwareId = hardwareId;\n }\n\n public String getSerialNumber() {\n return serialNumber;\n }\n\n public void setSerialNumber(String serialNumber) {\n this.serialNumber = serialNumber;\n }\n\n @JacksonXmlProperty(isAttribute=true)\n public String getHardwarePartNumber() {\n return hardwarePartNumber;\n }\n\n @JacksonXmlProperty(isAttribute=true)\n public void setHardwarePartNumber(String hardwarePartNumber) {\n this.hardwarePartNumber = hardwarePartNumber;\n }\n\n public String getHardwareRevision() {\n return hardwareRevision;\n }\n\n public void setHardwareRevision(String hardwareRevision) {\n this.hardwareRevision = hardwareRevision;\n }\n\n public String getDateTimeCreated() {\n return dateTimeCreated;\n }\n\n public void setDateTimeCreated(String dateTimeCreated) {\n this.dateTimeCreated = dateTimeCreated;\n }\n\n public String getHardwareId() {\n return hardwareId;\n }\n\n public void setHardwareId(String hardwareId) {\n this.hardwareId = hardwareId;\n }\n}", "@ToString\n@EqualsAndHashCode\npublic class UserEventRecord {\n public static final int RECORD_LENGTH = 20;\n\n private long internalSecondsSinceDexcomEpoch;\n private long localSecondsSinceDexcomEpoch;\n private UserEventType eventType;\n private byte eventSubType;\n private long eventSecondsSinceDexcomEpoch;\n private long eventValue;\n\n public UserEventRecord(long internalSecondsSinceDexcomEpoch,\n long localSecondsSinceDexcomEpoch,\n long eventSecondsSinceDexcomEpoch,\n UserEventType eventType,\n byte eventSubType,\n long eventValue) {\n this.internalSecondsSinceDexcomEpoch = internalSecondsSinceDexcomEpoch;\n this.localSecondsSinceDexcomEpoch = localSecondsSinceDexcomEpoch;\n this.eventType = eventType;\n this.eventSubType = eventSubType;\n this.eventSecondsSinceDexcomEpoch = eventSecondsSinceDexcomEpoch;\n this.eventValue = eventValue;\n }\n\n public long getInternalSecondsSinceDexcomEpoch() {\n return internalSecondsSinceDexcomEpoch;\n }\n\n public long getLocalSecondsSinceDexcomEpoch() {\n return localSecondsSinceDexcomEpoch;\n }\n\n public UserEventType getEventType() {\n return eventType;\n }\n\n public byte getEventSubType() {\n return eventSubType;\n }\n\n public long getEventSecondsSinceDexcomEpoch() {\n return eventSecondsSinceDexcomEpoch;\n }\n\n public long getEventValue() {\n return eventValue;\n }\n\n public static enum UserEventType {\n CARBS((byte) 1),\n EXERCISE((byte) 4),\n HEALTH((byte) 3),\n INSULIN((byte) 2),\n MaxValue((byte) 5),\n NullType((byte) 0);\n\n private byte id;\n private static Map<Byte, UserEventType> mappings;\n\n private UserEventType(byte id) {\n this.id = id;\n addMapping(id, this);\n }\n\n private static void addMapping(byte id, UserEventType recordType) {\n if (mappings == null) {\n mappings = newHashMap();\n }\n mappings.put(id, recordType);\n }\n\n public static UserEventType fromId(byte id) {\n return mappings.get(id);\n }\n\n public byte getId() {\n return id;\n }\n }\n\n public static enum ExerciseIntensity {\n HEAVY((byte) 3),\n LIGHT((byte) 1),\n MaxValue((byte) 4),\n MEDIUM((byte) 2),\n Null((byte) 0);\n\n private byte id;\n private static Map<Byte, ExerciseIntensity> mappings;\n\n private ExerciseIntensity(byte id) {\n this.id = id;\n addMapping(id, this);\n }\n\n private static void addMapping(byte id, ExerciseIntensity recordType) {\n if (mappings == null) {\n mappings = newHashMap();\n }\n mappings.put(id, recordType);\n }\n\n public static ExerciseIntensity fromId(byte id) {\n return mappings.get(id);\n }\n\n public byte getId() {\n return id;\n }\n }\n}", "static final List<Integer> SPECIAL_GLUCOSE_VALUES = Arrays.asList(0, 1, 2, 3, 5, 6, 9, 10, 12);", "public static final String UNAVAILABLE_INSULIN_NAME = \"N/A\";" ]
import org.glukit.dexcom.sync.g4.DexcomG4Constants; import org.glukit.dexcom.sync.model.DexcomSyncData; import org.glukit.dexcom.sync.model.GlucoseReadRecord; import org.glukit.dexcom.sync.model.ManufacturingParameters; import org.glukit.dexcom.sync.model.UserEventRecord; import org.glukit.sync.api.*; import org.junit.Test; import org.threeten.bp.Duration; import org.threeten.bp.Instant; import org.threeten.bp.LocalDateTime; import org.threeten.bp.ZoneId; import java.util.Arrays; import java.util.Collections; import java.util.List; import static java.lang.String.format; import static org.glukit.dexcom.sync.DexcomAdapterService.SPECIAL_GLUCOSE_VALUES; import static org.glukit.sync.api.InsulinInjection.InsulinType.UNKNOWN; import static org.glukit.sync.api.InsulinInjection.UNAVAILABLE_INSULIN_NAME; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat;
package org.glukit.dexcom.sync; /** * Unit test of {@link DexcomAdapterService}. * * @author alexandre.normand */ public class TestDexcomAdapterService { private static final String SERIAL_NUMBER = "serial"; private static final String HARDWARE_REVISION = "revision1"; private static final String HARDWARE_ID = "hardwareId"; private static final Integer NORMAL_READ_TEST_VALUE = 83; private static final List<GlucoseRead> EMPTY_GLUCOSE_READS = Collections.emptyList();
private static final List<GlucoseReadRecord> EMPTY_GLUCOSE_READ_RECORDS = Collections.emptyList();
2
AVMf/avmf
src/main/java/org/avmframework/examples/inputdatageneration/line/LineTestObject.java
[ "public class Vector extends AbstractVector {\n\n public void addVariable(Variable variable) {\n variables.add(variable);\n }\n\n public List<Variable> getVariables() {\n return new ArrayList<>(variables);\n }\n\n public void setVariablesToInitial() {\n for (Variable var : variables) {\n var.setValueToInitial();\n }\n }\n\n public void setVariablesToRandom(RandomGenerator rg) {\n for (Variable var : variables) {\n var.setValueToRandom(rg);\n }\n }\n\n public Vector deepCopy() {\n Vector copy = new Vector();\n deepCopyVariables(copy);\n return copy;\n }\n}", "public class Branch {\n public static String TRUE = \"T\";\n public static String FALSE = \"F\";\n\n protected int node;\n protected boolean edge;\n\n public Branch(int id, boolean edge) {\n this.node = id;\n this.edge = edge;\n }\n\n public int getId() {\n return node;\n }\n\n public boolean getEdge() {\n return edge;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (!(obj instanceof Branch)) {\n return false;\n }\n\n Branch branch = (Branch) obj;\n\n if (node != branch.node) {\n return false;\n }\n return edge == branch.edge;\n }\n\n @Override\n public int hashCode() {\n int result = node;\n result = 31 * result + (edge ? 1 : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return node + (edge ? TRUE : FALSE);\n }\n\n public static Branch instantiate(String id) {\n return instantiate(id, null);\n }\n\n public static Branch instantiate(String id, TestObject testObject) {\n if (id.length() >= 2) {\n String edgeCharacter = id.substring(id.length() - 1, id.length());\n\n boolean gotEdge = false;\n boolean edge = false;\n\n if (edgeCharacter.equals(TRUE)) {\n edge = true;\n gotEdge = true;\n } else if (edgeCharacter.equals(FALSE)) {\n edge = false;\n gotEdge = true;\n }\n\n if (gotEdge) {\n String nodeString = id.substring(0, id.length() - 1);\n try {\n int node = Integer.parseInt(nodeString);\n\n boolean validNode = node >= 1;\n System.out.println(testObject.getNumBranchingNodes());\n if (testObject != null && node > testObject.getNumBranchingNodes()) {\n validNode = false;\n }\n if (!validNode) {\n throw new RuntimeException(\n \"Branch node \\\"\" + node + \"\\\" does not exist for the test object specified\");\n }\n\n return new Branch(node, edge);\n\n } catch (NumberFormatException exception) {\n throw new RuntimeException(\"Branch node \\\"\" + nodeString + \"\\\" not recognized\");\n }\n } else {\n throw new RuntimeException(\"Unrecognized branch edge (must be \\\"T\\\" or \\\"F\\\")\");\n }\n } else {\n throw new RuntimeException(\"Branch ID should be over two characters long\");\n }\n }\n}", "public abstract class BranchTargetObjectiveFunction extends ObjectiveFunction {\n\n protected Branch target;\n protected ControlDependenceChain controlDependenceChain;\n protected ExecutionTrace trace;\n\n public BranchTargetObjectiveFunction(Branch target) {\n this.target = target;\n this.controlDependenceChain = getControlDependenceChainForTarget();\n }\n\n protected abstract ControlDependenceChain getControlDependenceChainForTarget();\n\n protected ObjectiveValue computeObjectiveValue(Vector vector) {\n trace = new ExecutionTrace();\n executeTestObject(vector);\n DivergencePoint divergencePoint = controlDependenceChain.getDivergencePoint(trace);\n\n int approachLevel = 0;\n double distance = 0;\n if (divergencePoint != null) {\n approachLevel = divergencePoint.chainIndex;\n distance = trace.getBranchExecution(divergencePoint.traceIndex).getDistanceToAlternative();\n }\n return new BranchTargetObjectiveValue(approachLevel, distance);\n }\n\n protected abstract void executeTestObject(Vector vector);\n}", "public abstract class TestObject {\n\n public abstract Vector getVector();\n\n public abstract BranchTargetObjectiveFunction getObjectiveFunction(Branch target);\n\n public abstract int getNumBranchingNodes();\n\n public static TestObject instantiate(String name) {\n String testObjectClassName =\n \"org.avmframework.examples.inputdatageneration.\"\n + name.toLowerCase()\n + \".\"\n + name\n + \"TestObject\";\n\n try {\n Class<?> testObjectClass = Class.forName(testObjectClassName);\n return (TestObject) testObjectClass.newInstance();\n } catch (ClassNotFoundException | InstantiationException | IllegalAccessException exception) {\n throw new RuntimeException(\"Unable to instantiate test object \\\"\" + name + \"\\\"\");\n }\n }\n}", "public class FixedPointVariable extends AtomicVariable {\n\n protected int precision;\n\n public FixedPointVariable(double initialValue, int precision, double min, double max) {\n super(\n doubleToInt(initialValue, precision),\n doubleToInt(min, precision),\n doubleToInt(max, precision));\n this.precision = precision;\n if (min > max) {\n throw new MinGreaterThanMaxException(min, max);\n }\n setValueToInitial();\n }\n\n public double asDouble() {\n return intToDouble(value, precision);\n }\n\n @Override\n public FixedPointVariable deepCopy() {\n FixedPointVariable copy = new FixedPointVariable(initialValue, precision, min, max);\n copy.value = value;\n return copy;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (!(obj instanceof FixedPointVariable)) {\n return false;\n }\n if (!super.equals(obj)) {\n return false;\n }\n\n FixedPointVariable that = (FixedPointVariable) obj;\n\n return precision == that.precision;\n }\n\n @Override\n public int hashCode() {\n int result = super.hashCode();\n result = 31 * result + precision;\n return result;\n }\n\n @Override\n public String toString() {\n return String.format(\"%.\" + precision + \"f\", asDouble());\n }\n\n private static int doubleToInt(double value, int precision) {\n return (int) Math.round(value * Math.pow(10, precision));\n }\n\n private static double intToDouble(int value, int precision) {\n return ((double) value) * Math.pow(10, -precision);\n }\n}" ]
import org.avmframework.Vector; import org.avmframework.examples.inputdatageneration.Branch; import org.avmframework.examples.inputdatageneration.BranchTargetObjectiveFunction; import org.avmframework.examples.inputdatageneration.TestObject; import org.avmframework.variable.FixedPointVariable;
package org.avmframework.examples.inputdatageneration.line; public class LineTestObject extends TestObject { static final int NUM_BRANCHING_NODES = 7; static final int PRECISION = 1; static final double INITIAL_VALUE = 0.0; static final double MIN = 0.0; static final double MAX = 100.0; @Override public Vector getVector() { Vector vector = new Vector(); for (int i = 0; i < 8; i++) { vector.addVariable(new FixedPointVariable(INITIAL_VALUE, PRECISION, MIN, MAX)); } return vector; } @Override
public BranchTargetObjectiveFunction getObjectiveFunction(Branch target) {
2
dannormington/appengine-cqrs
src/main/java/com/cqrs/appengine/core/persistence/EventRepository.java
[ "public interface AggregateRoot {\n\n /**\n * get the Id\n * \n * @return\n */\n UUID getId();\n\n /**\n * Gets all change events since the\n * original hydration. If there are no\n * changes then null is returned\n * \n * @return\n */\n Iterable<Event> getUncommittedChanges();\n\n /**\n * Mark all changes a committed\n */\n void markChangesAsCommitted();\n\n /**\n * load the aggregate root\n * \n * @param history\n * @throws HydrationException \n */\n void loadFromHistory(Iterable<Event> history) throws HydrationException;\n\n /**\n * Returns the version of the aggregate when it was hydrated\n * @return\n */\n int getExpectedVersion();\n}", "public class AggregateNotFoundException extends AggregateException {\n\n\tprivate static final String ERROR_TEXT = \"The aggregate you requested cannot be found.\";\n\t\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Constructor\n\t * \n\t * @param aggregateId\n\t */\n\tpublic AggregateNotFoundException(UUID aggregateId) {\n\t\tsuper(aggregateId, ERROR_TEXT);\n\t}\n\n}", "public class EventCollisionException extends AggregateException {\n\n private static final String ERROR_TEXT = \"Data has been changed between loading and state changes.\";\n\n private static final long serialVersionUID = 1L;\n\n private int expectedVersion;\n private Date dateOccurred;\n\n /**\n * Constructor\n * \n * @param aggregateId\n * @param expectedVersion\n */\n public EventCollisionException(UUID aggregateId, int expectedVersion){\n this(aggregateId, expectedVersion, ERROR_TEXT);\n }\n \n /**\n * Constructor\n * \n * @param aggregateId\n * @param expectedVersion\n * @param message\n */\n public EventCollisionException(UUID aggregateId, int expectedVersion, String message){\n super(aggregateId, message);\n this.expectedVersion = expectedVersion;\n this.dateOccurred = new Date();\n }\n\n /**\n * Get the expected version when the collision occurred\n * \n * @return\n */\n public int getExpectedVersion(){\n return expectedVersion;\n }\n\n /**\n * Get the date the exception occurred\n * \n * @return\n */\n public Date getDateOccurred(){\n return dateOccurred;\n }\n}", "public class HydrationException extends AggregateException {\n\n private static final String ERROR_TEXT = \"Loading the data failed\";\n\n private static final long serialVersionUID = 1L;\n\n /**\n * Default constructor\n * \n * @param aggregateId\n */\n public HydrationException(UUID aggregateId){\n super(aggregateId, ERROR_TEXT);\n }\n\n /**\n * Constructor to provide specific error reason for the hydration exception\n * \n * @param aggregateId\n * @param error\n */\n public HydrationException(UUID aggregateId, String error){\n super(aggregateId, error);\n }\n}", "public interface Event {\n\n}" ]
import java.util.UUID; import com.cqrs.appengine.core.domain.AggregateRoot; import com.cqrs.appengine.core.exceptions.AggregateNotFoundException; import com.cqrs.appengine.core.exceptions.EventCollisionException; import com.cqrs.appengine.core.exceptions.HydrationException; import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.persistence; /** * Implementation of a simple event repository * * @param <T> */ public class EventRepository<T extends AggregateRoot> implements Repository<T> { /** * Instance of the event store */ private EventStore eventStore; /** * The class type that the repository is working with */ private Class<T> aClass; /** * Default Constructor * * @param aClass */ public EventRepository(Class<T> aClass){ this.aClass = aClass; eventStore = new AppEngineEventStore(); } /** * Constructor to be used when specifying a specific * queue for events to be published to * * @param aClass */ public EventRepository(Class<T> aClass, String queue){ this.aClass = aClass; eventStore = new AppEngineEventStore(queue); } @Override
public void save(T aggregate) throws EventCollisionException {
2
highway-to-urhell/highway-to-urhell
h2hell-core/src/main/java/com/highway2urhell/service/ThunderExporterService.java
[ "public class CoreEngine {\n\n\tprivate static CoreEngine instance;\n\n\tprivate Map<String, LeechService> leechPluginRegistry = new HashMap<String, LeechService>();\n\tprivate Set<ReporterService> reporterPluginRegistry = new HashSet<ReporterService>();\n\tprivate final static String H2H_CONFIG = \"H2H_CONFIG\";\n\tprivate final static String JAVA = \"Java\";\n\tprivate final static Integer DEFAULT_TIMER = 2000;\n\tprivate final static String NO_URL = \"NO_URL\";\n\tprivate final static String NO_SOURCE = \"NO_SOURCE\";\n\n\tprivate H2hConfig config;\n\n\tprivate CoreEngine() {\n\t\t// nothing\n\t}\n\n\tpublic static CoreEngine getInstance() {\n\t\tif (instance == null) {\n\t\t\tsynchronized (CoreEngine.class) {\n\t\t\t\tif (instance == null) {\n\t\t\t\t\tinstance = new CoreEngine();\n\t\t\t\t\tinstance.registerPlugins();\n\t\t\t\t\tinstance.runPluginsTriggeredAtStartup();\n\t\t\t\t\tinstance.configure();\n\t\t\t\t\tinstance.runListener();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn instance;\n\t}\n\n\tprivate void runListener() {\n\t\tScheduledExecutorService schExService = Executors.newScheduledThreadPool(1);\n\t\tschExService.scheduleAtFixedRate(new Runnable() {\n\n\t\t\tpublic void run() {\n\t\t\t\tSystem.out.println(\"Call the H2H-Web server\");\n\t\t\t\tListenerService.getInstance().callServerH2H();\n\t\t\t}\n\t\t}, 5, 10, TimeUnit.SECONDS);\n\t}\n\n\tpublic void enableEntryPointCoverage(FilterEntryPath filter)\n\t\t\tthrows ClassNotFoundException, UnmodifiableClassException {\n\t\tSystem.out.println(\"enabling entry point coverage \"+filter.toString());\n\t\tInstrumentation instrumentation = InstrumentationHolder.getInstance().getInst();\n\t\tif (instrumentation != null) {\n\t\t\tTransformerService ts = new TransformerService();\n\t\t\tMap<String, List<EntryPathData>> mapConvert = ts\n\t\t\t\t\t.transformDataFromLeechPluginForTransformation(leechPluginRegistry.values(), filter);\n\t\t\tif (!config.getPathSend()) {\n\t\t\t\t// if the initPath are not called\n\t\t\t\tinitPathsRemote();\n\t\t\t}\n\t\t\tinstrumentation.addTransformer(\n\t\t\t\t\tnew EntryPointTransformer(mapConvert, CoreEngine.getInstance().getConfig().getPerformance()), true);\n\t\t\tts.transformAllClassScanByH2h(instrumentation, mapConvert.keySet());\n\t\t} else {\n\t\t\tSystem.err.println(\"Instrumentation fail because internal inst is null\");\n\t\t}\n\t}\n\n\tprivate void getLineNumberFromEntryPoint(FilterEntryPath filter)\n\t\t\tthrows ClassNotFoundException, UnmodifiableClassException {\n\t\tSystem.out.println(\"enabling getLineNumberFromEntryPoint \"+filter.toString());\n\t\tInstrumentation instrumentation = InstrumentationHolder.getInstance().getInst();\n\t\tif (instrumentation != null) {\n\t\t\tTransformerService ts = new TransformerService();\n\t\t\tMap<String, List<EntryPathData>> mapConvert = ts\n\t\t\t\t\t.transformDataFromLeechPluginForTransformation(leechPluginRegistry.values(), filter);\n\t\t\tinstrumentation.addTransformer(new LineNumberEntryPointTransformer(mapConvert));\n\t\t\tts.transformAllClassScanByH2h(instrumentation, mapConvert.keySet());\n\t\t} else {\n\t\t\tSystem.err.println(\"Instrumentation fail because internal inst is null\");\n\t\t}\n\t}\n\n\tpublic void initPathsRemoteWithOutTransformerLine() {\n\t\tThunderExporterService.getInstance().initPathsRemoteApp();\n\t\tconfig.setPathSend(true);\n\t}\n\n\tpublic void initPathsRemote() {\n\t\tif (config.getToken() != null && !config.getPathSend()) {\n\t\t\ttry {\n\t\t\t\tFilterEntryPath filter = new FilterEntryPath();\n\t\t\t\tfilter.setFilter(true);\n\t\t\t\tfilter.setListFilter(new ArrayList<String>());\n\t\t\t\tgetLineNumberFromEntryPoint(filter);\n\t\t\t\tThunderExporterService.getInstance().initPathsRemoteApp();\n\t\t\t\tconfig.setPathSend(true);\n\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\tSystem.err.println(\"Error while launchTransformer \"+ e);\n\t\t\t} catch (UnmodifiableClassException e) {\n\t\t\t\tSystem.err.println(\"Error while launchTransformer \"+ e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void updateLineNumberEntryPoint(EntryPathData entry) {\n\t\tSystem.out.println(\"Try to update entry \"+entry);\n\t\tfor (LeechService leech : leechPluginRegistry.values()) {\n\t\t\tfor (EntryPathData entryPath : leech.getFrameworkInformations().getListEntryPath()) {\n\t\t\t\tif(entryPath.getClassName().equals(entry.getClassName()) && entryPath.getMethodName().equals(entry.getMethodName()) && entryPath.getSignatureName().equals(entry.getSignatureName())){\n\t\t\t\t\tentryPath.setLineNumber(entry.getLineNumber());\n\t\t\t\t\tSystem.out.println(\"Update complete entry \"+entry);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void leech() {\n\t\tfor (ReporterService reporterService : reporterPluginRegistry) {\n\t\t\tfor (LeechService leechService : leechPluginRegistry.values()) {\n\t\t\t\treporterService.report(leechService.getFrameworkInformations());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic Collection<LeechService> getLeechServiceRegistered() {\n\t\treturn leechPluginRegistry.values();\n\t}\n\n\tpublic LeechService getFramework(String frameworkName) {\n\t\treturn leechPluginRegistry.get(frameworkName);\n\t}\n\n\tprivate void registerPlugins() {\n\t\tautoDiscoverLeechPlugins();\n\t\tautoDiscoverReporterPlugins();\n\t}\n\n\tprivate void autoDiscoverLeechPlugins() {\n\t\tSet<AbstractLeechService> leechServices = PluginUtils.autodiscoverPlugin(AbstractLeechService.class);\n\t\tfor (AbstractLeechService leechService : leechServices) {\n\t\t\tleechPluginRegistry.put(leechService.getFrameworkInformations().getFrameworkName(), leechService);\n\t\t}\n\t}\n\n\tprivate void autoDiscoverReporterPlugins() {\n\t\treporterPluginRegistry = PluginUtils.autodiscoverPlugin(ReporterService.class);\n\t}\n\n\tprivate void runPluginsTriggeredAtStartup() {\n\t\tfor (LeechService leechService : leechPluginRegistry.values()) {\n\t\t\tif (leechService.isTriggeredAtStartup()) {\n\t\t\t\tleechService.receiveData(null);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void configure() {\n\t\t// Grab Env\n\t\tString rootH2h = System.getProperty(H2H_CONFIG);\n\t\tif (rootH2h == null) {\n\t\t\tdefaultConfig();\n\t\t} else if (\"\".equals(rootH2h)) {\n\t\t\tdefaultConfig();\n\t\t} else {\n\t\t\tparseConfig(rootH2h);\n\t\t}\n\t}\n\n\tprivate void defaultConfig() {\n\t\tconfig = new H2hConfig();\n\t\tconfig.setTypeAppz(JAVA);\n\t\tconfig.setUrlApplication(NO_URL);\n\t\tconfig.setNameApplication(String.valueOf(System.currentTimeMillis()));\n\t\tconfig.setPathSource(NO_SOURCE);\n\t\tconfig.setDescription(\"Default Name.\");\n\t\tconfig.setPerformance(false);\n\t\tconfig.setTimer(OutputSystem.REMOTE);\n\t\tconfig.setHigherTime(DEFAULT_TIMER);\n\t\t// TODO\n\t\t// Hardcoded la valeur de la plateforme --> le jour ou la plateforme\n\t\t// fonctionnera ... one day ... one day ..\n\t\t// Actuellement on hardcode le local\n\t\tconfig.setUrlH2hWeb(\"http://localhost:8090/core/api/ThunderEntry\");\n\t\t// TODO\n\t\t// Recuperer le token comme parametre le jour ou la plate fonctionnera\n\t\t// ... one day ... one day ..\n\t\tconfig.setToken(null);\n\t}\n\n\tprivate void parseConfig(String pathFile) {\n\t\tconfig = new H2hConfig();\n\t\tconfig.setTypeAppz(JAVA);\n\t\tProperties prop = new Properties();\n\t\tInputStream input = null;\n\t\ttry {\n\t\t\tinput = new FileInputStream(pathFile);\n\t\t\tprop.load(input);\n\t\t\tconfig.setUrlApplication(prop.getProperty(\"urlapplication\"));\n\t\t\tconfig.setNameApplication(prop.getProperty(\"nameapplication\"));\n\t\t\tconfig.setPathH2h(prop.getProperty(\"pathH2h\"));\n\t\t\tconfig.setPathSource(prop.getProperty(\"pathSource\"));\n\t\t\tconfig.setDescription(prop.getProperty(\"description\"));\n\t\t\tconfig.setVersionApp(prop.getProperty(\"versionApp\"));\n\t\t\tconfig.setToken(prop.getProperty(\"token\"));\n\t\t\tconfig.setReference(prop.getProperty(\"reference\"));\n\t\t\tString performance = prop.getProperty(\"performance\");\n\t\t\tif (performance != null && performance.equals(\"true\")) {\n\t\t\t\tconfig.setPerformance(true);\n\t\t\t} else {\n\t\t\t\tconfig.setPerformance(false);\n\t\t\t}\n\t\t\tString timer = prop.getProperty(\"timer\");\n\t\t\tif (timer != null) {\n\t\t\t\tconfig.setTimer(OutputSystem.valueOf(timer));\n\t\t\t} else {\n\t\t\t\tthrow new RuntimeException(\"Variable timer is not defined\");\n\t\t\t}\n\t\t\tconfig.setUrlH2hWeb(prop.getProperty(\"urlh2hweb\"));\n\t\t\tString higherTimer = prop.getProperty(\"higherTimer\");\n\t\t\tif (higherTimer != null) {\n\t\t\t\ttry {\n\t\t\t\t\tconfig.setHigherTime(Integer.valueOf(higherTimer));\n\t\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t\t// default value\n\t\t\t\t\tconfig.setHigherTime(DEFAULT_TIMER);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// default value\n\t\t\t\tconfig.setHigherTime(DEFAULT_TIMER);\n\t\t\t}\n\n\t\t} catch (IOException ex) {\n\t\t\tthrow new RuntimeException(\"Error while reading H2hConfigFile \" + pathFile, ex);\n\t\t} finally {\n\t\t\tif (input != null) {\n\t\t\t\ttry {\n\t\t\t\t\tinput.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t// Don't care\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic H2hConfig getConfig() {\n\t\treturn config;\n\t}\n\n}", "public class EntryPathData {\n private String uri;\n private String methodName;\n private String className;\n private String classNameNormalized;\n private String signatureName;\n private TypePath typePath = TypePath.UNKNOWN;\n private Boolean audit = true;\n private String httpMethod = \"\";\n private List<EntryPathParam> listEntryPathData = new ArrayList<EntryPathParam>();\n private Integer lineNumber;\n\n public Integer getLineNumber() {\n\t\treturn lineNumber;\n\t}\n\n\tpublic void setLineNumber(Integer lineNumber) {\n\t\tthis.lineNumber = lineNumber;\n\t}\n\n\tpublic Boolean getAudit() {\n return audit;\n }\n\n public void setAudit(Boolean audit) {\n this.audit = audit;\n }\n\n public String getUri() {\n return uri;\n }\n\n public void setUri(String uri) {\n this.uri = uri;\n }\n\n public String getMethodName() {\n return methodName;\n }\n\n public void setMethodName(String methodName) {\n this.methodName = methodName;\n }\n\n public String getClassName() {\n return className;\n }\n\n public void setClassName(String className) {\n this.className = className;\n }\n\n public String getClassNameNormalized() {\n return classNameNormalized;\n }\n\n public void setClassNameNormalized(String classNameNormalized) {\n this.classNameNormalized = classNameNormalized;\n }\n\n public String getSignatureName() {\n return signatureName;\n }\n\n public void setSignatureName(String signatureName) {\n this.signatureName = signatureName;\n }\n\n public TypePath getTypePath() {\n return typePath;\n }\n\n public void setTypePath(TypePath typePath) {\n this.typePath = typePath;\n }\n\n public String getHttpMethod() {\n return httpMethod;\n }\n\n public void setHttpMethod(String httpMethod) {\n this.httpMethod = httpMethod;\n }\n\n public List<EntryPathParam> getListEntryPathData() {\n return listEntryPathData;\n }\n\n public void setListEntryPathData(List<EntryPathParam> listEntryPathData) {\n this.listEntryPathData = listEntryPathData;\n }\n\n @Override\n public String toString() {\n return \"EntryPathData [uri=\" + uri + \", methodName=\" + methodName\n + \", className=\" + className + \", classNameNormalized=\"\n + classNameNormalized + \", signatureName=\" + signatureName\n + \", typePath=\" + typePath + \", httpMethod=\" + httpMethod\n + \"]\";\n }\n}", "public class MessageBreaker {\n private String pathClassMethodName;\n private String token;\n private String dateIncoming;\n private String parameters;\n\n public String getParameters() {\n return parameters;\n }\n\n public void setParameters(String parameters) {\n this.parameters = parameters;\n }\n\n public String getPathClassMethodName() {\n return pathClassMethodName;\n }\n\n public void setPathClassMethodName(String pathClassMethodName) {\n this.pathClassMethodName = pathClassMethodName;\n }\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 getDateIncoming() {\n return dateIncoming;\n }\n\n public void setDateIncoming(String dateIncoming) {\n this.dateIncoming = dateIncoming;\n }\n\n}", "public class MessageMetrics {\n\tprivate String pathClassMethodName;\n\tprivate String token;\n\tprivate String dateIncoming;\n\tprivate int timeExec;\n\tprivate Double cpuLoadSystem;\n\tprivate Double cpuLoadProcess;\n\tprivate String parameters;\n\n\tpublic String getParameters() {\n\t\treturn parameters;\n\t}\n\n\tpublic void setParameters(String parameters) {\n\t\tthis.parameters = parameters;\n\t}\n\n\tpublic Double getCpuLoadSystem() {\n\t\treturn cpuLoadSystem;\n\t}\n\n\tpublic void setCpuLoadSystem(Double cpuLoadSystem) {\n\t\tthis.cpuLoadSystem = cpuLoadSystem;\n\t}\n\n\tpublic Double getCpuLoadProcess() {\n\t\treturn cpuLoadProcess;\n\t}\n\n\tpublic void setCpuLoadProcess(Double cpuLoadProcess) {\n\t\tthis.cpuLoadProcess = cpuLoadProcess;\n\t}\n\tpublic String getPathClassMethodName() {\n\t\treturn pathClassMethodName;\n\t}\n\tpublic void setPathClassMethodName(String pathClassMethodName) {\n\t\tthis.pathClassMethodName = pathClassMethodName;\n\t}\n\tpublic String getToken() {\n\t\treturn token;\n\t}\n\tpublic void setToken(String token) {\n\t\tthis.token = token;\n\t}\n\tpublic String getDateIncoming() {\n\t\treturn dateIncoming;\n\t}\n\tpublic void setDateIncoming(String dateIncoming) {\n\t\tthis.dateIncoming = dateIncoming;\n\t}\n\tpublic int getTimeExec() {\n\t\treturn timeExec;\n\t}\n\tpublic void setTimeExec(int timeExec) {\n\t\tthis.timeExec = timeExec;\n\t}\n\n}", "public class MessageThunderApp {\n\n private String token;\n private List<EntryPathData> listentryPathData;\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n\tpublic List<EntryPathData> getListentryPathData() {\n\t\treturn listentryPathData;\n\t}\n\n\tpublic void setListentryPathData(List<EntryPathData> listentryPathData) {\n\t\tthis.listentryPathData = listentryPathData;\n\t}\n}" ]
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.highway2urhell.CoreEngine; import com.highway2urhell.domain.EntryPathData; import com.highway2urhell.domain.MessageBreaker; import com.highway2urhell.domain.MessageMetrics; import com.highway2urhell.domain.MessageThunderApp; import com.sun.management.OperatingSystemMXBean; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.management.ManagementFactory; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.*;
package com.highway2urhell.service; public class ThunderExporterService { private static ThunderExporterService instance; private BlockingQueue<MessageBreaker> queueRemoteBreaker = new LinkedBlockingQueue<MessageBreaker>(10000); private BlockingQueue<MessageMetrics> queueRemotePerformance = new LinkedBlockingQueue<MessageMetrics>(10000); private final static int MSG_SIZE = 50; private ThunderExporterService() { ScheduledExecutorService schExService = Executors.newScheduledThreadPool(1); schExService.scheduleAtFixedRate(new Runnable() { public void run() { System.out.println("Drain the queue Remote"); List<MessageBreaker> listBreaker = new ArrayList<MessageBreaker>(); int result = queueRemoteBreaker.drainTo(listBreaker, MSG_SIZE); System.out.println("Drain Remote size " + result); if (result > 0) { System.out.println("Send the Data "); sendDataHTTPOldSchool("/addBreaker", listBreaker); }
if (CoreEngine.getInstance().getConfig().getPerformance()) {
0
DSH105/SparkTrail
src/main/java/com/dsh105/sparktrail/util/fanciful/FancyMessage.java
[ "public class ReflectionUtil {\n\n public static String NMS_PATH = getNMSPackageName();\n public static String CBC_PATH = getCBCPackageName();\n\n public static String getServerVersion() {\n return Bukkit.getServer().getClass().getPackage().getName().replace(\".\", \",\").split(\",\")[3];\n }\n\n public static String getNMSPackageName() {\n return \"net.minecraft.server.\" + getServerVersion();\n }\n\n public static String getCBCPackageName() {\n return \"org.bukkit.craftbukkit.\" + getServerVersion();\n }\n\n /**\n * Class stuff\n */\n\n public static Class getClass(String name) {\n try {\n return Class.forName(name);\n } catch (ClassNotFoundException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Could not find class: \" + name + \"!\");\n return null;\n }\n }\n\n public static Class getNMSClass(String className) {\n return getClass(NMS_PATH + \".\" + className);\n }\n\n public static Class getCBCClass(String classPath) {\n return getClass(CBC_PATH + \".\" + classPath);\n }\n\n /**\n * Field stuff\n */\n\n public static Field getField(Class<?> clazz, String fieldName) {\n try {\n Field field = clazz.getDeclaredField(fieldName);\n\n if (!field.isAccessible()) {\n field.setAccessible(true);\n }\n\n return field;\n } catch (NoSuchFieldException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"No such field: \" + fieldName + \"!\");\n return null;\n }\n }\n\n public static <T> T getField(Class<?> clazz, String fieldName, Object instance) {\n try {\n return (T) getField(clazz, fieldName).get(instance);\n } catch (IllegalAccessException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to access field: \" + fieldName + \"!\");\n return null;\n }\n }\n\n public static void setField(Class<?> clazz, String fieldName, Object instance, Object value) {\n try {\n getField(clazz, fieldName).set(instance, value);\n } catch (IllegalAccessException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Could not set new field value for: \" + fieldName);\n }\n }\n\n public static <T> T getField(Field field, Object instance) {\n try {\n return (T) field.get(instance);\n } catch (IllegalAccessException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to retrieve field: \" + field.getName());\n return null;\n }\n }\n\n /**\n * Method stuff\n */\n\n public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) {\n try {\n return clazz.getDeclaredMethod(methodName, params);\n } catch (NoSuchMethodException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"No such method: \" + methodName + \"!\");\n return null;\n }\n }\n\n public static <T> T invokeMethod(Method method, Object instance, Object... args) {\n try {\n return (T) method.invoke(instance, args);\n } catch (IllegalAccessException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to access method: \" + method.getName() + \"!\");\n return null;\n } catch (InvocationTargetException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to invoke method: \" + method.getName() + \"!\");\n return null;\n }\n }\n}", "public class WrapperPacketChat extends Packet {\n\n public WrapperPacketChat() {\n super(PacketFactory.PacketType.CHAT);\n }\n\n public void setMessage(String chatComponent) {\n if (!SparkTrailPlugin.isUsingNetty) {\n if (!(chatComponent instanceof String)) {\n throw new IllegalArgumentException(\"Chat component for 1.6 chat packet must be a String!\");\n }\n }\n this.write(\"a\", new SafeMethod(ReflectionUtil.getNMSClass(\"ChatSerializer\"), \"a\", String.class).invoke(null, chatComponent));\n }\n\n public String getMessage() {\n if (!SparkTrailPlugin.isUsingNetty) {\n return (String) this.read(\"message\");\n }\n return (String) new SafeMethod(ReflectionUtil.getNMSClass(\"ChatSerializer\"), \"a\", ReflectionUtil.getNMSClass(\"IChatBaseComponent\")).invoke(null, this.read(\"a\"));\n }\n}", "public class SafeConstructor<T> {\n\n private Constructor<T> constructor;\n private Class[] params;\n\n public SafeConstructor(Constructor constructor) {\n setConstructor(constructor);\n }\n\n public SafeConstructor(Class<?> coreClass, Class<?>... params) {\n try {\n Constructor constructor = coreClass.getConstructor(params);\n setConstructor(constructor);\n } catch (NoSuchMethodException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"No such constructor!\");\n }\n }\n\n protected void setConstructor(Constructor constructor) {\n if (constructor == null) {\n throw new UnsupportedOperationException(\"Cannot create a new constructor!\");\n }\n this.constructor = constructor;\n this.params = constructor.getParameterTypes();\n }\n\n public Constructor getConstructor() {\n return this.constructor;\n }\n\n public T newInstance(Object... params) {\n try {\n return (T) this.getConstructor().newInstance(params);\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (InvocationTargetException e) {\n throw new RuntimeException(e);\n }\n }\n}", "public class SafeField<T> implements FieldAccessor<T> {\n\n private Field field;\n private boolean isStatic;\n\n public SafeField(Field field) {\n setField(field);\n }\n\n public SafeField(Class<?> coreClass, String fieldName) {\n try {\n Field field = coreClass.getDeclaredField(fieldName);\n setField(field);\n } catch (NoSuchFieldException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to find a matching field with name: \" + fieldName);\n e.printStackTrace();\n }\n }\n\n protected void setField(Field field) {\n if (!field.isAccessible()) {\n try {\n field.setAccessible(true);\n } catch (Exception e) {\n e.printStackTrace();\n field = null;\n }\n }\n this.field = field;\n this.isStatic = Modifier.isStatic(field.getModifiers());\n }\n\n @Override\n public Field getField() {\n return this.field;\n }\n\n @Override\n public boolean set(Object instance, T value) {\n if (!isStatic && instance == null) {\n throw new UnsupportedOperationException(\"Non-static fields require a valid instance passed in!\");\n }\n\n try {\n this.field.set(instance, value);\n return true;\n } catch (IllegalAccessException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to access field: \" + toString());\n e.printStackTrace();\n }\n return false;\n }\n\n @Override\n public T get(Object instance) {\n if (!isStatic && instance == null) {\n throw new UnsupportedOperationException(\"Non-static fields require a valid instance passed in!\");\n }\n try {\n return (T) this.field.get(instance);\n } catch (IllegalAccessException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to access field: \" + toString());\n e.printStackTrace();\n }\n return null;\n }\n\n @Override\n public T transfer(Object from, Object to) {\n if (this.field == null) {\n return null;\n }\n T old = get(to);\n set(to, get(from));\n return old;\n }\n\n public String getName() {\n return this.field.getName();\n }\n\n @Override\n public String toString() {\n StringBuilder string = new StringBuilder(75);\n int mod = this.field.getModifiers();\n if (Modifier.isPublic(mod)) {\n string.append(\"public \");\n } else if (Modifier.isPrivate(mod)) {\n string.append(\"private \");\n } else if (Modifier.isProtected(mod)) {\n string.append(\"protected \");\n }\n\n if (Modifier.isStatic(mod)) {\n string.append(\"static \");\n }\n\n string.append(this.field.getName());\n\n return string.toString();\n }\n\n @Override\n public boolean isPublic() {\n return Modifier.isPublic(field.getModifiers());\n }\n\n @Override\n public boolean isReadOnly() {\n return Modifier.isFinal(field.getModifiers());\n }\n\n @Override\n public void setReadOnly(Object target, boolean value) {\n if (value)\n set(target, \"modifiers\", field.getModifiers() | Modifier.FINAL);\n else\n set(target, \"modifiers\", field.getModifiers() & ~Modifier.FINAL);\n }\n\n public static <T> T get(Class<?> clazz, String fieldname) {\n return new SafeField<T>(clazz, fieldname).get(null);\n }\n\n public static <T> T get(Object instance, String fieldName) {\n return new SafeField<T>(instance.getClass(), fieldName).get(instance);\n }\n\n public static <T> void set(Object instance, String fieldName, T value) {\n new SafeField<T>(instance.getClass(), fieldName).set(instance, value);\n }\n\n public static <T> void setStatic(Class<?> clazz, String fieldname, T value) {\n new SafeField<T>(clazz, fieldname).set(null, value);\n }\n}", "public class SafeMethod<T> implements MethodAccessor<T> {\n\n private Method method;\n private Class[] params;\n private boolean isStatic;\n\n public SafeMethod() {\n }\n\n public SafeMethod(Method method) {\n setMethod(method);\n }\n\n public SafeMethod(Class<?> coreClass, String methodname, Class<?>... params) {\n try {\n Method method = coreClass.getDeclaredMethod(methodname, params);\n setMethod(method);\n } catch (NoSuchMethodException e) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Failed to find a matching method with name: \" + methodname);\n e.printStackTrace();\n }\n }\n\n protected void setMethod(Method method) {\n if (method == null) {\n ConsoleLogger.log(Logger.LogLevel.WARNING, \"Cannot create a SafeMethod with a null method!\");\n }\n if (!method.isAccessible()) {\n method.setAccessible(true);\n }\n this.method = method;\n this.params = method.getParameterTypes();\n this.isStatic = Modifier.isStatic(method.getModifiers());\n }\n\n @Override\n public T invoke(Object instance, Object... args) {\n if (this.method != null) {\n\n //check if the instance is right\n if (instance == null && !isStatic) {\n throw new UnsupportedOperationException(\"Non-static methods require a valid instance passed in!\");\n }\n\n //check if param lenght is right\n if (args.length != this.params.length) {\n throw new UnsupportedOperationException(\"Not enough arguments!\");\n }\n\n //if we got trough the above stuff then eventually invoke the method\n try {\n return (T) this.method.invoke(instance, args);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n e.printStackTrace();\n }\n }\n return null;\n }\n}" ]
import com.dsh105.sparktrail.util.ReflectionUtil; import com.dsh105.sparktrail.util.protocol.wrapper.WrapperPacketChat; import com.dsh105.sparktrail.util.reflection.SafeConstructor; import com.dsh105.sparktrail.util.reflection.SafeField; import com.dsh105.sparktrail.util.reflection.SafeMethod; import org.bukkit.Achievement; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.Statistic; import org.bukkit.Statistic.Type; import org.bukkit.craftbukkit.libs.com.google.gson.stream.JsonWriter; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.io.StringWriter; import java.util.ArrayList; import java.util.List;
/* * 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/>. */ /* * This file is part of HoloAPI. * * HoloAPI 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. * * HoloAPI 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 HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.sparktrail.util.fanciful; public class FancyMessage { private final List<MessagePart> messageParts; private String jsonString; private boolean dirty; public FancyMessage(final String firstPartText) { messageParts = new ArrayList<MessagePart>(); messageParts.add(new MessagePart(firstPartText)); jsonString = null; dirty = false; } public FancyMessage color(final ChatColor color) { if (!color.isColor()) { throw new IllegalArgumentException(color.name() + " is not a color"); } latest().color = color; dirty = true; return this; } public FancyMessage style(final ChatColor... styles) { for (final ChatColor style : styles) { if (!style.isFormat()) { throw new IllegalArgumentException(style.name() + " is not a style"); } } latest().styles = styles; dirty = true; return this; } public FancyMessage file(final String path) { onClick("open_file", path); return this; } public FancyMessage link(final String url) { onClick("open_url", url); return this; } public FancyMessage suggest(final String command) { onClick("suggest_command", command); return this; } public FancyMessage command(final String command) { onClick("run_command", command); return this; } public FancyMessage achievementTooltip(final String name) { onHover("show_achievement", "achievement." + name); return this; } public FancyMessage achievementTooltip(final Achievement which) {
Object achievement = new SafeMethod(ReflectionUtil.getCBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which);
0
ingwarsw/arquillian-suite-extension
src/test/java/org/eu/ingwar/tools/arquillian/extension/suite/Deployments.java
[ "public class EarGenericBuilder {\n\n private static final String RUN_AT_ARQUILLIAN_PATH = \"/runs-at-arquillian.txt\";\n private static final String RUN_AT_ARQUILLIAN_CONTENT = \"at-arquillian\";\n private static final Logger LOG = Logger.getLogger(EarGenericBuilder.class.getName());\n\n /**\n * Private constructor.\n */\n private EarGenericBuilder() {\n }\n\n /**\n * Generates deployment for given application.\n *\n * @param type Module type to generate\n * @return EnterpriseArchive containing given module and all dependencies\n */\n public static EnterpriseArchive getModuleDeployment(ModuleType type) {\n return getModuleDeployment(type, type.generateModuleName());\n }\n\n /**\n * Generates deployment for given application.\n *\n * @param type Module type to generate\n * @param basename Base name of module to generate\n * @return EnterpriseArchive containing given module and all dependencies\n */\n public static EnterpriseArchive getModuleDeployment(ModuleType type, String basename) {\n return getModuleDeployment(type, basename, true);\n }\n\n /**\n * Generates deployment for given application.\n *\n * @param type Module type to generate\n * @param basename Base name of module to generate\n * @param doFiltering should do basic filtering\n * @return EnterpriseArchive containing given module and all dependencies\n */\n public static EnterpriseArchive getModuleDeployment(ModuleType type, String basename, boolean doFiltering) {\n String name = basename + \".\" + type.getExtension();\n String testJarName = basename + \"-tests.jar\";\n// LOG.debug(\"Creating Arquillian deployment for [\" + name + \"]\");\n try {\n EarDescriptorBuilder descriptorBuilder = new EarDescriptorBuilder(basename);\n MavenResolverSystem maven = Maven.resolver();\n //ConfigurableMavenResolverSystem maven = Maven.configureResolver().workOffline().withMavenCentralRepo(false);\n EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, basename + \"-full.ear\");\n PomEquippedResolveStage resolveStage = maven.loadPomFromFile(\"pom.xml\");\n\n // przejrzenie dependency oznaczonych jako provided w celu znalezienia EJB'ków\n MavenResolvedArtifact[] provided = resolveStage.importRuntimeDependencies().importDependencies(ScopeType.PROVIDED).resolve().using(new AcceptScopesStrategy(ScopeType.PROVIDED)).asResolvedArtifact();\n for (MavenResolvedArtifact mra : provided) {\n// System.out.println(\"Checking provided: \" + mra.getCoordinate().toCanonicalForm());\n if (isArtifactEjb(mra.getCoordinate())) {\n ear.addAsModule(mra.as(JavaArchive.class));\n // dodajemy jako moduł\n descriptorBuilder.addEjb(mra.asFile().getName());\n // przeglądamy dependency EJB'ka w celu pobrania także zależności z EJB'ka\n for (MavenArtifactInfo mai : mra.getDependencies()) {\n// LOG.debug(\"Resolved: \" + mai.getCoordinate().getGroupId() + \":\" + mai.getCoordinate().getArtifactId());\n // pomijamy wzajemne zależności do innych EJB'ków\n if (!isArtifactEjb(mai.getCoordinate())) {\n for (MavenResolvedArtifact reqMra : provided) {\n if (reqMra.getCoordinate().toCanonicalForm().equals(mai.getCoordinate().toCanonicalForm())) {\n // dodanie zależności do lib'ów\n ear.addAsLibrary(reqMra.asFile());\n break;\n }\n }\n }\n }\n }\n }\n MavenResolvedArtifact[] deps = resolveStage.importRuntimeAndTestDependencies().resolve().withTransitivity().asResolvedArtifact();\n\n for (MavenResolvedArtifact mra : deps) {\n MavenCoordinate mc = mra.getCoordinate();\n PackagingType packaging = mc.getPackaging();\n if (doFiltering && isFiltered(mc)) {\n continue;\n }\n LOG.log(Level.FINEST, \"Adding: {0}\", mc.toCanonicalForm());\n if (isArtifactEjb(mc)) {\n // dependency w postaci ejb'ków\n ear.addAsModule(mra.as(JavaArchive.class));\n descriptorBuilder.addEjb(mra.asFile().getName());\n } else if (packaging.equals(PackagingType.WAR)) {\n // dependency w postaci war'ów\n ear.addAsModule(mra.as(WebArchive.class));\n descriptorBuilder.addWeb(mra.asFile().getName());\n } else {\n // resztę dodajemy jako lib\n ear.addAsLibrary(mra.asFile());\n }\n }\n // utworzenie głównego archiwum\n// Archive<?> module = ShrinkWrap.create(MavenImporter.class, name)\n// .loadPomFromFile(\"pom.xml\")\n// .as(type.getType());\n\n Archive<?> module = ShrinkWrap.create(ExplodedImporter.class, name)\n .importDirectory(type.getExplodedDir(basename))\n .as(type.getType());\n\n JavaArchive testJar = ShrinkWrap.create(ExplodedImporter.class, testJarName)\n .importDirectory(\"target/test-classes\")\n .as(JavaArchive.class);\n\n module = module.merge(testJar, type.getMergePoint());\n// mergeReplace(ear, module, testJar);\n\n module.add(new StringAsset(RUN_AT_ARQUILLIAN_CONTENT), RUN_AT_ARQUILLIAN_PATH);\n LOG.log(Level.FINE, module.toString(true));\n\n addMainModule(ear, type, module, descriptorBuilder);\n \n // Workaround for arquillian bug\n if (!descriptorBuilder.containsWar()) {\n String testModuleName = ModuleType.WAR.generateModuleName() + \".war\";\n ear.addAsModule(ShrinkWrap.create(WebArchive.class, testModuleName));\n descriptorBuilder.addWeb(testModuleName);\n }\n\n ear.setApplicationXML(new StringAsset(descriptorBuilder.render()));\n ear.addManifest();\n LOG.log(Level.INFO, \"Created deployment [{0}]\", ear.getName());\n// System.out.println(ear.toString(true));\n// System.out.println(descriptorBuilder.render());\n return ear;\n } catch (IllegalArgumentException ex) {\n throw new IllegalStateException(\"Error in creating deployment [\" + ex + \"]\", ex);\n } catch (InvalidConfigurationFileException ex) {\n throw new IllegalStateException(\"Error in creating deployment [\" + ex + \"]\", ex);\n } catch (ArchiveImportException ex) {\n throw new IllegalStateException(\"Error in creating deployment [\" + ex + \"]\", ex);\n }\n }\n\n /**\n * Sprawdza czy dany artefakt jest ejb (ale nie jest ejb-clientem). Artefakt w formie MavenCoordinate.\n *\n * FIXME: Z powodu bledu shrinkwrapa szukamy tak na lewo po nazwie.\n *\n * @param artifactCoordinate MavenCoordinate artefaktu do sprawdzenia\n * @return true jesli jest projektem ejb\n */\n private static boolean isArtifactEjb(MavenCoordinate artifactCoordinate) {\n if (\"client\".equals(artifactCoordinate.getClassifier())) {\n return false;\n }\n if (!artifactCoordinate.getGroupId().startsWith(\"pl.gov.coi\")) {\n return false;\n }\n if (!artifactCoordinate.getArtifactId().toLowerCase().contains(\"ejb\")) {\n return false;\n }\n return true;\n }\n\n /**\n * Dodaje główny moduł do archiwum EAR.\n *\n * @param ear archiwum EAR\n * @param type typ głównego modułu\n * @param module główny moduł\n * @param descriptorBuilder deskreptor builder dla EAR'a\n */\n private static void addMainModule(EnterpriseArchive ear, ModuleType type, Archive<?> module, EarDescriptorBuilder descriptorBuilder) {\n if (type.isModule()) {\n ear.addAsModule(module);\n if (type == ModuleType.EJB) {\n descriptorBuilder.addEjb(module.getName());\n }\n if (type == ModuleType.WAR) {\n descriptorBuilder.addWeb(module.getName());\n }\n } else {\n ear.addAsLibrary(module);\n }\n }\n\n// /**\n// * Merges additional (usualy test) archive into main module.\n// *\n// * @param module main module\n// * @param additional module\n// */\n// private static void mergeReplace(EnterpriseArchive ear, Archive<?> module, Archive<?> additional) {\n// for (Map.Entry<ArchivePath, Node> entry : additional.getContent().entrySet()) {\n// ArchivePath ap = new BasicPath(entry.getKey().get());\n// if (module.contains(ap) && module.get(ap).getAsset() != null) {\n// module.delete(ap);\n// }\n// Asset asset = entry.getValue().getAsset();\n// if (asset == null) {\n// module.addAsDirectory(ap);\n// } else if (\"/META-INF/jboss-deployment-structure.xml\".equals(ap.get())) {\n// ear.add(asset, ap);\n// } else {\n// module.add(asset, ap);\n// }\n// }\n// }\n\n /**\n * Check if artefact should be filtered (omitted from packaging).\n * <p>\n * By default all artefact witch groups start with org.jboss.(shrinkwrap|arqrquillian) are filtered.\n * </p>\n * @param artifactCoordinate Artifact coordinate to check\n * @return true if artifact should be filtered\n */\n private static boolean isFiltered(MavenCoordinate artifactCoordinate) {\n if (artifactCoordinate.getGroupId().startsWith(\"org.jboss.shrinkwrap\")) {\n return true;\n }\n if (artifactCoordinate.getGroupId().startsWith(\"org.jboss.arquillian\")) {\n return true;\n }\n if (artifactCoordinate.getGroupId().startsWith(\"org.jboss.as\")) {\n return true;\n }\n return false;\n }\n}", "public enum ModuleType {\n\n /**\n * WAR archive.\n */\n WAR(\"war\"),\n /**\n * EJB archive.\n */\n EJB(\"ejb\"),\n /**\n * JAR archive.\n */\n JAR(\"jar\");\n private String type;\n\n /**\n * Constructor.\n *\n * @param type module type\n */\n private ModuleType(String type) {\n this.type = type;\n }\n\n @Override\n public String toString() {\n return type;\n }\n\n /**\n * Tworzy enum ze stringa.\n *\n * @param packaging nazwa typu pakowania\n * @return typ modułu\n */\n public static ModuleType fromString(String packaging) {\n for (ModuleType moduleType : ModuleType.values()) {\n if (moduleType.type.equals(packaging)) {\n return moduleType;\n }\n }\n throw new IllegalArgumentException(\"Nieprawidłowa wartość dla enuma: \" + packaging);\n }\n\n /**\n * Pobiera typ archiwum.\n *\n * @return typ archiwum\n */\n public Class<? extends Archive<?>> getType() {\n switch (this) {\n case WAR:\n return WebArchive.class;\n case EJB:\n case JAR:\n return JavaArchive.class;\n default:\n throw new IllegalStateException(\"Illegal type for archive\");\n }\n }\n\n /**\n * Sprawdza czy jest modułem czy bibioteką.\n *\n * @return true jeżeli jest modułem\n */\n public boolean isModule() {\n return (this != JAR);\n }\n\n /**\n * Pobiera rozszerzenie dla danego modułu.\n *\n * @return rozszerzenie\n */\n public String getExtension() {\n switch (this) {\n case WAR:\n return \"war\";\n case EJB:\n case JAR:\n return \"jar\";\n default:\n throw new IllegalStateException(\"Illegal type for extension\");\n }\n }\n\n /**\n * Generates module name for given type.\n *\n * Adds random part to name.\n *\n * @return randomized module name\n */\n String generateModuleName() {\n String name;\n switch (this) {\n case WAR:\n name = \"war\";\n break;\n case EJB:\n name = \"ejb\";\n break;\n case JAR:\n name = \"jar\";\n break;\n default:\n throw new IllegalStateException(\"Illegal type for extension\");\n }\n Random random = new Random();\n name += \"_module_\" + random.nextInt(Integer.MAX_VALUE);\n return name;\n }\n\n String getMergePoint() {\n if (this.equals(WAR)) {\n return \"WEB-INF/classes\";\n }\n return \"\";\n }\n\n String getExplodedDir(String basename) {\n if (this.equals(WAR)) {\n return \"target/\" + basename;\n }\n return \"target/classes\";\n }\n}", "public interface AlphaGroup {\n \n}", "@RunWith(Arquillian.class)\npublic class Extension1Test extends Deployments {\n\n @Test\n @OperateOnDeployment(\"normal\")\n @Category(AlphaGroup.class)\n public void shouldInject(InjectedObject bm) {\n Assert.assertNotNull(bm);\n Assert.assertEquals(NormalInjectedObject.NAME, bm.getName());\n System.out.println(\"Test1\");\n }\n}", "public interface InjectedObject {\n String getName();\n}", "@RunWith(Arquillian.class)\npublic class ExtensionExtra1Test extends Deployments {\n\n @Test\n @OperateOnDeployment(\"extra\")\n public void shouldInject(InjectedObject bm) {\n Assert.assertNotNull(bm);\n Assert.assertEquals(ExtendedInjectedObject.NAME, bm.getName());\n System.out.println(\"extra Test1\");\n }\n}" ]
import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.eu.ingwar.tools.arquillian.extension.deployment.EarGenericBuilder; import org.eu.ingwar.tools.arquillian.extension.deployment.ModuleType; import org.eu.ingwar.tools.arquillian.extension.groups.AlphaGroup; import org.eu.ingwar.tools.arquillian.extension.suite.normal.Extension1Test; import org.eu.ingwar.tools.arquillian.extension.suite.inject.InjectedObject; import org.eu.ingwar.tools.arquillian.extension.suite.annotations.ArquillianSuiteDeployment; import org.eu.ingwar.tools.arquillian.extension.suite.extra.ExtensionExtra1Test; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.shrinkwrap.api.Archive;
package org.eu.ingwar.tools.arquillian.extension.suite; /* * #%L * Arquillian suite extension * %% * Copyright (C) 2013 Ingwar & co. * %% * 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. * #L% */ @ArquillianSuiteDeployment public class Deployments { @Deployment(name = "normal", order = 3) @TargetsContainer("app") public static Archive<?> generateDefaultDeployment() { return ShrinkWrap.create(WebArchive.class, "normal.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClass(Deployments.class) .addClass(InjectedObject.class) .addPackage(AlphaGroup.class.getPackage()) .addPackage(Extension1Test.class.getPackage()); } @Deployment(name = "extra", order = 4) @TargetsContainer("app") public static Archive<?> generateExtraDeployment() { Archive<?> ejb = ShrinkWrap.create(WebArchive.class, "extra_ejb.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClass(Deployments.class) .addClass(InjectedObject.class) .addPackage(AlphaGroup.class.getPackage()) .addPackage(ExtensionExtra1Test.class.getPackage()); return ejb; } @Deployment(name = "autogenerated", order = 2) @TargetsContainer("app") public static Archive<?> generateAutogeneratedDeployment() {
EnterpriseArchive ear = EarGenericBuilder.getModuleDeployment(ModuleType.EJB);
1
lacuna/bifurcan
src/io/lacuna/bifurcan/DurableEncodings.java
[ "public class BlockPrefix {\n\n public enum BlockType {\n // root (2 bits)\n PRIMITIVE,\n TABLE,\n DIFF, // continuation\n COLLECTION, // continuation\n\n // 3 bits preceded by COLLECTION\n HASH_MAP,\n SORTED_MAP,\n HASH_SET,\n SORTED_SET,\n LIST,\n COLLECTION_PLACEHOLDER_0,\n COLLECTION_PLACEHOLDER_1,\n EXTENDED, // continuation\n\n // 3 bits preceded by DIFF\n DIFF_HASH_MAP,\n DIFF_SORTED_MAP,\n DIFF_HASH_SET,\n DIFF_SORTED_SET,\n SLICE_LIST,\n CONCAT_LIST,\n DIFF_PLACEHOLDER_0,\n DEPENDENCY, // continuation\n\n // 3 bits preceded by COLLECTION and EXTENDED\n DIRECTED_GRAPH,\n DIRECTED_ACYCLIC_GRAPH,\n UNDIRECTED_GRAPH,\n EXTENDED_PLACEHOLDER_0,\n EXTENDED_PLACEHOLDER_1,\n EXTENDED_PLACEHOLDER_2,\n EXTENDED_PLACEHOLDER_3,\n EXTENDED_PLACEHOLDER_4,\n\n // 3 bits preceded by DIFF and DEPENDENCY\n REFERENCE,\n REBASE,\n DEPENDENCY_PLACEHOLDER_0,\n DEPENDENCY_PLACEHOLDER_1,\n DEPENDENCY_PLACEHOLDER_2,\n DEPENDENCY_PLACEHOLDER_3,\n DEPENDENCY_PLACEHOLDER_4,\n DEPENDENCY_PLACEHOLDER_5,\n\n }\n\n private static final BlockType[] TYPES = BlockType.values();\n\n public final long length;\n public final BlockType type;\n\n public BlockPrefix(long length, BlockType type) {\n this.length = length;\n this.type = type;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(length, type);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof BlockPrefix) {\n BlockPrefix p = (BlockPrefix) obj;\n return length == p.length\n && type == p.type;\n }\n return false;\n }\n\n @Override\n public String toString() {\n return \"[ length=\" + length + \", type=\" + type + \" ]\";\n }\n\n public static BlockPrefix decode(DurableInput in) {\n byte firstByte = in.readByte();\n int root = (firstByte & 0b11000000) >> 6;\n\n if (root < DIFF.ordinal()) {\n return new BlockPrefix(readPrefixedUVLQ(firstByte, 2, in), TYPES[root]);\n } else if (root == DIFF.ordinal()) {\n int diff = DIFF_HASH_MAP.ordinal() + ((firstByte & 0b00111000) >> 3);\n if (diff == DEPENDENCY.ordinal()) {\n int dependency = REFERENCE.ordinal() + (firstByte & 0b00000111);\n return new BlockPrefix(in.readUVLQ(), TYPES[dependency]);\n } else {\n return new BlockPrefix(readPrefixedUVLQ(firstByte, 5, in), TYPES[diff]);\n }\n } else {\n int collection = HASH_MAP.ordinal() + ((firstByte & 0b00111000) >> 3);\n if (collection == EXTENDED.ordinal()) {\n int extended = DIRECTED_GRAPH.ordinal() + (firstByte & 0b00000111);\n return new BlockPrefix(in.readUVLQ(), TYPES[extended]);\n } else {\n return new BlockPrefix(readPrefixedUVLQ(firstByte, 5, in), TYPES[collection]);\n }\n }\n }\n\n public void encode(DurableOutput out) {\n if (type.ordinal() >= REFERENCE.ordinal()) {\n out.writeByte(0b10111000 | (type.ordinal() - DIRECTED_GRAPH.ordinal()));\n out.writeUVLQ(length);\n } else if (type.ordinal() >= DIRECTED_GRAPH.ordinal()) {\n out.writeByte(0b11111000 | (type.ordinal() - DIRECTED_GRAPH.ordinal()));\n out.writeUVLQ(length);\n } else if (type.ordinal() >= DIFF_HASH_MAP.ordinal()) {\n writePrefixedUVLQ(0b10000 | (type.ordinal() - DIFF_HASH_MAP.ordinal()), 5, length, out);\n } else if (type.ordinal() >= HASH_MAP.ordinal()) {\n writePrefixedUVLQ(0b11000 | (type.ordinal() - HASH_MAP.ordinal()), 5, length, out);\n } else {\n writePrefixedUVLQ(type.ordinal(), 2, length, out);\n }\n }\n}", "public class DurableBuffer implements DurableOutput {\n\n private final LinearList<IBuffer> flushed = new LinearList<>();\n private long flushedBytes = 0;\n\n private IBuffer curr;\n private ByteBuffer bytes;\n\n private boolean isOpen = true;\n\n public DurableBuffer() {\n this.curr = allocate(bufferSize());\n this.bytes = curr.bytes();\n }\n\n public static void flushTo(DurableOutput out, Consumer<DurableBuffer> body) {\n DurableBuffer acc = new DurableBuffer();\n body.accept(acc);\n acc.flushTo(out);\n }\n\n public static void flushTo(DurableOutput out, BlockPrefix.BlockType type, Consumer<DurableBuffer> body) {\n DurableBuffer acc = new DurableBuffer();\n body.accept(acc);\n acc.flushTo(out, type);\n }\n\n /**\n * Writes the contents of the accumulator to {@code out}, and frees the associated buffers.\n */\n public void flushTo(DurableOutput out) {\n close();\n out.append(flushed);\n }\n\n public DurableInput toInput() {\n close();\n return DurableInput.from(flushed.stream().map(IBuffer::toInput).collect(Lists.linearCollector()));\n }\n\n public DurableInput toOffHeapInput() {\n assert (written() <= Integer.MAX_VALUE);\n DurableInput tmp = toInput();\n ByteBuffer b = Bytes.allocate((int) tmp.remaining());\n tmp.read(b);\n tmp.close();\n return new BufferInput((ByteBuffer) b.flip());\n }\n\n public IList<IBuffer> toBuffers() {\n close();\n return flushed;\n }\n\n public void flushTo(DurableOutput out, BlockPrefix.BlockType type) {\n close();\n BlockPrefix p = new BlockPrefix(written(), type);\n p.encode(out);\n flushTo(out);\n }\n\n public void free() {\n close();\n flushed.forEach(IBuffer::free);\n }\n\n @Override\n public void close() {\n if (isOpen) {\n isOpen = false;\n flushCurrentBuffer(true);\n bytes = null;\n }\n }\n\n @Override\n public void flush() {\n }\n\n @Override\n public long written() {\n return flushedBytes + (bytes != null ? bytes.position() : 0);\n }\n\n @Override\n public int write(ByteBuffer src) {\n int n = src.remaining();\n\n Bytes.transfer(src, bytes);\n while (src.remaining() > 0) {\n Bytes.transfer(src, ensureCapacity(src.remaining()));\n }\n\n return n;\n }\n\n @Override\n public void transferFrom(DurableInput in) {\n while (in.hasRemaining()) {\n in.read(this.bytes);\n ensureCapacity((int) Math.min(in.remaining(), Integer.MAX_VALUE));\n }\n }\n\n @Override\n public void append(Iterable<IBuffer> buffers) {\n Iterator<IBuffer> it = buffers.iterator();\n while (it.hasNext()) {\n IBuffer buf = it.next();\n if (!buf.isDurable()) {\n transferFrom(buf.toInput());\n buf.free();\n } else {\n flushCurrentBuffer(false);\n appendBuffer(buf);\n it.forEachRemaining(this::appendBuffer);\n }\n }\n }\n\n @Override\n public void writeByte(int v) {\n ensureCapacity(1).put((byte) v);\n }\n\n @Override\n public void writeShort(int v) {\n ensureCapacity(2).putShort((short) v);\n }\n\n @Override\n public void writeChar(int v) {\n ensureCapacity(2).putChar((char) v);\n }\n\n @Override\n public void writeInt(int v) {\n ensureCapacity(4).putInt(v);\n }\n\n @Override\n public void writeLong(long v) {\n ensureCapacity(8).putLong(v);\n }\n\n @Override\n public void writeFloat(float v) {\n ensureCapacity(4).putFloat(v);\n }\n\n @Override\n public void writeDouble(double v) {\n ensureCapacity(8).putDouble(v);\n }\n\n //\n\n private static final int MIN_BUFFER_SIZE = 4 << 10;\n public static final int MAX_BUFFER_SIZE = 16 << 20;\n\n private static final int BUFFER_SPILL_THRESHOLD = 4 << 20;\n private static final int MIN_DURABLE_BUFFER_SIZE = 1 << 20;\n\n\n private int bufferSize() {\n if (curr == null) {\n return MIN_BUFFER_SIZE;\n }\n\n int size = (int) Math.min(MAX_BUFFER_SIZE, written() / 4);\n if (written() > BUFFER_SPILL_THRESHOLD) {\n size = Math.max(MIN_DURABLE_BUFFER_SIZE, size);\n }\n return size;\n }\n\n private IBuffer allocate(int n) {\n return GenerationalAllocator.allocate(n);\n }\n\n private void appendBuffer(IBuffer b) {\n if (b.size() == 0) {\n b.free();\n } else {\n flushedBytes += b.size();\n flushed.addLast(b);\n }\n }\n\n private void flushCurrentBuffer(boolean isClosed) {\n boolean spill = written() >= BUFFER_SPILL_THRESHOLD || (flushed.size() > 0 && flushed.last().isDurable());\n\n if (spill && !flushed.first().isDurable()) {\n LinearList<IBuffer> prefix = new LinearList<>();\n while (flushed.size() > 0 && !flushed.first().isDurable()) {\n prefix.addLast(flushed.popFirst());\n }\n flushed.addFirst(GenerationalAllocator.spill(prefix));\n prefix.forEach(IBuffer::free);\n }\n\n IBuffer closed = curr.close(bytes.position(), spill);\n appendBuffer(closed);\n\n if (!isClosed) {\n curr = allocate(bufferSize());\n bytes = curr.bytes();\n } else {\n curr = null;\n bytes = null;\n }\n }\n\n private ByteBuffer ensureCapacity(int n) {\n if (n > bytes.remaining()) {\n flushCurrentBuffer(false);\n }\n return bytes;\n }\n}", "public class Iterators {\n\n private static final Object NONE = new Object();\n\n public static final Iterator EMPTY = new Iterator() {\n @Override\n public boolean hasNext() {\n return false;\n }\n\n @Override\n public Object next() {\n throw new NoSuchElementException();\n }\n };\n\n public static <V> Iterator<V> mergeSort(IList<Iterator<V>> iterators, Comparator<V> comparator) {\n\n if (iterators.size() == 1) {\n return iterators.first();\n }\n\n PriorityQueue<IEntry<V, Iterator<V>>> heap = new PriorityQueue<>(Comparator.comparing(IEntry::key, comparator));\n for (Iterator<V> it : iterators) {\n if (it.hasNext()) {\n heap.add(IEntry.of(it.next(), it));\n }\n }\n\n return from(\n () -> heap.size() > 0,\n () -> {\n IEntry<V, Iterator<V>> e = heap.poll();\n if (e.value().hasNext()) {\n heap.add(IEntry.of(e.value().next(), e.value()));\n }\n return e.key();\n }\n );\n }\n\n /**\n * A utility class for dynamically appending and prepending iterators to a collection, which itself can be iterated\n * over.\n */\n public static class IteratorStack<V> implements Iterator<V> {\n\n LinearList<Iterator<V>> iterators = new LinearList<>();\n\n public IteratorStack() {\n }\n\n public IteratorStack(Iterator<V>... its) {\n for (Iterator<V> it : its) {\n iterators.addFirst(it);\n }\n }\n\n private void primeIterator() {\n while (iterators.size() > 0 && !iterators.first().hasNext()) {\n iterators.removeFirst();\n }\n }\n\n @Override\n public boolean hasNext() {\n primeIterator();\n return iterators.size() > 0 && iterators.first().hasNext();\n }\n\n @Override\n public V next() {\n primeIterator();\n if (iterators.size() == 0) {\n throw new NoSuchElementException();\n }\n return iterators.first().next();\n }\n\n public void addFirst(Iterator<V> it) {\n iterators.addFirst(it);\n }\n\n public void addLast(Iterator<V> it) {\n iterators.addLast(it);\n }\n }\n\n public static <V> boolean equals(Iterator<V> a, Iterator<V> b, BiPredicate<V, V> equals) {\n while (a.hasNext()) {\n if (!equals.test(a.next(), b.next())) {\n return false;\n }\n }\n return true;\n }\n\n public static <V> Iterator<V> from(BooleanSupplier hasNext, Supplier<V> next) {\n return new Iterator<V>() {\n @Override\n public boolean hasNext() {\n return hasNext.getAsBoolean();\n }\n\n @Override\n public V next() {\n return next.get();\n }\n };\n }\n\n public static <V> Iterator<V> onExhaustion(Iterator<V> it, Runnable f) {\n return new Iterator<V>() {\n @Override\n public boolean hasNext() {\n return it.hasNext();\n }\n\n @Override\n public V next() {\n V result = it.next();\n if (!it.hasNext()) {\n f.run();\n }\n return result;\n }\n };\n }\n\n public static <V> Iterator<V> singleton(V val) {\n return new Iterator<V>() {\n boolean consumed = false;\n\n @Override\n public boolean hasNext() {\n return !consumed;\n }\n\n @Override\n public V next() {\n if (!consumed) {\n consumed = true;\n return val;\n } else {\n throw new NoSuchElementException();\n }\n }\n };\n }\n\n /**\n * @param it an iterator\n * @param f a predicate\n * @return an iterator which only yields values that satisfy the predicate\n */\n public static <V> Iterator<V> filter(Iterator<V> it, Predicate<V> f) {\n return new Iterator<V>() {\n\n private Object next = NONE;\n private boolean done = false;\n\n private void prime() {\n if (next == NONE && !done) {\n while (it.hasNext()) {\n next = it.next();\n if (f.test((V) next)) {\n return;\n }\n }\n done = true;\n }\n }\n\n @Override\n public boolean hasNext() {\n prime();\n return !done;\n }\n\n @Override\n public V next() {\n prime();\n if (next == NONE) {\n throw new NoSuchElementException();\n }\n\n V val = (V) next;\n next = NONE;\n return val;\n }\n };\n }\n\n /**\n * @param it an iterator\n * @param f a function which transforms values\n * @return an iterator which yields the transformed values\n */\n public static <U, V> Iterator<V> map(Iterator<U> it, Function<U, V> f) {\n return from(it::hasNext, () -> f.apply(it.next()));\n }\n\n /**\n * @param it an iterator\n * @param f a function which transforms values into iterators\n * @return an iterator which yields the concatenation of the iterators\n */\n public static <U, V> Iterator<V> flatMap(Iterator<U> it, Function<U, Iterator<V>> f) {\n return new Iterator<V>() {\n\n Iterator<V> curr = EMPTY;\n\n private void prime() {\n while (!curr.hasNext() && it.hasNext()) {\n curr = f.apply(it.next());\n }\n }\n\n @Override\n public boolean hasNext() {\n prime();\n return curr.hasNext();\n }\n\n @Override\n public V next() {\n prime();\n return curr.next();\n }\n };\n }\n\n /**\n * @param min an inclusive start of the range\n * @param max an exclusive end of the range\n * @param f a function which transforms a number in the range into a value\n * @return an iterator which yields the values returned by {@code f}\n */\n public static <V> Iterator<V> range(long min, long max, LongFunction<V> f) {\n return new Iterator<V>() {\n\n long i = min;\n\n @Override\n public boolean hasNext() {\n return i < max;\n }\n\n @Override\n public V next() {\n if (hasNext()) {\n return f.apply(i++);\n } else {\n throw new NoSuchElementException();\n }\n }\n };\n }\n\n /**\n * Represents a range implicitly starting at 0.\n *\n * @param max an exclusive end of the range.\n * @param f a function which transforms a number in the range into a value.\n * @return an iterator which yields the values returned by {@code f}\n */\n public static <V> Iterator<V> range(long max, LongFunction<V> f) {\n return range(0, max, f);\n }\n\n /**\n * @param iterators a list of iterators\n * @return a concatenation of all iterators, in the order provided\n */\n public static <V> Iterator<V> concat(Iterator<V>... iterators) {\n if (iterators.length == 1) {\n return iterators[0];\n } else {\n IteratorStack<V> stack = new IteratorStack<V>();\n for (Iterator<V> it : iterators) {\n stack.addLast(it);\n }\n return stack;\n }\n }\n\n /**\n * @param it an iterator\n * @param n the number of elements to drop, which may be larger than the number of values in the iterator\n * @return an iterator with the first {@code n} values dropped\n */\n public static <V> Iterator<V> drop(Iterator<V> it, long n) {\n for (long i = 0; i < n && it.hasNext(); i++) {\n it.next();\n }\n return it;\n }\n\n public static <V> Stream<V> toStream(Iterator<V> it) {\n return toStream(it, 0);\n }\n\n public static <V> Stream<V> toStream(Iterator<V> it, long estimatedSize) {\n return StreamSupport.stream(Spliterators.spliterator(it, estimatedSize, Spliterator.ORDERED), false);\n }\n\n public static <V> IDurableEncoding.SkippableIterator skippable(Iterator<V> it) {\n return new IDurableEncoding.SkippableIterator() {\n @Override\n public void skip() {\n it.next();\n }\n\n @Override\n public boolean hasNext() {\n return it.hasNext();\n }\n\n @Override\n public Object next() {\n return it.next();\n }\n };\n }\n\n public static class Indexed<T> {\n public final long index;\n public final T value;\n\n public Indexed(long index, T value) {\n this.index = index;\n this.value = value;\n }\n\n @Override\n public String toString() {\n return index + \": \" + value;\n }\n }\n\n public static <V> Iterator<Indexed<V>> indexed(Iterator<V> it) {\n return indexed(it, 0);\n }\n\n public static <V> Iterator<Indexed<V>> indexed(Iterator<V> it, long offset) {\n AtomicLong counter = new AtomicLong(offset);\n return map(it, v -> new Indexed<>(counter.getAndIncrement(), v));\n }\n\n}", "public static IDurableEncoding.SkippableIterator decodeBlock(\n DurableInput in,\n IDurableCollection.Root root,\n IDurableEncoding encoding\n) {\n BlockPrefix prefix = in.peekPrefix();\n if (prefix.type == BlockPrefix.BlockType.PRIMITIVE) {\n if (!(encoding instanceof IDurableEncoding.Primitive)) {\n throw new IllegalArgumentException(String.format(\n \"cannot decode primitive value using %s\",\n encoding.description()\n ));\n }\n\n return ((IDurableEncoding.Primitive) encoding).decode(\n in.duplicate().sliceBlock(BlockPrefix.BlockType.PRIMITIVE),\n root\n );\n } else {\n return Iterators.skippable(Iterators.singleton(decodeCollection(prefix, encoding, root, in.pool())));\n }\n}", "public static void encodeBlock(IList<Object> os, IDurableEncoding encoding, DurableOutput out) {\n if (os.size() == 1) {\n encodeSingleton(os.first(), encoding, out);\n } else if (encoding instanceof IDurableEncoding.Primitive) {\n encodePrimitives(os, (IDurableEncoding.Primitive) encoding, out);\n } else {\n throw new IllegalArgumentException(String.format(\"cannot encode primitive with %s\", encoding.description()));\n }\n}" ]
import io.lacuna.bifurcan.durable.BlockPrefix; import io.lacuna.bifurcan.durable.io.DurableBuffer; import io.lacuna.bifurcan.utils.Iterators; import java.util.Arrays; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import java.util.function.*; import static io.lacuna.bifurcan.durable.codecs.Core.decodeBlock; import static io.lacuna.bifurcan.durable.codecs.Core.encodeBlock;
Comparator<Object> comparator, Predicate<Object> isSingleton, Codec codec ) { return new IDurableEncoding.Primitive() { @Override public String description() { return description; } @Override public ToLongFunction<Object> hashFn() { return valueHash; } @Override public BiPredicate<Object, Object> equalityFn() { return valueEquality; } @Override public boolean isSingleton(Object o) { return isSingleton.test(o); } @Override public Comparator<Object> comparator() { return comparator; } @Override public int blockSize() { return blockSize; } @Override public void encode(IList<Object> primitives, DurableOutput out) { codec.encode(primitives, out); } @Override public SkippableIterator decode(DurableInput in, IDurableCollection.Root root) { return codec.decode(in, root); } }; } /** * Creates a tuple encoding, which allows us to decompose a compound object into individual values we know how to * encode. * <p> * To deconstruct the value, we use {@code preEncode}, which yields an array of individual values, which by convention * have the same order as {@code encodings}. * <p> * To reconstruct the value, we use {@code postDecode}, which takes an array of individual values an yields a * compound value. * <p> * The block size of this encoding is equal to the smallest block size of its sub-encodings. */ public static IDurableEncoding.Primitive tuple( Function<Object, Object[]> preEncode, Function<Object[], Object> postDecode, IDurableEncoding... encodings ) { return tuple( preEncode, postDecode, Arrays.stream(encodings).mapToInt(DurableEncodings::blockSize).min().getAsInt(), encodings ); } /** * Same as {@link DurableEncodings#tuple(Function, Function, IDurableEncoding...)}, except that {@code blockSize} can * be explicitly specified. */ public static IDurableEncoding.Primitive tuple( Function<Object, Object[]> preEncode, Function<Object[], Object> postDecode, int blockSize, IDurableEncoding... encodings ) { return new IDurableEncoding.Primitive() { @Override public String description() { StringBuilder sb = new StringBuilder("("); for (IDurableEncoding e : encodings) { sb.append(e.description()).append(", "); } sb.delete(sb.length() - 2, sb.length()).append(")"); return sb.toString(); } @Override public int blockSize() { return blockSize; } @Override public boolean isSingleton(Object o) { Object[] ary = preEncode.apply(o); for (int i = 0; i < ary.length; i++) { if (encodings[i].isSingleton(ary[i])) { return true; } } return false; } @Override public void encode(IList<Object> primitives, DurableOutput out) { int index = 0; IList<Object[]> arrays = primitives.stream().map(preEncode).collect(Lists.linearCollector()); for (IDurableEncoding e : encodings) { final int i = index++; DurableBuffer.flushTo( out, BlockPrefix.BlockType.PRIMITIVE,
inner -> encodeBlock(Lists.lazyMap(arrays, t -> t[i]), e, inner)
4
teivah/TIBreview
src/test/java/com/tibco/exchange/tibreview/processor/resourcerule/CProcessorRendezvousResourceReliableTest.java
[ "public class TIBResource {\n\tprivate String filePath;\n\tprivate String type;\n\t\n\tprivate static final String REQUEST_GET_TYPE = \"/jndi:namedResource/@type\";\n\t\n\tpublic TIBResource(String filePath) throws Exception {\n\t\tthis.filePath = filePath;\n\t\tthis.type = Util.xpathEval(filePath, Constants.RESOURCES_NAMESPACES, REQUEST_GET_TYPE);\n\t}\n\n\tpublic String getFilePath() {\n\t\treturn filePath;\n\t}\n\t\n\tpublic String getType() {\n\t\treturn type;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"TIBResource [filePath=\" + filePath + \", type=\" + type + \"]\";\n\t}\n}", "public class Context {\n\tprivate Map<String, String> xpathFunctions;\n\tprivate Map<String, String> disabledRules;\n\tprivate Map<String, String> properties;\n\tprivate String source;\n\tprivate String inputType;\n\tprivate LinkedList<String> filenames;\n\n\tpublic Context() {\n\t\tthis.xpathFunctions = new HashMap<>();\n\t\tthis.disabledRules = new HashMap<>();\n\t\tthis.properties = new HashMap<>();\n\t\tthis.filenames = new LinkedList<>();\n\t}\n\n\tpublic Map<String, String> getXpathFunctions() {\n\t\treturn xpathFunctions;\n\t}\n\n\tpublic void setXpathFunctions(Map<String, String> xpathFunctions) {\n\t\tthis.xpathFunctions = xpathFunctions;\n\t}\n\n\tpublic Map<String, String> getDisabledRules() {\n\t\treturn disabledRules;\n\t}\n\n\tpublic void setDisabledRules(Map<String, String> disabledRules) {\n\t\tthis.disabledRules = disabledRules;\n\t}\n\n\tpublic Map<String, String> getProperties() {\n\t\treturn properties;\n\t}\n\n\tpublic void setProperties(Map<String, String> properties) {\n\t\tthis.properties = properties;\n\t}\n\t\n\tpublic String getSource() {\n\t\treturn source;\n\t}\n\n\tpublic void setSource(String source) {\n\t\tthis.source = source;\n\t}\n\n\tpublic String getInputType() {\n\t\treturn inputType;\n\t}\n\n\tpublic void setInputType(String inputType) {\n\t\tthis.inputType = inputType;\n\t}\n\n\tpublic LinkedList<String> getFilenames() {\n\t\treturn filenames;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Context [xpathFunctions=\" + xpathFunctions + \", disabledRules=\" + disabledRules + \", properties=\"\n\t\t\t\t+ properties + \", source=\" + source + \", inputType=\" + inputType + \"]\";\n\t}\n}", "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"violation\", propOrder = {\n \"value\"\n})\npublic class Violation {\n\n @XmlValue\n protected String value;\n @XmlAttribute(name = \"line\", required = true)\n protected int line;\n @XmlAttribute(name = \"rule\", required = true)\n protected String rule;\n @XmlAttribute(name = \"ruleset\", required = true)\n protected String ruleset;\n @XmlAttribute(name = \"priority\", required = true)\n protected int priority;\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 line property.\n * \n */\n public int getLine() {\n return line;\n }\n\n /**\n * Sets the value of the line property.\n * \n */\n public void setLine(int value) {\n this.line = value;\n }\n\n /**\n * Gets the value of the rule property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getRule() {\n return rule;\n }\n\n /**\n * Sets the value of the rule property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setRule(String value) {\n this.rule = value;\n }\n\n /**\n * Gets the value of the ruleset property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getRuleset() {\n return ruleset;\n }\n\n /**\n * Sets the value of the ruleset property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setRuleset(String value) {\n this.ruleset = value;\n }\n\n /**\n * Gets the value of the priority property.\n * \n */\n public int getPriority() {\n return priority;\n }\n\n /**\n * Sets the value of the priority property.\n * \n */\n public void setPriority(int value) {\n this.priority = value;\n }\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Violation [value=\" + value + \", line=\" + line + \", rule=\" + rule + \", ruleset=\" + ruleset\n\t\t\t\t+ \", priority=\" + priority + \"]\";\n\t}\n}", "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"configuration\", propOrder = {\n \"property\"\n})\npublic class Configuration {\n\n @XmlElement(required = true)\n protected List<Property> property;\n @XmlAttribute(name = \"type\")\n protected String type;\n @XmlAttribute(name = \"filter\")\n protected String filter=\"\";\n\n /**\n * Gets the value of the property property.\n * \n * <p>\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a <CODE>set</CODE> method for the property property.\n * \n * <p>\n * For example, to add a new item, do as follows:\n * <pre>\n * getProperty().add(newItem);\n * </pre>\n * \n * \n * <p>\n * Objects of the following type(s) are allowed in the list\n * {@link Property }\n * \n * \n */\n public List<Property> getProperty() {\n if (property == null) {\n property = new ArrayList<Property>();\n }\n return this.property;\n }\n\n /**\n * Gets the value of the type property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getType() {\n return type;\n }\n\n /**\n * Sets the value of the type property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setType(String value) {\n this.type = value;\n }\n \n /**\n * Gets the value of the type property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getFilter() {\n return filter;\n }\n\n /**\n * Sets the value of the type property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setFilter(String filter) {\n this.filter = filter;\n }\n\n}", "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"resource\", propOrder = {\n \"rule\"\n})\npublic class Resource {\n\n @XmlElement(required = true)\n protected List<Resourcerule> rule;\n\n /**\n * Gets the value of the rule property.\n * \n * <p>\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a <CODE>set</CODE> method for the rule property.\n * \n * <p>\n * For example, to add a new item, do as follows:\n * <pre>\n * getRule().add(newItem);\n * </pre>\n * \n * \n * <p>\n * Objects of the following type(s) are allowed in the list\n * {@link Resourcerule }\n * \n * \n */\n public List<Resourcerule> getRule() {\n if (rule == null) {\n rule = new ArrayList<Resourcerule>();\n }\n return this.rule;\n }\n\n}", "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"tibrules\", propOrder = {\n \"process\",\n \"resource\",\n \"xpathfunctions\"\n})\npublic class Tibrules {\n\n protected Process process;\n protected Resource resource;\n protected Xpathfunctions xpathfunctions;\n\n /**\n * Gets the value of the process property.\n * \n * @return\n * possible object is\n * {@link Process }\n * \n */\n public Process getProcess() {\n return process;\n }\n\n /**\n * Sets the value of the process property.\n * \n * @param value\n * allowed object is\n * {@link Process }\n * \n */\n public void setProcess(Process value) {\n this.process = value;\n }\n\n /**\n * Gets the value of the resource property.\n * \n * @return\n * possible object is\n * {@link Resource }\n * \n */\n public Resource getResource() {\n return resource;\n }\n\n /**\n * Sets the value of the resource property.\n * \n * @param value\n * allowed object is\n * {@link Resource }\n * \n */\n public void setResource(Resource value) {\n this.resource = value;\n }\n\n /**\n * Gets the value of the xpathfunctions property.\n * \n * @return\n * possible object is\n * {@link Xpathfunctions }\n * \n */\n public Xpathfunctions getXpathfunctions() {\n return xpathfunctions;\n }\n\n /**\n * Sets the value of the xpathfunctions property.\n * \n * @param value\n * allowed object is\n * {@link Xpathfunctions }\n * \n */\n public void setXpathfunctions(Xpathfunctions value) {\n this.xpathfunctions = value;\n }\n\n}", "public class RulesParser {\n\tprivate static RulesParser instance = null;\n\tprivate static final String SCHEMA_FILE = \"schemas/tibrules.xsd\";\n\t\n\tprivate RulesParser() {\n\t\t\n\t}\n\t\n\tpublic static RulesParser getInstance() {\n\t\tif(instance == null) {\n\t\t\tinstance = new RulesParser();\n\t\t}\n\t\t\n\t\treturn instance;\n\t}\n\n\tpublic Tibrules parseFile(String file) throws ParsingException {\n\t\tFile f = new File(file);\n\n\t\tif (!f.exists()) {\n\t\t\tthrow new IllegalArgumentException(\"File \" + file + \" does not exist\");\n\t\t}\n\n\t\tFileInputStream is = null;\n\t\ttry {\n\t\t\tis = new FileInputStream(f);\n\t\t\tSource source = new StreamSource(is);\n\t\t\t\n\t\t\tSchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);\n\t\t\t\n\t\t\tSchema schema = sf.newSchema(getClass().getClassLoader().getResource(SCHEMA_FILE));\n\t\t\tJAXBContext jc = JAXBContext.newInstance(\"com.tibco.exchange.tibreview.model.rules\");\n\t\t\t\n\t\t\tUnmarshaller unmarshaller = jc.createUnmarshaller();\n\t\t\tunmarshaller.setSchema(schema);\n\n\t\t\tJAXBElement<Tibrules> root = unmarshaller.unmarshal(source, Tibrules.class);\n\t\t\t\n\t\t\treturn root.getValue();\n\t\t} catch (Exception e) {\n\t\t\tthrow new ParsingException(\"Unable to parse file \" + file, e);\n\t\t}\n\t}\n}" ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import org.apache.log4j.Logger; import org.junit.Test; import com.tibco.exchange.tibreview.common.TIBResource; import com.tibco.exchange.tibreview.engine.Context; import com.tibco.exchange.tibreview.model.pmd.Violation; import com.tibco.exchange.tibreview.model.rules.Configuration; import com.tibco.exchange.tibreview.model.rules.Resource; import com.tibco.exchange.tibreview.model.rules.Tibrules; import com.tibco.exchange.tibreview.parser.RulesParser;
package com.tibco.exchange.tibreview.processor.resourcerule; public class CProcessorRendezvousResourceReliableTest { private static final Logger LOGGER = Logger.getLogger(CProcessorRendezvousResourceReliableTest.class); @Test public void testCProcessorRendezvousResourceReliableTest() { TIBResource fileresource; try { fileresource = new TIBResource("src/test/resources/FileResources/RendezvousResourceReliable.rvResource"); fileresource.toString(); LOGGER.info(fileresource.toString()); assertTrue(fileresource.toString().equals("TIBResource [filePath=src/test/resources/FileResources/RendezvousResourceReliable.rvResource, type=rvsharedresource:RVResource]")); Tibrules tibrules= RulesParser.getInstance().parseFile("src/test/resources/FileResources/xml/RendezvousResourceReliable.xml"); Resource resource = tibrules.getResource(); LOGGER.info(resource.getRule().size()); assertEquals(resource.getRule().size(),1); ConfigurationProcessor a = new ConfigurationProcessor(); Configuration Configuracion = resource.getRule().get(0).getConfiguration();
List<Violation> b = a.process(new Context(), fileresource, resource.getRule().get(0), Configuracion);
1
Daskiworks/ghwatch
app/src/main/java/com/daskiworks/ghwatch/WatchedRepositoriesActivity.java
[ "public class PreferencesUtils {\n\n private static final String TAG = PreferencesUtils.class.getSimpleName();\n\n /*\n * Names of user edited preferences.\n */\n public static final String PREF_SERVER_CHECK_PERIOD = \"pref_serverCheckPeriod\";\n public static final String PREF_SERVER_CHECK_WIFI_ONLY = \"pref_serverCheckWifiOnly\";\n public static final String PREF_SERVER_CHECK_FULL = \"pref_serverCheckFull\";\n public static final String PREF_SERVER_DETAIL_LOADING = \"pref_serverDetailLoading\";\n public static final String PREF_SERVER_LABELS_LOADING = \"pref_serverLabelsLoading\";\n public static final String PREF_NOTIFY = \"pref_notify\";\n public static final String PREF_NOTIFY_VIBRATE = \"pref_notifyVibrate\";\n public static final String PREF_NOTIFY_SOUND = \"pref_notifySound\";\n public static final String PREF_NOTIFY_FILTER = \"pref_notifyFilter\";\n /**\n * Preference used to store night mode setting of the app, some of AppCompatDelegate.MODE_NIGHT_xx constants.\n */\n public static final String PREF_APP_NIGHT_MODE = \"pref_appNightMode\";\n\n public static final String PREF_NOTIFY_FILTER_INHERITED = \"0\";\n public static final String PREF_NOTIFY_FILTER_ALL = \"1\";\n public static final String PREF_NOTIFY_FILTER_PARTICIPATING = \"2\";\n public static final String PREF_NOTIFY_FILTER_NOTHING = \"3\";\n\n public static final String PREF_REPO_VISIBILITY = \"pref_repoVisibility\";\n public static final String PREF_REPO_VISIBILITY_INHERITED = \"0\";\n public static final String PREF_REPO_VISIBILITY_VISIBLE = \"1\";\n public static final String PREF_REPO_VISIBILITY_INVISIBLE = \"2\";\n\n public static final String PREF_MARK_READ_ON_SHOW = \"pref_markReadOnShow\";\n public static final String PREF_MARK_READ_ON_SHOW_ASK = \"ask\";\n public static final String PREF_MARK_READ_ON_SHOW_YES = \"yes\";\n public static final String PREF_MARK_READ_ON_SHOW_NO = \"no\";\n\n /*\n * Names of internal preferences\n */\n public static final String INT_SERVERINFO_APILIMIT = \"pref_serverInfo_APILimit\";\n public static final String INT_SERVERINFO_APILIMITREMAINING = \"pref_serverInfo_APILimitRemaining\";\n public static final String INT_SERVERINFO_APILIMITRESETTIMESTAMP = \"pref_serverInfo_APILimitResetTimestamp\";\n public static final String INT_SERVERINFO_LASTREQUESTDURATION = \"pref_serverInfo_lastRequestDuration\";\n public static final String INT_SERVERINFO_LASTUNREADNOTIFBACKREQUESTTIMESTAMP = \"pref_serverInfo_lastUnredNotifBackRequestTimestamp\";\n\n public static final String PREF_LOG_GITHUB_API_CALL_ERROR_TO_FILE = \"pref_logGithubAPiCallErrorToFile\";\n\n /* Set to true if at least one widget for unread notifications exists */\n public static final String PREF_WIDGET_UNREAD_EXISTS = \"pref_widget_unread_exists\";\n public static final String PREF_WIDGET_UNREAD_HIGHLIGHT = \"pref_widget_unread_highlight\";\n\n public static int setAppNightMode(Context context) {\n int m = Integer.parseInt(PreferencesUtils.getString(context, PREF_APP_NIGHT_MODE, AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM + \"\"));\n AppCompatDelegate.setDefaultNightMode(m);\n return m;\n }\n\n /**\n * Get string preference.\n *\n * @param context to get preferences for\n * @param key of preference\n * @param defaultValue\n * @return preference value\n */\n public static String getString(Context context, String key, String defaultValue) {\n return PreferenceManager.getDefaultSharedPreferences(context).getString(key, defaultValue);\n }\n\n /**\n * Patch preferences after restored from cloud - remove preferences which shouldn't be restored on new device.\n *\n * @param context\n */\n public static void patchAfterRestore(Context context) {\n SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = wmbPreference.edit();\n editor.remove(PREF_WIDGET_UNREAD_EXISTS);\n editor.remove(PREF_WIDGET_UNREAD_HIGHLIGHT);\n editor.commit();\n }\n\n /**\n * Read new notifications server backend check over wifi only setting {@link #PREF_SERVER_CHECK_WIFI_ONLY}\n *\n * @param context to read preference over\n * @return true if check should be performed over wifi only\n */\n public static Boolean getServerCheckWifiOnly(Context context) {\n return getBoolean(context, PREF_SERVER_CHECK_WIFI_ONLY, false);\n }\n\n /**\n * Read Notification Filter setting for defined repository.\n *\n * @param context to read preference over\n * @param repositoryName to get preference for\n * @param inheritResolve if true then {@link #PREF_NOTIFY_FILTER_INHERITED} is not returned but resolved from master preference\n * @return some of {@link #PREF_NOTIFY_FILTER_ALL} {@link #PREF_NOTIFY_FILTER_PARTICIPATING}, {@link #PREF_NOTIFY_FILTER_NOTHING} or\n * {@link #PREF_NOTIFY_FILTER_INHERITED}\n */\n public static String getNotificationFilterForRepository(Context context, String repositoryName, boolean inheritResolve) {\n String rs = getString(context, getNotificationFilterRepositoryPrefName(repositoryName), PREF_NOTIFY_FILTER_INHERITED);\n if (inheritResolve && PREF_NOTIFY_FILTER_INHERITED.equals(rs)) {\n return getNotificationFilter(context);\n } else {\n return rs;\n }\n }\n\n /**\n * Read Repository Visibility setting for defined repository.\n *\n * @param context to read preference over\n * @param repositoryName to get preference for\n * @param inheritResolve if true then {@link #PREF_REPO_VISIBILITY_INHERITED} is not returned but resolved from master preference\n * @return some of {@link #PREF_REPO_VISIBILITY_INVISIBLE} {@link #PREF_REPO_VISIBILITY_VISIBLE} or\n * {@link #PREF_REPO_VISIBILITY_INHERITED}\n */\n public static String getRepoVisibilityForRepository(Context context, String repositoryName, boolean inheritResolve) {\n String rs = getString(context, getRepoVisibilityRepositoryPrefName(repositoryName), PREF_REPO_VISIBILITY_INHERITED);\n if (inheritResolve && PREF_REPO_VISIBILITY_INHERITED.equals(rs)) {\n return getRepoVisibility(context);\n } else {\n return rs;\n }\n }\n\n /**\n * Read Notification Filter master setting\n *\n * @param context to read preference over\n * @return some of {@link #PREF_NOTIFY_FILTER_ALL} {@link #PREF_NOTIFY_FILTER_PARTICIPATING}, {@link #PREF_NOTIFY_FILTER_NOTHING} or\n * {@link #PREF_NOTIFY_FILTER_INHERITED}\n */\n public static String getNotificationFilter(Context context) {\n return getString(context, PREF_NOTIFY_FILTER, PREF_NOTIFY_FILTER_ALL);\n }\n\n /**\n * Read Repository Visibility master setting\n *\n * @param context to read preference over\n * @return some of {@link #PREF_REPO_VISIBILITY_INHERITED} {@link #PREF_REPO_VISIBILITY_INVISIBLE} or\n * {@link #PREF_REPO_VISIBILITY_VISIBLE}\n */\n public static String getRepoVisibility(Context context) {\n return getString(context, PREF_REPO_VISIBILITY, PREF_REPO_VISIBILITY_VISIBLE);\n }\n\n /**\n * Store Notification Filter setting for defined repository.\n *\n * @param context used to write preference\n * @param repositoryName to write preference for\n * @param value of preference, some of {@link #PREF_NOTIFY_FILTER_ALL} {@link #PREF_NOTIFY_FILTER_PARTICIPATING}, {@link #PREF_NOTIFY_FILTER_NOTHING} or\n * {@link #PREF_NOTIFY_FILTER_INHERITED}\n */\n public static void setNotificationFilterForRepository(Context context, String repositoryName, String value) {\n storeString(context, getNotificationFilterRepositoryPrefName(repositoryName), value);\n (new BackupManager(context)).dataChanged();\n }\n\n protected static String getNotificationFilterRepositoryPrefName(String repositoryName) {\n return PREF_NOTIFY_FILTER + \"-\" + repositoryName;\n }\n\n /**\n * Store Repository Visibility setting for defined repository.\n *\n * @param context used to write preference\n * @param repositoryName to write preference for\n * @param value of preference, some of {@link #PREF_REPO_VISIBILITY_VISIBLE} {@link #PREF_REPO_VISIBILITY_INVISIBLE} or\n * {@link #PREF_REPO_VISIBILITY_INHERITED}\n */\n public static void setRepoVisibilityForRepository(Context context, String repositoryName, String value) {\n storeString(context, getRepoVisibilityRepositoryPrefName(repositoryName), value);\n (new BackupManager(context)).dataChanged();\n }\n\n protected static String getRepoVisibilityRepositoryPrefName(String repositoryName) {\n return PREF_REPO_VISIBILITY + \"-\" + repositoryName;\n }\n\n /**\n * Read 'Mark notification as read on show' setting\n *\n * @param context to read preference over\n * @return some of {@link #PREF_MARK_READ_ON_SHOW_ASK} {@link #PREF_MARK_READ_ON_SHOW_YES} or\n * {@link #PREF_MARK_READ_ON_SHOW_NO}\n */\n public static String getMarkReadOnShow(Context context) {\n return getString(context, PREF_MARK_READ_ON_SHOW, PREF_MARK_READ_ON_SHOW_ASK);\n }\n\n /**\n * Store 'Mark notification as read on show' setting\n *\n * @param context to read preference over\n * @param value some of {@link #PREF_MARK_READ_ON_SHOW_ASK} {@link #PREF_MARK_READ_ON_SHOW_YES} or\n * {@link #PREF_MARK_READ_ON_SHOW_NO}\n */\n public static void setMarkReadOnShow(Context context, String value) {\n ActivityTracker.sendEvent(context, ActivityTracker.CAT_PREF, \"PREF_MARK_READ_ON_SHOW\", value, 0L);\n storeString(context, PREF_MARK_READ_ON_SHOW, value);\n }\n\n /**\n * Get boolean preference.\n *\n * @param context\n * @param key\n * @param defaultValue\n * @return\n */\n public static boolean getBoolean(Context context, String key, boolean defaultValue) {\n return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(key, defaultValue);\n }\n\n /**\n * Get boolean preference. Same as {@link #getBoolean(Context, String, boolean)} with <code>false</code> as default.\n */\n public static boolean getBoolean(Context context, String key) {\n return getBoolean(context, key, false);\n }\n\n /**\n * Get long preference.\n *\n * @param context\n * @param key\n * @param defaultValue\n * @return\n */\n public static long getLong(Context context, String key, long defaultValue) {\n return PreferenceManager.getDefaultSharedPreferences(context).getLong(key, defaultValue);\n }\n\n /**\n * Store long preference.\n *\n * @param context\n * @param key\n * @param value\n */\n public static void storeLong(Context context, String key, long value) {\n SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = wmbPreference.edit();\n editor.putLong(key, value);\n editor.commit();\n }\n\n /**\n * Get int preference.\n *\n * @param context\n * @param key\n * @param defaultValue\n * @return\n */\n public static int getInt(Context context, String key, int defaultValue) {\n return PreferenceManager.getDefaultSharedPreferences(context).getInt(key, defaultValue);\n }\n\n /**\n * Store int preference.\n *\n * @param context\n * @param key\n * @param value\n */\n public static void storeInt(Context context, String key, int value) {\n SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = wmbPreference.edit();\n editor.putInt(key, value);\n editor.commit();\n }\n\n /**\n * Store boolean preference.\n *\n * @param context\n * @param key\n * @param value\n */\n public static void storeBoolean(Context context, String key, boolean value) {\n SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = wmbPreference.edit();\n editor.putBoolean(key, value);\n editor.commit();\n }\n\n /**\n * Store String preference.\n *\n * @param context\n * @param key of preference\n * @param value to store\n */\n public static void storeString(Context context, String key, String value) {\n SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = wmbPreference.edit();\n editor.putString(key, value);\n editor.commit();\n }\n\n /**\n * Remove preference.\n *\n * @param context\n * @param key of preference to remove\n */\n public static void remove(Context context, String key) {\n SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = wmbPreference.edit();\n editor.remove(key);\n editor.commit();\n }\n\n private static final String DTFN = \"dtfn\";\n\n /**\n * Store donation timestamp.\n *\n * @param context\n * @param timestamp to store\n */\n public static void storeDonationTimestamp(Context context, Long timestamp) {\n File file = context.getFileStreamPath(DTFN);\n Utils.writeToStore(TAG, context, file, timestamp);\n }\n\n /**\n * Read donation timestamp.\n *\n * @param context\n * @return donation timestamp or null if not donated yet.\n */\n public static Long readDonationTimestamp(Context context) {\n File file = context.getFileStreamPath(DTFN);\n return Utils.readFromStore(TAG, context, file);\n }\n\n}", "public class WatchedRepositoriesService {\n\n private static final String TAG = \"WatchedRepositoriesServ\";\n\n /**\n * URL to load notifications from.\n */\n private static final String URL_NOTIFICATIONS = GHConstants.URL_BASE + \"/user/subscriptions\";\n\n /**\n * Name of file where data are persisted.\n */\n private static final String fileName = \"WatchedRepositories.td\";\n\n /**\n * Reload from server is forced automatically if data in persistent store are older than this timeout [millis]\n */\n private static final long FORCE_VIEW_RELOAD_AFTER = 12 * Utils.MILLIS_HOUR;\n\n private Context context;\n\n private File persistFile;\n\n private AuthenticationManager authenticationManager;\n\n /**\n * Create service.\n * \n * @param context this service runs in\n */\n public WatchedRepositoriesService(Context context) {\n this.context = context;\n persistFile = context.getFileStreamPath(fileName);\n this.authenticationManager = AuthenticationManager.getInstance();\n }\n\n /**\n * Get watched repositories for view.\n * \n * @param reloadStrategy if data should be reloaded from server\n * @return view data\n */\n public WatchedRepositoriesViewData getWatchedRepositoriesForView(ViewDataReloadStrategy reloadStrategy) {\n\n WatchedRepositoriesViewData nswd = new WatchedRepositoriesViewData();\n WatchedRepositories ns = null;\n synchronized (TAG) {\n WatchedRepositories oldNs = Utils.readFromStore(TAG, context, persistFile);\n\n // user from store if possible, apply timeout of data from store\n if (reloadStrategy == ViewDataReloadStrategy.IF_TIMED_OUT) {\n ns = oldNs;\n if (ns != null && ns.getLastFullUpdateTimestamp() < (System.currentTimeMillis() - FORCE_VIEW_RELOAD_AFTER))\n ns = null;\n } else if (reloadStrategy == ViewDataReloadStrategy.NEVER) {\n ns = oldNs;\n }\n\n // read from server\n try {\n if (ns == null && reloadStrategy != ViewDataReloadStrategy.NEVER) {\n ns = readFromServer(URL_NOTIFICATIONS);\n if (ns != null) {\n Utils.writeToStore(TAG, context, persistFile, ns);\n }\n }\n } catch (InvalidObjectException e) {\n nswd.loadingStatus = LoadingStatus.DATA_ERROR;\n Log.w(TAG, \"Watched Repositories loading failed due to data format problem: \" + e.getMessage(), e);\n } catch (NoRouteToHostException e) {\n nswd.loadingStatus = LoadingStatus.CONN_UNAVAILABLE;\n Log.d(TAG, \"Watched Repositories loading failed due to connection not available.\");\n } catch (AuthenticationException e) {\n nswd.loadingStatus = LoadingStatus.AUTH_ERROR;\n Log.d(TAG, \"Watched Repositories loading failed due to authentication problem: \" + e.getMessage());\n } catch (IOException e) {\n nswd.loadingStatus = LoadingStatus.CONN_ERROR;\n Log.w(TAG, \"Watched Repositories loading failed due to connection problem: \" + e.getMessage());\n } catch (JSONException e) {\n nswd.loadingStatus = LoadingStatus.DATA_ERROR;\n Log.w(TAG, \"Watched Repositories loading failed due to data format problem: \" + e.getMessage());\n } catch (Exception e) {\n nswd.loadingStatus = LoadingStatus.UNKNOWN_ERROR;\n Log.e(TAG, \"Watched Repositories loading failed due to: \" + e.getMessage(), e);\n }\n\n // Show content from store because we are unable to read new one but want to show something\n if (ns == null)\n ns = oldNs;\n\n nswd.repositories = ns;\n return nswd;\n }\n }\n\n /**\n * @param id of repository to unwatch\n * @return view data with result of call\n */\n public BaseViewData unwatchRepository(long id) {\n BaseViewData nswd = new BaseViewData();\n try {\n synchronized (TAG) {\n WatchedRepositories oldNs = Utils.readFromStore(TAG, context, persistFile);\n if (oldNs != null) {\n Repository ret = oldNs.removeRepositoryById(id);\n if (ret != null) {\n RemoteSystemClient.deleteToURL(context, authenticationManager.getGhApiCredentials(context),\n GHConstants.URL_BASE + \"/repos/\" + ret.getRepositoryFullName() + \"/subscription\", null);\n Utils.writeToStore(TAG, context, persistFile, oldNs);\n }\n }\n }\n } catch (NoRouteToHostException e) {\n nswd.loadingStatus = LoadingStatus.CONN_UNAVAILABLE;\n } catch (AuthenticationException e) {\n nswd.loadingStatus = LoadingStatus.AUTH_ERROR;\n } catch (IOException e) {\n Log.w(TAG, \"Repository unwatch failed due to connection problem: \" + e.getMessage());\n nswd.loadingStatus = LoadingStatus.CONN_ERROR;\n } catch (Exception e) {\n Log.e(TAG, \"Repository unwatch failed due to: \" + e.getMessage(), e);\n nswd.loadingStatus = LoadingStatus.UNKNOWN_ERROR;\n }\n return nswd;\n }\n\n protected WatchedRepositories readFromServer(String url) throws InvalidObjectException, NoRouteToHostException, AuthenticationException, IOException,\n JSONException, URISyntaxException {\n\n Response<JSONArray> resp = RemoteSystemClient.getJSONArrayFromUrl(context, authenticationManager.getGhApiCredentials(context), url, null);\n\n if (resp.notModified)\n return null;\n\n WatchedRepositories ns = WatchedRepositoriesParser.parseNotificationStream(resp.data);\n ns.setLastFullUpdateTimestamp(System.currentTimeMillis());\n return ns;\n }\n\n public void flushPersistentStore() {\n persistFile.delete();\n }\n\n}", "public class ImageLoader {\n\n private static final String TAG = \"ImageLoader\";\n\n /**\n * Timeout of images in file cache [millis]\n */\n private static final int IMG_FILE_CACHE_TIMEOUT = 24 * 60 * 60 * 1000;\n\n private Context context;\n private MemoryCache memoryCache = new MemoryCache();\n private FileCache fileCache;\n private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());\n private ExecutorService executorService;\n private Map<String, ImageToLoad> imageToLoadTasksMap = new WeakHashMap<String, ImageToLoad>();\n\n private static ImageLoader instance;\n\n /**\n * Get instance for use.\n *\n * @param context to be used in loader\n * @return image loader instance for use\n */\n public static ImageLoader getInstance(Context context) {\n if (instance == null)\n instance = new ImageLoader(context);\n return instance;\n }\n\n private ImageLoader(Context context) {\n this.context = context.getApplicationContext();\n fileCache = new FileCache(context);\n executorService = Executors.newFixedThreadPool(5);\n }\n\n /**\n * Display image from given URL - cached.\n *\n * @param url to get image from\n * @param imageView to display image into - Activity is taken from it.\n * @see #displayImage(String, ImageView, Activity)\n */\n public void displayImage(String url, ImageView imageView) {\n displayImage(url, imageView, null);\n }\n\n /**\n * Display image from given URL - cached.\n *\n * @param url to get image from\n * @param imageView to display image into\n * @param activity to show image in\n */\n public void displayImage(String url, ImageView imageView, Activity activity) {\n if (url == null || url.isEmpty())\n imageView.setVisibility(View.INVISIBLE);\n imageViews.put(imageView, url);\n Bitmap bitmap = memoryCache.get(url);\n if (bitmap != null) {\n showImageInView(imageView, bitmap, false);\n } else {\n queueImageLoad(url, imageView, activity);\n setProgressBarVisibility(imageView, true);\n }\n }\n\n /**\n * Load image for given URL. All caches are used as in {@link #displayImage(String, ImageView, Activity)}.\n *\n * @param url to get image from\n * @return image bitmap or null if not available\n */\n public Bitmap loadImageWithFileLevelCache(String url) {\n if (url == null || url.isEmpty())\n return null;\n Bitmap bitmap = memoryCache.get(url);\n if (bitmap != null)\n return bitmap;\n return loadImageWithFileLevelCache(null, url);\n }\n\n private void setProgressBarVisibility(ImageView imageView, boolean visible) {\n View pb = (View) ((View) imageView.getParent()).findViewById(android.R.id.progress);\n if (visible) {\n if (pb != null) {\n pb.setVisibility(View.VISIBLE);\n imageView.setVisibility(View.INVISIBLE);\n }\n } else {\n if (pb != null) {\n pb.setVisibility(View.INVISIBLE);\n }\n imageView.setVisibility(View.VISIBLE);\n }\n }\n\n private void queueImageLoad(String url, ImageView imageView, Activity activity) {\n synchronized (imageToLoadTasksMap) {\n ImageToLoad p = imageToLoadTasksMap.get(url);\n if (p == null) {\n p = new ImageToLoad(url, imageView, activity);\n imageToLoadTasksMap.put(url, p);\n executorService.submit(new ImageLoaderTask(p));\n } else {\n p.addImageView(imageView);\n }\n }\n\n }\n\n protected Bitmap loadImageWithFileLevelCache(ImageToLoad imageToLoad, String url) {\n\n if (imageToLoad != null)\n url = imageToLoad.url;\n File f = fileCache.getFile(url);\n\n // get from file cache if exists there and not too old\n if (f.exists()) {\n boolean isTimeoutValid = (f.lastModified() > System.currentTimeMillis() - IMG_FILE_CACHE_TIMEOUT);\n if (isTimeoutValid || imageToLoad != null) {\n Bitmap b = decodeFile(f);\n if (b != null) {\n if (isTimeoutValid) {\n return b;\n } else {\n // temporarily show image before new one is loaded from web\n showImage(imageToLoad, b, false);\n }\n }\n }\n }\n\n // from web\n if (Utils.isInternetConnectionAvailable(Utils.getConnectivityManager(context))) {\n\n InputStream is = null;\n OutputStream os = null;\n try {\n Bitmap bitmap = null;\n URL imageUrl = new URL(url);\n HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();\n conn.setConnectTimeout(30000);\n conn.setReadTimeout(30000);\n conn.setInstanceFollowRedirects(true);\n is = conn.getInputStream();\n if (!f.exists()) {\n Log.d(TAG, \"File do not exists: \" + f.getAbsolutePath());\n f.createNewFile();\n }\n os = new FileOutputStream(f);\n Utils.copyStream(is, os);\n os.close();\n os = null;\n bitmap = decodeFile(f);\n return bitmap;\n } catch (Throwable ex) {\n Log.w(TAG, \"Can't load image from server for URL \" + url + \" due to exception: \" + ex.getMessage(), ex);\n if (ex instanceof OutOfMemoryError)\n memoryCache.clear();\n } finally {\n Utils.closeStream(os);\n Utils.closeStream(is);\n }\n }\n\n if (f.exists()) {\n // not connected to internet or some error, so use from file if available (even timed out) to show at least something\n return decodeFile(f);\n }\n return null;\n }\n\n // decodes image and scales it to reduce memory consumption\n private Bitmap decodeFile(File f) {\n if (!f.exists())\n return null;\n FileInputStream stream1 = null;\n FileInputStream stream2 = null;\n try {\n // decode image size\n BitmapFactory.Options o = new BitmapFactory.Options();\n o.inJustDecodeBounds = true;\n stream1 = new FileInputStream(f);\n BitmapFactory.decodeStream(stream1, null, o);\n stream1.close();\n\n // Find the correct scale value. It should be the power of 2.\n final int REQUIRED_SIZE = 70;\n int width_tmp = o.outWidth, height_tmp = o.outHeight;\n int scale = 1;\n while (true) {\n if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)\n break;\n width_tmp /= 2;\n height_tmp /= 2;\n scale *= 2;\n }\n\n // decode with inSampleSize\n BitmapFactory.Options o2 = new BitmapFactory.Options();\n o2.inSampleSize = scale;\n stream2 = new FileInputStream(f);\n Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);\n stream2.close();\n return bitmap;\n\n } catch (Exception e) {\n Log.w(TAG, \"Can't decode cached image file due to exception: \" + e.getMessage(), e);\n } finally {\n Utils.closeStream(stream1);\n Utils.closeStream(stream2);\n }\n return null;\n }\n\n private class ImageToLoad {\n public String url;\n public boolean isShownAlready = false;\n Set<WeakReference<ImageView>> imageViewList = new HashSet<WeakReference<ImageView>>();\n Activity activity;\n\n public ImageToLoad(String u, ImageView i, Activity a) {\n url = u;\n activity = a;\n imageViewList.add(new WeakReference<ImageView>(i));\n }\n\n public void addImageView(ImageView i) {\n imageViewList.add(new WeakReference<ImageView>(i));\n }\n }\n\n class ImageLoaderTask implements Runnable {\n ImageToLoad imageToLoad;\n\n ImageLoaderTask(ImageToLoad photoToLoad) {\n this.imageToLoad = photoToLoad;\n }\n\n @Override\n public void run() {\n try {\n synchronized (imageToLoadTasksMap) {\n if (!isAtLeastOneImageViewValid(imageToLoad)) {\n imageToLoadTasksMap.remove(imageToLoad.url);\n return;\n }\n }\n Bitmap bmp = loadImageWithFileLevelCache(imageToLoad, null);\n if (bmp != null)\n memoryCache.put(imageToLoad.url, bmp);\n showImage(imageToLoad, bmp, true);\n } catch (Throwable th) {\n Log.e(TAG, \"Image loading error: \" + th.getMessage(), th);\n }\n }\n\n }\n\n private void showImage(ImageToLoad imageToLoad, Bitmap bmp, boolean removeFromMap) {\n synchronized (imageToLoadTasksMap) {\n if (removeFromMap)\n imageToLoadTasksMap.remove(imageToLoad.url);\n if (isAtLeastOneImageViewValid(imageToLoad)) {\n BitmapDisplayerTask bd = new BitmapDisplayerTask(bmp, imageToLoad);\n Activity a = getActivity(imageToLoad);\n if (a != null) {\n a.runOnUiThread(bd);\n }\n }\n }\n }\n\n private Activity getActivity(ImageToLoad imageToLoad) {\n if (imageToLoad.activity != null)\n return imageToLoad.activity;\n for (WeakReference<ImageView> wr : imageToLoad.imageViewList) {\n if (wr != null) {\n ImageView iv = wr.get();\n if (iv != null) {\n Context c = iv.getContext();\n if (c instanceof Activity) {\n return (Activity) c;\n }\n }\n }\n }\n return null;\n }\n\n boolean isAtLeastOneImageViewValid(ImageToLoad photoToLoad) {\n for (WeakReference<ImageView> wr : photoToLoad.imageViewList) {\n if (wr != null)\n if (isImageViewValid(photoToLoad, wr.get()))\n return true;\n }\n return false;\n }\n\n private boolean isImageViewValid(ImageToLoad photoToLoad, ImageView iv) {\n if (iv == null)\n return false;\n String tag = imageViews.get(iv);\n if (tag != null && tag.equals(photoToLoad.url)) {\n return true;\n }\n return false;\n }\n\n class BitmapDisplayerTask implements Runnable {\n Bitmap bitmap;\n ImageToLoad imageToLoad;\n\n public BitmapDisplayerTask(Bitmap b, ImageToLoad p) {\n bitmap = b;\n imageToLoad = p;\n }\n\n public void run() {\n for (WeakReference<ImageView> wr : imageToLoad.imageViewList) {\n if (wr != null) {\n ImageView iv = wr.get();\n if (isImageViewValid(imageToLoad, iv)) {\n if (bitmap != null) {\n showImageInView(iv, bitmap, !imageToLoad.isShownAlready);\n }\n }\n }\n }\n imageToLoad.isShownAlready = true;\n }\n }\n\n protected void showImageInView(ImageView iv, Bitmap bitmap, boolean animate) {\n iv.clearAnimation();\n if (animate)\n iv.setAlpha(0f);\n iv.setImageBitmap(bitmap);\n setProgressBarVisibility(iv, false);\n if (animate)\n iv.animate().alpha(1f).setDuration(200).start();\n }\n\n /**\n * Clear memory cache.\n */\n public void clearCache() {\n memoryCache.clear();\n }\n\n}", "public class BaseViewData {\n\n public LoadingStatus loadingStatus = LoadingStatus.OK;\n\n}", "public enum LoadingStatus {\n\n OK(0), CONN_UNAVAILABLE(R.string.message_err_comm_error_conn_unavailable), AUTH_ERROR(R.string.message_err_comm_error_auth), CONN_ERROR(\n R.string.message_err_comm_error_conn_error), DATA_ERROR(R.string.message_err_comm_error_data_error), UNKNOWN_ERROR(\n R.string.message_err_comm_error_unknown);\n\n private int resId;\n\n private LoadingStatus(int resId) {\n this.resId = resId;\n }\n\n /**\n * @return resource id for error message\n */\n public int getResId() {\n return resId;\n }\n\n}", "public class Repository implements Serializable {\n\n private static final long serialVersionUID = 2L;\n\n private long id;\n private String url;\n private String htmlUrl;\n private String repositoryFullName;\n private String repositoryAvatarUrl;\n\n /**\n * Constructor for unit tests.\n * \n * @param id\n * @param repositoryFullName\n */\n protected Repository(long id, String repositoryFullName) {\n super();\n this.id = id;\n this.repositoryFullName = repositoryFullName;\n }\n\n public Repository(long id, String url, String repositoryFullName, String repositoryAvatarUrl, String htmlUrl) {\n super();\n this.id = id;\n this.url = Utils.trimToNull(url);\n this.repositoryFullName = repositoryFullName;\n this.repositoryAvatarUrl = Utils.trimToNull(repositoryAvatarUrl);\n this.htmlUrl = Utils.trimToNull(htmlUrl);\n }\n\n public long getId() {\n return id;\n }\n\n public String getUrl() {\n return url;\n }\n\n public String getHtmlUrl() {\n return htmlUrl;\n }\n\n public String getRepositoryFullName() {\n return repositoryFullName;\n }\n\n public String getRepositoryAvatarUrl() {\n return repositoryAvatarUrl;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + (int) (id ^ (id >>> 32));\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 Repository other = (Repository) obj;\n if (id != other.id)\n return false;\n return true;\n }\n\n}" ]
import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import android.widget.Toast; import com.daskiworks.ghwatch.backend.PreferencesUtils; import com.daskiworks.ghwatch.backend.ViewDataReloadStrategy; import com.daskiworks.ghwatch.backend.WatchedRepositoriesService; import com.daskiworks.ghwatch.image.ImageLoader; import com.daskiworks.ghwatch.model.BaseViewData; import com.daskiworks.ghwatch.model.LoadingStatus; import com.daskiworks.ghwatch.model.Repository; import com.daskiworks.ghwatch.model.WatchedRepositoriesViewData; import java.util.concurrent.RejectedExecutionException;
/* * Copyright 2014 contributors as indicated by the @authors tag. * * 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.daskiworks.ghwatch; /** * Activity used to show list of watched repositories. * * @author Vlastimil Elias <[email protected]> */ public class WatchedRepositoriesActivity extends ActivityBase implements OnRefreshListener { private static final String TAG = WatchedRepositoriesActivity.class.getSimpleName(); // common fields private DataLoaderTask dataLoader; private ListView repositoriesListView; private WatchedRepositoryListAdapter repositoriesListAdapter; // backend services
private ImageLoader imageLoader;
2
Arjun-sna/Android-AudioRecorder-App
app/src/main/java/in/arjsna/audiorecorder/audiorecording/RecordFragment.java
[ "public class AppConstants {\n public static final String ACTION_PAUSE = \"in.arjsna.audiorecorder.PAUSE\";\n public static final String ACTION_RESUME = \"in.arjsna.audiorecorder.RESUME\";\n public static final String ACTION_STOP = \"in.arjsna.audiorecorder.STOP\";\n public static final String ACTION_IN_SERVICE = \"in.arjsna.audiorecorder.ACTION_IN_SERVICE\";\n}", "public class PlayListActivity extends BaseActivity implements HasSupportFragmentInjector {\n\n @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;\n\n @Override public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_record_list);\n Toolbar toolbar = findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n ActionBar actionBar = getSupportActionBar();\n if (actionBar != null) {\n actionBar.setTitle(R.string.tab_title_saved_recordings);\n actionBar.setDisplayHomeAsUpEnabled(true);\n actionBar.setDisplayShowHomeEnabled(true);\n }\n setNavBarColor();\n\n if (savedInstanceState == null) {\n getSupportFragmentManager().beginTransaction()\n .add(R.id.record_list_container, PlayListFragment.newInstance())\n .commit();\n }\n }\n\n @Override public AndroidInjector<Fragment> supportFragmentInjector() {\n return dispatchingAndroidInjector;\n }\n}", "public class SettingsActivity extends BaseActivity {\n @Override public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_preferences);\n\n Toolbar toolbar = findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n ActionBar actionBar = getSupportActionBar();\n if (actionBar != null) {\n actionBar.setTitle(R.string.action_settings);\n actionBar.setDisplayHomeAsUpEnabled(true);\n actionBar.setDisplayShowHomeEnabled(true);\n }\n\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.container, new SettingsFragment())\n .commit();\n }\n}", "public class GLAudioVisualizationView extends GLSurfaceView\n implements AudioVisualization, InnerAudioVisualization {\n\n private static final int EGL_VERSION = 2;\n private final GLRenderer renderer;\n private DbmHandler<?> dbmHandler;\n private final Configuration configuration;\n private CalmDownListener innerCalmDownListener;\n\n private GLAudioVisualizationView(@NonNull Builder builder) {\n super(builder.context);\n configuration = new Configuration(builder);\n renderer = new GLRenderer(getContext(), configuration);\n init();\n }\n\n public GLAudioVisualizationView(Context context, AttributeSet attrs) {\n super(context, attrs);\n configuration = new Configuration(context, attrs, isInEditMode());\n renderer = new GLRenderer(getContext(), configuration);\n init();\n }\n\n private void init() {\n setEGLContextClientVersion(EGL_VERSION);\n setRenderer(renderer);\n renderer.calmDownListener(() -> {\n stopRendering();\n if (innerCalmDownListener != null) {\n innerCalmDownListener.onCalmedDown();\n }\n });\n }\n\n @Override public void onResume() {\n super.onResume();\n if (dbmHandler != null) {\n dbmHandler.onResume();\n }\n }\n\n @Override public void onPause() {\n if (dbmHandler != null) {\n dbmHandler.onPause();\n }\n super.onPause();\n }\n\n @Override public <T> void linkTo(@NonNull DbmHandler<T> dbmHandler) {\n if (this.dbmHandler != null) {\n this.dbmHandler.release();\n }\n this.dbmHandler = dbmHandler;\n this.dbmHandler.setUp(this, configuration.layersCount);\n }\n\n @Override public void release() {\n if (dbmHandler != null) {\n dbmHandler = null;\n calmDownListener(null);\n renderer.calmDownListener(null);\n }\n }\n\n @Override public void startRendering() {\n if (getRenderMode() != RENDERMODE_CONTINUOUSLY) {\n setRenderMode(RENDERMODE_CONTINUOUSLY);\n }\n }\n\n @Override public void stopRendering() {\n if (getRenderMode() != RENDERMODE_WHEN_DIRTY) {\n setRenderMode(RENDERMODE_WHEN_DIRTY);\n }\n }\n\n @Override public void calmDownListener(@Nullable CalmDownListener calmDownListener) {\n innerCalmDownListener = calmDownListener;\n }\n\n @Override public void onDataReceived(float[] dBmArray, float[] ampsArray) {\n renderer.onDataReceived(dBmArray, ampsArray);\n }\n\n public void updateConfig(ColorsBuilder colorsBuilder) {\n renderer.updateConfiguration(colorsBuilder);\n }\n\n /**\n * Configuration holder class.\n */\n static class Configuration {\n\n int wavesCount;\n int layersCount;\n int bubblesPerLayer;\n float bubbleSize;\n float waveHeight;\n float footerHeight;\n boolean randomizeBubbleSize;\n float[] backgroundColor;\n float[][] layerColors;\n\n public Configuration(Context context, AttributeSet attrs, boolean isInEditMode) {\n TypedArray array =\n context.obtainStyledAttributes(attrs, R.styleable.GLAudioVisualizationView);\n int[] colors;\n int bgColor;\n try {\n layersCount = array.getInt(R.styleable.GLAudioVisualizationView_av_layersCount,\n Constants.DEFAULT_LAYERS_COUNT);\n layersCount =\n Utils.between(layersCount, Constants.MIN_LAYERS_COUNT, Constants.MAX_LAYERS_COUNT);\n wavesCount = array.getInt(R.styleable.GLAudioVisualizationView_av_wavesCount,\n Constants.DEFAULT_WAVES_COUNT);\n wavesCount =\n Utils.between(wavesCount, Constants.MIN_WAVES_COUNT, Constants.MAX_WAVES_COUNT);\n waveHeight =\n array.getDimensionPixelSize(R.styleable.GLAudioVisualizationView_av_wavesHeight,\n (int) Constants.DEFAULT_WAVE_HEIGHT);\n waveHeight =\n Utils.between(waveHeight, Constants.MIN_WAVE_HEIGHT, Constants.MAX_WAVE_HEIGHT);\n bubbleSize =\n array.getDimensionPixelSize(R.styleable.GLAudioVisualizationView_av_bubblesSize,\n Constants.DEFAULT_BUBBLE_SIZE);\n bubbleSize =\n Utils.between(bubbleSize, Constants.MIN_BUBBLE_SIZE, Constants.MAX_BUBBLE_SIZE);\n randomizeBubbleSize =\n array.getBoolean(R.styleable.GLAudioVisualizationView_av_bubblesRandomizeSizes, false);\n footerHeight =\n array.getDimensionPixelSize(R.styleable.GLAudioVisualizationView_av_wavesFooterHeight,\n (int) Constants.DEFAULT_FOOTER_HEIGHT);\n footerHeight =\n Utils.between(footerHeight, Constants.MIN_FOOTER_HEIGHT, Constants.MAX_FOOTER_HEIGHT);\n bubblesPerLayer = array.getInt(R.styleable.GLAudioVisualizationView_av_bubblesPerLayer,\n Constants.DEFAULT_BUBBLES_PER_LAYER);\n bubblesPerLayer = Utils.between(bubblesPerLayer, Constants.DEFAULT_BUBBLES_PER_LAYER_MIN,\n Constants.DEFAULT_BUBBLES_PER_LAYER_MAX);\n bgColor = array.getColor(R.styleable.GLAudioVisualizationView_av_backgroundColor,\n Color.TRANSPARENT);\n if (bgColor == Color.TRANSPARENT) {\n bgColor = ContextCompat.getColor(context, R.color.av_color_bg);\n }\n // TODO: 9/9/17 fix this\n //int arrayId = array.getResourceId(R.styleable.GLAudioVisualizationView_av_wavesColors,\n // R.array.av_colors);\n //if (isInEditMode) {\n // colors = new int[layersCount];\n //} else {\n // TypedArray colorsArray = array.getResources().obtainTypedArray(arrayId);\n // colors = new int[colorsArray.length()];\n // for (int i = 0; i < colorsArray.length(); i++) {\n // colors[i] = colorsArray.getColor(i, Color.TRANSPARENT);\n // }\n // colorsArray.recycle();\n //}\n } finally {\n array.recycle();\n }\n colors = Hawk.get(context.getString(R.string.preference_layer_colors),\n ColorPalette.getColors(context, ContextCompat.getColor(context, R.color.av_color5)));\n if (colors.length < layersCount) {\n throw new IllegalArgumentException(\"You specified more layers than colors.\");\n }\n\n layerColors = new float[colors.length][];\n for (int i = 0; i < colors.length; i++) {\n layerColors[i] = Utils.convertColor(colors[i]);\n }\n backgroundColor = Utils.convertColor(bgColor);\n bubbleSize /= context.getResources().getDisplayMetrics().widthPixels;\n }\n\n private Configuration(@NonNull Builder builder) {\n this.waveHeight = builder.waveHeight;\n waveHeight = Utils.between(waveHeight, Constants.MIN_WAVE_HEIGHT, Constants.MAX_WAVE_HEIGHT);\n this.wavesCount = builder.wavesCount;\n wavesCount = Utils.between(wavesCount, Constants.MIN_WAVES_COUNT, Constants.MAX_WAVES_COUNT);\n this.layerColors = builder.layerColors();\n this.bubbleSize = builder.bubbleSize;\n bubbleSize = Utils.between(bubbleSize, Constants.MIN_BUBBLE_SIZE, Constants.MAX_BUBBLE_SIZE);\n this.bubbleSize =\n this.bubbleSize / builder.context.getResources().getDisplayMetrics().widthPixels;\n this.footerHeight = builder.footerHeight;\n footerHeight =\n Utils.between(footerHeight, Constants.MIN_FOOTER_HEIGHT, Constants.MAX_FOOTER_HEIGHT);\n this.randomizeBubbleSize = builder.randomizeBubbleSize;\n this.backgroundColor = builder.backgroundColor();\n this.layersCount = builder.layersCount;\n this.bubblesPerLayer = builder.bubblesPerLayer;\n Utils.between(bubblesPerLayer, Constants.DEFAULT_BUBBLES_PER_LAYER_MIN,\n Constants.DEFAULT_BUBBLES_PER_LAYER_MAX);\n layersCount =\n Utils.between(layersCount, Constants.MIN_LAYERS_COUNT, Constants.MAX_LAYERS_COUNT);\n if (layerColors.length < layersCount) {\n throw new IllegalArgumentException(\"You specified more layers than colors.\");\n }\n }\n }\n\n public static class ColorsBuilder<T extends ColorsBuilder> {\n private float[] backgroundColor;\n private float[][] layerColors;\n private final Context context;\n\n public ColorsBuilder(@NonNull Context context) {\n this.context = context;\n }\n\n float[][] layerColors() {\n return layerColors;\n }\n\n float[] backgroundColor() {\n return backgroundColor;\n }\n\n /**\n * Set background color\n *\n * @param backgroundColor background color\n */\n public T setBackgroundColor(@ColorInt int backgroundColor) {\n this.backgroundColor = Utils.convertColor(backgroundColor);\n return getThis();\n }\n\n /**\n * Set layer colors from array resource\n *\n * @param arrayId array resource\n */\n public T setLayerColors(@ArrayRes int arrayId) {\n TypedArray colorsArray = context.getResources().obtainTypedArray(arrayId);\n int[] colors = new int[colorsArray.length()];\n for (int i = 0; i < colorsArray.length(); i++) {\n colors[i] = colorsArray.getColor(i, Color.TRANSPARENT);\n }\n colorsArray.recycle();\n return setLayerColors(colors);\n }\n\n /**\n * Set layer colors.\n *\n * @param colors array of colors\n */\n public T setLayerColors(int[] colors) {\n layerColors = new float[colors.length][];\n for (int i = 0; i < colors.length; i++) {\n layerColors[i] = Utils.convertColor(colors[i]);\n }\n return getThis();\n }\n\n /**\n * Set background color from color resource\n *\n * @param backgroundColor color resource\n */\n public T setBackgroundColorRes(@ColorRes int backgroundColor) {\n return setBackgroundColor(ContextCompat.getColor(context, backgroundColor));\n }\n\n protected T getThis() {\n //noinspection unchecked\n return (T) this;\n }\n }\n\n public static class Builder extends ColorsBuilder<Builder> {\n\n private final Context context;\n private int wavesCount;\n private int layersCount;\n private float bubbleSize;\n private float waveHeight;\n private float footerHeight;\n private boolean randomizeBubbleSize;\n private int bubblesPerLayer;\n\n public Builder(@NonNull Context context) {\n super(context);\n this.context = context;\n }\n\n @Override protected Builder getThis() {\n return this;\n }\n\n /**\n * Set waves count\n *\n * @param wavesCount waves count\n */\n public Builder setWavesCount(int wavesCount) {\n this.wavesCount = wavesCount;\n return this;\n }\n\n /**\n * Set layers count\n *\n * @param layersCount layers count\n */\n public Builder setLayersCount(int layersCount) {\n this.layersCount = layersCount;\n return this;\n }\n\n /**\n * Set bubbles size in pixels\n *\n * @param bubbleSize bubbles size in pixels\n */\n public Builder setBubblesSize(float bubbleSize) {\n this.bubbleSize = bubbleSize;\n return this;\n }\n\n /**\n * Set bubble size from dimension resource\n *\n * @param bubbleSize dimension resource\n */\n public Builder setBubblesSize(@DimenRes int bubbleSize) {\n return setBubblesSize((float) context.getResources().getDimensionPixelSize(bubbleSize));\n }\n\n /**\n * Set wave height in pixels\n *\n * @param waveHeight wave height in pixels\n */\n public Builder setWavesHeight(float waveHeight) {\n this.waveHeight = waveHeight;\n return this;\n }\n\n /**\n * Set wave height from dimension resource\n *\n * @param waveHeight dimension resource\n */\n public Builder setWavesHeight(@DimenRes int waveHeight) {\n return setWavesHeight((float) context.getResources().getDimensionPixelSize(waveHeight));\n }\n\n /**\n * Set footer height in pixels\n *\n * @param footerHeight footer height in pixels\n */\n public Builder setWavesFooterHeight(float footerHeight) {\n this.footerHeight = footerHeight;\n return this;\n }\n\n /**\n * Set footer height from dimension resource\n *\n * @param footerHeight dimension resource\n */\n public Builder setWavesFooterHeight(@DimenRes int footerHeight) {\n return setWavesFooterHeight(\n (float) context.getResources().getDimensionPixelSize(footerHeight));\n }\n\n /**\n * Set flag indicates that size of bubbles should be randomized\n *\n * @param randomizeBubbleSize true if size of bubbles should be randomized, false if size of\n * bubbles must be the same\n */\n public Builder setBubblesRandomizeSize(boolean randomizeBubbleSize) {\n this.randomizeBubbleSize = randomizeBubbleSize;\n return this;\n }\n\n /**\n * Set number of bubbles per layer.\n *\n * @param bubblesPerLayer number of bubbles per layer\n */\n public Builder setBubblesPerLayer(int bubblesPerLayer) {\n this.bubblesPerLayer = bubblesPerLayer;\n return this;\n }\n\n public GLAudioVisualizationView build() {\n return new GLAudioVisualizationView(this);\n }\n }\n\n /**\n * Renderer builder.\n */\n public static class RendererBuilder {\n\n private final Builder builder;\n private GLSurfaceView glSurfaceView;\n private DbmHandler handler;\n\n /**\n * Create new renderer using existing Audio Visualization builder.\n *\n * @param builder instance of Audio Visualization builder\n */\n public RendererBuilder(@NonNull Builder builder) {\n this.builder = builder;\n }\n\n /**\n * Set dBm handler.\n *\n * @param handler instance of dBm handler\n */\n public RendererBuilder handler(DbmHandler handler) {\n this.handler = handler;\n return this;\n }\n\n /**\n * Set OpenGL surface view.\n *\n * @param glSurfaceView instance of OpenGL surface view\n */\n public RendererBuilder glSurfaceView(@NonNull GLSurfaceView glSurfaceView) {\n this.glSurfaceView = glSurfaceView;\n return this;\n }\n\n /**\n * Create new Audio Visualization Renderer.\n *\n * @return new Audio Visualization Renderer\n */\n public AudioVisualizationRenderer build() {\n final GLRenderer renderer = new GLRenderer(builder.context, new Configuration(builder));\n final InnerAudioVisualization audioVisualization = new InnerAudioVisualization() {\n @Override public void startRendering() {\n if (glSurfaceView.getRenderMode() != RENDERMODE_CONTINUOUSLY) {\n glSurfaceView.setRenderMode(RENDERMODE_CONTINUOUSLY);\n }\n }\n\n @Override public void stopRendering() {\n if (glSurfaceView.getRenderMode() != RENDERMODE_WHEN_DIRTY) {\n glSurfaceView.setRenderMode(RENDERMODE_WHEN_DIRTY);\n }\n }\n\n @Override public void calmDownListener(@Nullable CalmDownListener calmDownListener) {\n\n }\n\n @Override public void onDataReceived(float[] dBmArray, float[] ampsArray) {\n renderer.onDataReceived(dBmArray, ampsArray);\n }\n };\n renderer.calmDownListener(audioVisualization::stopRendering);\n handler.setUp(audioVisualization, builder.layersCount);\n return renderer;\n }\n }\n\n /**\n * Audio Visualization renderer interface that allows to change waves' colors at runtime.\n */\n public interface AudioVisualizationRenderer extends Renderer {\n\n /**\n * Update colors configuration.\n *\n * @param builder instance of color builder.\n */\n void updateConfiguration(@NonNull ColorsBuilder builder);\n }\n}", "public abstract class BaseFragment extends ThemedFragment implements IMVPView {\n\n @Override public void onAttach(Context context) {\n super.onAttach(context);\n AndroidSupportInjection.inject(this);\n }\n}", "public class AudioRecordService extends Service {\n private static final String LOG_TAG = \"RecordingService\";\n\n @Inject\n public AudioRecorder audioRecorder;\n @Inject\n public AudioRecordingDbmHandler handler;\n private ServiceBinder mIBinder;\n private NotificationManager mNotificationManager;\n private static final int NOTIFY_ID = 100;\n private AudioRecorder.RecordTime lastUpdated;\n private boolean mIsClientBound = false;\n\n @Override public IBinder onBind(Intent intent) {\n mIsClientBound = true;\n return mIBinder;\n }\n\n public boolean isRecording() {\n return audioRecorder.isRecording();\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n AndroidInjection.inject(this);\n handler.addRecorder(audioRecorder);\n mIBinder = new ServiceBinder();\n mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n }\n\n public AudioRecordingDbmHandler getHandler() {\n return handler;\n }\n\n @Override public int onStartCommand(Intent intent, int flags, int startId) {\n if (intent.getAction() != null) {\n switch (intent.getAction()) {\n case AppConstants.ACTION_PAUSE:\n pauseRecord();\n break;\n case AppConstants.ACTION_RESUME:\n resumeRecord();\n break;\n case AppConstants.ACTION_STOP:\n if (!mIsClientBound) {\n stopSelf();\n }\n }\n if (mIsClientBound) {\n intent.putExtra(AppConstants.ACTION_IN_SERVICE, intent.getAction());\n intent.setAction(AppConstants.ACTION_IN_SERVICE);\n LocalBroadcastManager.getInstance(this).sendBroadcast(intent);\n }\n } else {\n startRecording();\n startForeground(NOTIFY_ID, createNotification(new AudioRecorder.RecordTime()));\n }\n return START_STICKY;\n }\n\n @Override public void onDestroy() {\n super.onDestroy();\n if (isRecording()) {\n stopRecodingAndRelease();\n }\n }\n\n private void stopRecodingAndRelease() {\n audioRecorder.finishRecord();\n handler.stop();\n }\n\n private void startRecording() {\n boolean prefHighQuality =\n Hawk.get(getApplicationContext().getString(R.string.pref_high_quality_key), false);\n audioRecorder.startRecord(\n prefHighQuality ? Constants.RECORDER_SAMPLE_RATE_HIGH : Constants.RECORDER_SAMPLE_RATE_LOW);\n handler.startDbmThread();\n audioRecorder.subscribeTimer(this::updateNotification);\n }\n\n public Disposable subscribeForTimer(Consumer<AudioRecorder.RecordTime> timerConsumer) {\n return audioRecorder.subscribeTimer(timerConsumer);\n }\n\n private void updateNotification(AudioRecorder.RecordTime recordTime) {\n mNotificationManager.notify(NOTIFY_ID, createNotification(recordTime));\n }\n\n private Notification createNotification(AudioRecorder.RecordTime recordTime) {\n lastUpdated = recordTime;\n NotificationCompat.Builder mBuilder =\n new NotificationCompat.Builder(getApplicationContext()).setSmallIcon(\n R.drawable.ic_media_record)\n .setContentTitle(getString(R.string.notification_recording))\n .setContentText(\n String.format(Locale.getDefault(), getString(R.string.record_time_format),\n recordTime.hours,\n recordTime.minutes,\n recordTime.seconds))\n .addAction(R.drawable.ic_media_stop, getString(R.string.stop_recording),\n getActionIntent(AppConstants.ACTION_STOP))\n .setOngoing(true);\n if (audioRecorder.isPaused()) {\n mBuilder.addAction(R.drawable.ic_media_record, getString(R.string.resume_recording_button),\n getActionIntent(AppConstants.ACTION_RESUME));\n } else {\n mBuilder.addAction(R.drawable.ic_media_pause, getString(R.string.pause_recording_button),\n getActionIntent(AppConstants.ACTION_PAUSE));\n }\n mBuilder.setContentIntent(PendingIntent.getActivities(getApplicationContext(), 0,\n new Intent[] {new Intent(getApplicationContext(), MainActivity.class)}, 0));\n\n return mBuilder.build();\n }\n\n public void pauseRecord() {\n audioRecorder.pauseRecord();\n updateNotification(lastUpdated);\n }\n\n public boolean isPaused() {\n return audioRecorder.isPaused();\n }\n\n public void resumeRecord() {\n audioRecorder.resumeRecord();\n }\n\n public class ServiceBinder extends Binder {\n public AudioRecordService getService() {\n return AudioRecordService.this;\n }\n }\n\n private PendingIntent getActionIntent(String action) {\n Intent pauseIntent = new Intent(this, AudioRecordService.class);\n pauseIntent.setAction(action);\n return PendingIntent.getService(this, 100, pauseIntent, 0);\n }\n\n @Override public boolean onUnbind(Intent intent) {\n mIsClientBound = false;\n return true;\n }\n\n @Override public void onRebind(Intent intent) {\n mIsClientBound = true;\n }\n}", "public class AudioRecorder implements IAudioRecorder {\n\n private static final int RECORDER_STATE_FAILURE = -1;\n private static final int RECORDER_STATE_IDLE = 0;\n private static final int RECORDER_STATE_STARTING = 1;\n private static final int RECORDER_STATE_STOPPING = 2;\n private static final int RECORDER_STATE_BUSY = 3;\n\n private volatile int recorderState;\n\n private int mRecorderSampleRate = 8000;\n\n private AudioSaveHelper audioSaveHelper = null;\n\n private final Object recorderStateMonitor = new Object();\n\n private byte[] recordBuffer;\n\n private final CompositeDisposable compositeDisposable = new CompositeDisposable();\n\n private final AtomicLong mRecordTimeCounter = new AtomicLong(0);\n private final AtomicBoolean mIsPaused = new AtomicBoolean(false);\n private RecordTime currentRecordTime;\n\n @Inject\n public AudioRecorder(AudioSaveHelper audioSaveHelper) {\n this.audioSaveHelper = audioSaveHelper;\n }\n\n @SuppressWarnings(\"ResultOfMethodCallIgnored\") private void onRecordFailure() {\n recorderState = RECORDER_STATE_FAILURE;\n finishRecord();\n }\n\n @Override public void startRecord(int recorderSampleRate) {\n if (recorderState != RECORDER_STATE_IDLE) {\n return;\n }\n this.mRecorderSampleRate = recorderSampleRate;\n audioSaveHelper.setSampleRate(mRecorderSampleRate);\n startTimer();\n recorderState = RECORDER_STATE_STARTING;\n startRecordThread();\n }\n\n private final BehaviorProcessor<RecordTime> recordTimeProcessor = BehaviorProcessor.create();\n\n private void startTimer() {\n getTimerObservable().subscribeOn(Schedulers.newThread()).subscribe(recordTimeProcessor);\n }\n\n private Flowable<RecordTime> getTimerObservable() {\n return Flowable.interval(1000, TimeUnit.MILLISECONDS)\n .filter(timeElapsed -> !mIsPaused.get())\n .map(tick -> {\n long seconds = mRecordTimeCounter.incrementAndGet();\n RecordTime recordTime = new RecordTime();\n recordTime.millis = seconds * 1000;\n recordTime.hours = seconds / (60 * 60);\n seconds = seconds % (60 * 60);\n recordTime.minutes = seconds / 60;\n seconds = seconds % 60;\n recordTime.seconds = seconds;\n currentRecordTime = recordTime;\n return recordTime;\n });\n }\n\n private final Flowable<byte[]> audioDataFlowable = Flowable.create(emitter -> {\n int bufferSize = 4 * 1024;\n\n AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, mRecorderSampleRate,\n Constants.RECORDER_CHANNELS, Constants.RECORDER_AUDIO_ENCODING, bufferSize);\n audioSaveHelper.createNewFile();\n\n try {\n if (recorderState == RECORDER_STATE_STARTING) {\n recorderState = RECORDER_STATE_BUSY;\n }\n recorder.startRecording();\n\n recordBuffer = new byte[bufferSize];\n do {\n if (!mIsPaused.get()) {\n int bytesRead = recorder.read(recordBuffer, 0, bufferSize);\n emitter.onNext(recordBuffer);\n if (bytesRead == 0) {\n Log.e(AudioRecorder.class.getSimpleName(), \"error: \" + bytesRead);\n onRecordFailure();\n }\n }\n } while (recorderState == RECORDER_STATE_BUSY);\n } finally {\n recorder.release();\n }\n emitter.onComplete();\n }, BackpressureStrategy.DROP);\n\n private final PublishProcessor<byte[]> recordDataPublishProcessor = PublishProcessor.create();\n\n private void startRecordThread() {\n audioDataFlowable.subscribeOn(Schedulers.io()).subscribe(recordDataPublishProcessor);\n compositeDisposable.add(recordDataPublishProcessor.onBackpressureBuffer()\n .observeOn(Schedulers.io())\n .subscribeWith(new DisposableSubscriber<byte[]>() {\n @Override public void onNext(byte[] bytes) {\n audioSaveHelper.onDataReady(recordBuffer);\n }\n\n @Override public void onError(Throwable t) {\n\n }\n\n @Override public void onComplete() {\n audioSaveHelper.onRecordingStopped(currentRecordTime);\n synchronized (recorderStateMonitor) {\n recorderState = RECORDER_STATE_IDLE;\n recorderStateMonitor.notifyAll();\n }\n }\n }));\n }\n\n @Override public void finishRecord() {\n int recorderStateLocal = recorderState;\n if (recorderStateLocal != RECORDER_STATE_IDLE) {\n synchronized (recorderStateMonitor) {\n recorderStateLocal = recorderState;\n if (recorderStateLocal == RECORDER_STATE_STARTING\n || recorderStateLocal == RECORDER_STATE_BUSY) {\n\n recorderStateLocal = recorderState = RECORDER_STATE_STOPPING;\n }\n\n do {\n try {\n if (recorderStateLocal != RECORDER_STATE_IDLE) {\n recorderStateMonitor.wait();\n }\n } catch (InterruptedException ignore) {\n /* Nothing to do */\n }\n recorderStateLocal = recorderState;\n } while (recorderStateLocal == RECORDER_STATE_STOPPING);\n }\n }\n compositeDisposable.dispose();\n }\n\n @Override public void pauseRecord() {\n mIsPaused.set(true);\n }\n\n @Override public void resumeRecord() {\n mIsPaused.set(false);\n }\n\n @Override public boolean isRecording() {\n return recorderState != RECORDER_STATE_IDLE;\n }\n\n public Flowable<byte[]> getAudioDataFlowable() {\n return recordDataPublishProcessor;\n }\n\n public Disposable subscribeTimer(Consumer<RecordTime> timerConsumer) {\n Disposable disposable =\n recordTimeProcessor.observeOn(AndroidSchedulers.mainThread()).subscribe(timerConsumer);\n compositeDisposable.add(disposable);\n return disposable;\n }\n\n boolean isPaused() {\n return mIsPaused.get();\n }\n\n public static class RecordTime {\n public long seconds = 0;\n public long minutes = 0;\n public long hours = 0;\n long millis = 0;\n }\n}", "public class ThemeHelper {\n\n private final Context context;\n\n Theme baseTheme;\n private int primaryColor;\n private int accentColor;\n private int[] layerColor;\n\n private ThemeHelper(Context context) {\n this.context = context;\n }\n\n public static ThemeHelper getInstance(Context context) {\n return new ThemeHelper(context);\n }\n\n public static ThemeHelper getInstanceLoaded(Context context) {\n ThemeHelper instance = getInstance(context);\n instance.updateTheme();\n return instance;\n }\n\n public void updateTheme() {\n this.primaryColor = Hawk.get(context.getString(R.string.preference_primary_color),\n getColor(R.color.av_color5));\n this.accentColor = Hawk.get(context.getString(R.string.preference_accent_color),\n getColor(R.color.av_color5));\n this.layerColor = Hawk.get(context.getString(R.string.preference_layer_colors),\n ColorPalette.getColors(context, ContextCompat.getColor(context, R.color.av_color5)));\n baseTheme = Theme.fromValue(Hawk.get(context.getString(R.string.preference_base_theme), 1));\n }\n\n public int[] getLayerColor() {\n return layerColor;\n }\n\n public int getPrimaryColor() {\n return primaryColor;\n }\n\n public int getAccentColor() {\n return accentColor;\n }\n\n public Theme getBaseTheme() {\n return baseTheme;\n }\n\n public void setBaseTheme(Theme baseTheme) {\n this.baseTheme = baseTheme;\n Hawk.put(context.getString(R.string.preference_base_theme), getBaseTheme().getValue());\n }\n\n public static int getPrimaryColor(Context context) {\n return Hawk.get(context.getString(R.string.preference_primary_color),\n ContextCompat.getColor(context, R.color.md_indigo_500));\n }\n\n public boolean isPrimaryEqualAccent() {\n return (this.primaryColor == this.accentColor);\n }\n\n public static int getAccentColor(Context context) {\n return Hawk.get(context.getString(R.string.preference_accent_color),\n ContextCompat.getColor(context, R.color.md_light_blue_500));\n }\n\n public static Theme getBaseTheme(Context context) {\n return Theme.fromValue(\n Hawk.get(context.getString(R.string.preference_base_theme), Theme.LIGHT.value));\n }\n\n public int getColor(@ColorRes int color) {\n return ContextCompat.getColor(context, color);\n }\n\n private static int getColor(Context context, @ColorRes int color) {\n return ContextCompat.getColor(context, color);\n }\n\n public void themeSeekBar(SeekBar bar) {\n bar.getProgressDrawable()\n .setColorFilter(new PorterDuffColorFilter(getAccentColor(), PorterDuff.Mode.SRC_IN));\n bar.getThumb()\n .setColorFilter(new PorterDuffColorFilter(getAccentColor(), PorterDuff.Mode.SRC_IN));\n }\n\n public int getBackgroundColor() {\n switch (baseTheme) {\n case DARK:\n return getColor(R.color.md_dark_background);\n case AMOLED:\n return getColor(R.color.md_black_1000);\n case LIGHT:\n default:\n return getColor(R.color.md_light_background);\n }\n }\n\n public int getInvertedBackgroundColor() {\n switch (baseTheme) {\n case DARK:\n case AMOLED:\n return getColor(R.color.md_light_background);\n case LIGHT:\n default:\n return getColor(R.color.md_dark_background);\n }\n }\n\n public int getTextColor() {\n switch (baseTheme) {\n case DARK:\n case AMOLED:\n return getColor(R.color.md_grey_200);\n case LIGHT:\n default:\n return getColor(R.color.md_grey_800);\n }\n }\n\n public int getSubTextColor() {\n switch (baseTheme) {\n case DARK:\n case AMOLED:\n return getColor(R.color.md_grey_400);\n case LIGHT:\n default:\n return getColor(R.color.md_grey_600);\n }\n }\n\n public int getCardBackgroundColor() {\n switch (baseTheme) {\n case DARK:\n return getColor(R.color.md_dark_cards);\n case AMOLED:\n return getColor(R.color.md_black_1000);\n case LIGHT:\n default:\n return getColor(R.color.md_light_cards);\n }\n }\n\n public int getButtonBackgroundColor() {\n switch (baseTheme) {\n case DARK:\n return getColor(R.color.md_grey_700);\n case AMOLED:\n return getColor(R.color.md_grey_900);\n case LIGHT:\n default:\n return getColor(R.color.md_grey_200);\n }\n }\n\n public int getDrawerBackground() {\n switch (baseTheme) {\n case DARK:\n return getColor(R.color.md_dark_cards);\n case AMOLED:\n return getColor(R.color.md_black_1000);\n case LIGHT:\n default:\n return getColor(R.color.md_light_cards);\n }\n }\n\n public int getDefaultThemeToolbarColor3th() {\n switch (baseTheme) {\n case DARK:\n return getColor(R.color.md_black_1000);\n case LIGHT:\n default:\n case AMOLED:\n return getColor(R.color.md_blue_grey_800);\n }\n }\n\n private ColorStateList getTintList() {\n return new ColorStateList(\n new int[][] {\n new int[] {-android.R.attr.state_enabled}, //disabled\n new int[] {android.R.attr.state_enabled} //enabled\n }, new int[] {getTextColor(), getAccentColor()});\n }\n\n public void themeRadioButton(RadioButton radioButton) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n radioButton.setButtonTintList(getTintList());\n radioButton.setTextColor(getTextColor());\n }\n }\n\n public void themeCheckBox(CheckBox chk) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n chk.setButtonTintList(getTintList());\n chk.setTextColor(getTextColor());\n }\n }\n\n public void themeButton(Button btn) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n btn.setTextColor(getTextColor());\n btn.setBackgroundColor(getButtonBackgroundColor());\n }\n }\n\n public void setSwitchCompactColor(SwitchCompat sw, int color) {\n /** SWITCH HEAD **/\n sw.getThumbDrawable().setColorFilter(\n sw.isChecked() ? color :\n (baseTheme.equals(Theme.LIGHT) ? getColor(R.color.md_grey_200)\n : getColor(R.color.md_grey_600)),\n PorterDuff.Mode.MULTIPLY);\n /** SWITCH BODY **/\n sw.getTrackDrawable().setColorFilter(\n sw.isChecked() ? ColorPalette.getTransparentColor(color, 100) :\n (baseTheme.equals(Theme.LIGHT) ? getColor(R.color.md_grey_400)\n : getColor(R.color.md_grey_900)),\n PorterDuff.Mode.MULTIPLY);\n }\n\n public void setTextViewColor(TextView txt, int color) {\n txt.setTextColor(color);\n }\n\n public void setScrollViewColor(ScrollView scr) {\n try {\n Field mScrollCacheField = View.class.getDeclaredField(\"mScrollCache\");\n mScrollCacheField.setAccessible(true);\n Object mScrollCache = mScrollCacheField.get(scr); // scr is your Scroll View\n\n Field scrollBarField = mScrollCache.getClass().getDeclaredField(\"scrollBar\");\n scrollBarField.setAccessible(true);\n Object scrollBar = scrollBarField.get(mScrollCache);\n\n Method method =\n scrollBar.getClass().getDeclaredMethod(\"setVerticalThumbDrawable\", Drawable.class);\n method.setAccessible(true);\n\n ColorDrawable ColorDraw = new ColorDrawable(getPrimaryColor());\n method.invoke(scrollBar, ColorDraw);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public void setColorScrollBarDrawable(Drawable drawable) {\n drawable.setColorFilter(new PorterDuffColorFilter(getPrimaryColor(), PorterDuff.Mode.SRC_ATOP));\n }\n\n public static void setCursorColor(EditText editText, int color) {\n try {\n Field fCursorDrawableRes =\n TextView.class.getDeclaredField(\"mCursorDrawableRes\");\n fCursorDrawableRes.setAccessible(true);\n int mCursorDrawableRes = fCursorDrawableRes.getInt(editText);\n Field fEditor = TextView.class.getDeclaredField(\"mEditor\");\n fEditor.setAccessible(true);\n Object editor = fEditor.get(editText);\n Class<?> clazz = editor.getClass();\n Field fCursorDrawable = clazz.getDeclaredField(\"mCursorDrawable\");\n fCursorDrawable.setAccessible(true);\n\n Drawable[] drawables = new Drawable[2];\n drawables[0] = ContextCompat.getDrawable(editText.getContext(), mCursorDrawableRes);\n drawables[1] = ContextCompat.getDrawable(editText.getContext(), mCursorDrawableRes);\n drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);\n drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);\n fCursorDrawable.set(editor, drawables);\n } catch (final Throwable ignored) {\n }\n }\n}" ]
import android.animation.FloatEvaluator; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.TextView; import com.jakewharton.rxbinding2.view.RxView; import in.arjsna.audiorecorder.AppConstants; import in.arjsna.audiorecorder.R; import in.arjsna.audiorecorder.activities.PlayListActivity; import in.arjsna.audiorecorder.activities.SettingsActivity; import in.arjsna.audiorecorder.audiovisualization.GLAudioVisualizationView; import in.arjsna.audiorecorder.di.qualifiers.ActivityContext; import in.arjsna.audiorecorder.mvpbase.BaseFragment; import in.arjsna.audiorecorder.recordingservice.AudioRecordService; import in.arjsna.audiorecorder.recordingservice.AudioRecorder; import in.arjsna.audiorecorder.theme.ThemeHelper; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import javax.inject.Inject;
package in.arjsna.audiorecorder.audiorecording; public class RecordFragment extends BaseFragment implements AudioRecordMVPView { private static final String LOG_TAG = RecordFragment.class.getSimpleName(); private FloatingActionButton mRecordButton = null; private FloatingActionButton mPauseButton = null; private GLAudioVisualizationView audioVisualization; private TextView chronometer; private boolean mIsServiceBound = false; private AudioRecordService mAudioRecordService; private ObjectAnimator alphaAnimator; private FloatingActionButton mSettingsButton; private FloatingActionButton mPlayListBtn; @Inject @ActivityContext public Context mContext; @Inject public AudioRecordPresenter<AudioRecordMVPView> audioRecordPresenter; public static RecordFragment newInstance() { return new RecordFragment(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); audioRecordPresenter.onAttach(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View recordView = inflater.inflate(R.layout.fragment_record, container, false); initViews(recordView); bindEvents(); return recordView; } private void bindEvents() { RxView.clicks(mRecordButton) .subscribe(o -> audioRecordPresenter.onToggleRecodingStatus()); RxView.clicks(mSettingsButton)
.subscribe(o -> startActivity(new Intent(mContext, SettingsActivity.class)));
2
onepf/OPFPush
opfpush/src/test/java/org/onepf/opfpush/OPFPushHelperTest.java
[ "@SuppressWarnings(\"PMD.MissingStaticMethodInNonInstantiatableClass\")\npublic final class Configuration {\n\n @NonNull\n private final List<PushProvider> providers;\n\n @Nullable\n private final EventListener eventListener;\n\n @Nullable\n private final CheckManifestHandler checkManifestHandler;\n\n private final boolean isSelectSystemPreferred;\n\n private Configuration(@NonNull final Collection<? extends PushProvider> providers,\n @Nullable final EventListener eventListener,\n final boolean selectSystemPreferred,\n @Nullable CheckManifestHandler checkManifestHandler) {\n this.providers = Collections.unmodifiableList(new ArrayList<>(providers));\n this.eventListener = eventListener;\n this.isSelectSystemPreferred = selectSystemPreferred;\n this.checkManifestHandler = checkManifestHandler;\n }\n\n /**\n * Returns all available push providers.\n *\n * @return All available push providers.\n */\n @NonNull\n public List<PushProvider> getProviders() {\n return providers;\n }\n\n /**\n * Returns the instance of the {@link org.onepf.opfpush.listener.EventListener}.\n *\n * @return The instance of the {@link org.onepf.opfpush.listener.EventListener}.\n */\n @Nullable\n public EventListener getEventListener() {\n return eventListener;\n }\n\n /**\n * Returns {@code true} if the system push provider is preferred, false otherwise.\n *\n * @return {@code true} if the system push provider is preferred, false otherwise.\n */\n public boolean isSelectSystemPreferred() {\n return isSelectSystemPreferred;\n }\n\n /**\n * Returns the instance of the {@link CheckManifestHandler}.\n *\n * @return The instance of the {@link CheckManifestHandler}.\n */\n @Nullable\n public CheckManifestHandler getCheckManifestHandler() {\n return checkManifestHandler;\n }\n\n @Override\n public String toString() {\n return \"Configuration {\"\n + \"providers = \" + providers\n + \", isSelectSystemPreferred = \" + isSelectSystemPreferred\n + '}';\n }\n\n /**\n * The builder class that creates an instance of the {@code Configuration} class.\n */\n public static final class Builder {\n\n @Nullable\n private Map<String, PushProvider> providersMap;\n\n @Nullable\n private EventListener eventListener;\n\n private boolean isSelectSystemPreferred;\n\n @Nullable\n private CheckManifestHandler checkManifestHandler;\n\n /**\n * See {@link #addProviders(java.util.List)}\n *\n * @return The current {@code Builder} instance.\n * @throws java.lang.IllegalArgumentException If a provider was already added\n */\n @NonNull\n public Builder addProviders(@NonNull final PushProvider... providers) {\n if (providers.length == 0) {\n return this;\n } else {\n return addProviders(Arrays.asList(providers));\n }\n }\n\n /**\n * Add push providers to the configuration. The priority of the providers corresponds to the order\n * in which they were added.\n *\n * @return The current {@code Builder} instance.\n * @throws java.lang.IllegalArgumentException If a provider was already added.\n */\n @NonNull\n public Builder addProviders(@NonNull final List<? extends PushProvider> providers) {\n if (providers.isEmpty()) {\n return this;\n }\n\n if (this.providersMap == null) {\n this.providersMap = new LinkedHashMap<>();\n }\n\n for (PushProvider provider : providers) {\n final String providerName = provider.getName();\n if (this.providersMap.containsKey(providerName)) {\n throw new IllegalArgumentException(\n String.format(\"Provider '%s' already added.\", provider)\n );\n } else {\n this.providersMap.put(providerName, provider);\n }\n }\n return this;\n }\n\n @NonNull\n public Builder setEventListener(@NonNull final EventListener eventListener) {\n this.eventListener = eventListener;\n return this;\n }\n\n /**\n * If you set {@code true}, the system push provider will get the highest priority.\n * For Google devices this is Google Cloud Messaging, for Kindle devices - ADM.\n * False by default.\n *\n * @param isSelectSystemPreferred {@code true} if the system provider is preferred, {@code false} otherwise.\n * @return The current {@code Builder}.\n */\n public Builder setSelectSystemPreferred(final boolean isSelectSystemPreferred) {\n this.isSelectSystemPreferred = isSelectSystemPreferred;\n return this;\n }\n\n @NonNull\n public Builder setCheckManifestHandler(@NonNull final CheckManifestHandler checkManifestHandler) {\n this.checkManifestHandler = checkManifestHandler;\n return this;\n }\n\n /**\n * Create the instance of the {@link Configuration} class.\n *\n * @return The new {@link Configuration} object.\n * @throws java.lang.IllegalArgumentException If there are no any added providers.\n */\n @NonNull\n @SuppressWarnings(\"PMD.AccessorClassGeneration\")\n public Configuration build() {\n if (providersMap == null) {\n throw new IllegalArgumentException(\"Need to add at least one push provider.\");\n }\n\n return new Configuration(\n providersMap.values(),\n eventListener,\n isSelectSystemPreferred,\n checkManifestHandler\n );\n }\n\n @Override\n public String toString() {\n return \"Builder{\"\n + \"providersMap=\"\n + providersMap\n + \", systemPushPreferred=\"\n + isSelectSystemPreferred\n + '}';\n }\n }\n}", "public class SimpleEventListener implements EventListener {\n\n @Override\n public void onMessage(@NonNull Context context,\n @NonNull String providerName,\n @Nullable Bundle extras) {\n //nothing\n }\n\n @Override\n public void onDeletedMessages(@NonNull Context context,\n @NonNull String providerName,\n int messagesCount) {\n //nothing\n }\n\n @Override\n public void onRegistered(@NonNull Context context,\n @NonNull String providerName,\n @NonNull String registrationId) {\n //nothing\n }\n\n @Override\n public void onUnregistered(@NonNull Context context,\n @NonNull String providerName,\n @Nullable String registrationId) {\n //nothing\n }\n\n @Override\n public void onNoAvailableProvider(@NonNull Context context,\n @NonNull Map<String, UnrecoverablePushError> pushErrors) {\n //nothing\n }\n}", "@SuppressWarnings(\"PMD.MissingStaticMethodInNonInstantiatableClass\")\npublic final class MockPushProvider implements PushProvider {\n\n private final AvailabilityResult availabilityResult;\n private final String name;\n private final String hostAppPackage;\n private final boolean useOnlyOnError;\n private PushError regError;\n private PushError unregError;\n private String regId;\n\n private MockPushProvider(AvailabilityResult availabilityResult, @NonNull String name,\n @NonNull String hostAppPackage, PushError regError, PushError unregError, boolean useOnlyOnError) {\n this.availabilityResult = availabilityResult;\n this.name = name;\n this.regError = regError;\n this.unregError = unregError;\n this.useOnlyOnError = useOnlyOnError;\n this.hostAppPackage = hostAppPackage;\n }\n\n public void setUnregError(PushError unregError) {\n this.unregError = unregError;\n }\n\n public void setRegError(PushError regError) {\n this.regError = regError;\n }\n\n @Override\n public void register() {\n if (regError == null) {\n regId = Util.getRandomStrings(1, Util.RANDOM_STRING_LENGTH)[0];\n OPFPush.getHelper().getReceivedMessageHandler().onRegistered(name, regId);\n } else {\n if (useOnlyOnError) {\n OPFPush.getHelper().getReceivedMessageHandler().onError(name, regError);\n } else {\n OPFPush.getHelper().getReceivedMessageHandler().onRegistrationError(name, regError);\n }\n }\n }\n\n @Override\n public void unregister() {\n if (unregError == null) {\n final String oldRegId = regId;\n regId = null;\n OPFPush.getHelper().getReceivedMessageHandler().onUnregistered(name, oldRegId);\n } else {\n if (useOnlyOnError) {\n OPFPush.getHelper().getReceivedMessageHandler().onError(name, unregError);\n } else {\n OPFPush.getHelper().getReceivedMessageHandler().onUnregistrationError(name, unregError);\n }\n }\n }\n\n @NonNull\n @Override\n public AvailabilityResult getAvailabilityResult() {\n return availabilityResult;\n }\n\n @Override\n public boolean isRegistered() {\n return regId != null;\n }\n\n @Nullable\n @Override\n public String getRegistrationId() {\n return regId;\n }\n\n @NonNull\n @Override\n public String getName() {\n return name;\n }\n\n @Nullable\n @Override\n public String getHostAppPackage() {\n return hostAppPackage;\n }\n\n @NonNull\n @Override\n public NotificationMaker getNotificationMaker() {\n return new OPFNotificationMaker();\n }\n\n @Override\n public void checkManifest(@Nullable CheckManifestHandler checkManifestHandler) {\n // nothing\n }\n\n @Override\n public void onRegistrationInvalid() {\n regId = null;\n }\n\n @Override\n public void onUnavailable() {\n regId = null;\n }\n\n public static class Builder {\n\n private static final String DEFAULT_HOST_APP_PACKAGE = \"org.onepf.store\";\n\n private AvailabilityResult availabilityResult;\n private String name;\n private String hostAppPackage = DEFAULT_HOST_APP_PACKAGE;\n private PushError regError;\n private PushError unregError;\n private boolean useOnlyOnError;\n\n public Builder setName(final String name) {\n this.name = name;\n return this;\n }\n\n public void setHostAppPackage(String hostAppPackage) {\n this.hostAppPackage = hostAppPackage;\n }\n\n public Builder setRegError(final PushError regError) {\n this.regError = regError;\n return this;\n }\n\n public Builder setUnregError(final PushError unregError) {\n this.unregError = unregError;\n return this;\n }\n\n public Builder setUseOnlyOnError(final boolean useOnlyOnError) {\n this.useOnlyOnError = useOnlyOnError;\n return this;\n }\n\n public Builder setAvailabilityResult(AvailabilityResult availabilityResult) {\n this.availabilityResult = availabilityResult;\n return this;\n }\n\n @SuppressWarnings(\"PMD.AccessorClassGeneration\")\n public MockPushProvider build() {\n if (name == null) {\n throw new IllegalArgumentException(\"Name must be set\");\n }\n return new MockPushProvider(availabilityResult, name, hostAppPackage, regError, unregError, useOnlyOnError);\n }\n }\n}", "public final class AvailabilityResult {\n\n private boolean isAvailable;\n\n @Nullable\n private Integer errorCode;\n\n public AvailabilityResult(final boolean isAvailable) {\n this(isAvailable, null);\n }\n\n public AvailabilityResult(@NonNull final Integer errorCode) {\n this(false, errorCode);\n }\n\n public AvailabilityResult(final boolean isAvailable, @Nullable final Integer errorCode) {\n this.isAvailable = isAvailable;\n this.errorCode = errorCode;\n }\n\n /**\n * Returns {@code true} if a provider is available, false otherwise.\n *\n * @return {@code true} if a provider is available, false otherwise.\n */\n public boolean isAvailable() {\n return isAvailable;\n }\n\n /**\n * Returns a specific provider error code.\n *\n * @return The availability error code, or {@code null} if a provider hasn't returned a error code.\n */\n @Nullable\n public Integer getErrorCode() {\n return errorCode;\n }\n}", "public final class UnrecoverablePushError extends PushError<UnrecoverablePushError.Type> {\n\n @Nullable\n private Integer availabilityErrorCode;\n\n public UnrecoverablePushError(@NonNull final Type type,\n @NonNull final String providerName) {\n this(type, providerName, type.name(), null);\n }\n\n public UnrecoverablePushError(@NonNull final Type type,\n @NonNull final String providerName,\n @NonNull final String errorId) {\n this(type, providerName, errorId, null);\n }\n\n public UnrecoverablePushError(@NonNull final Type type,\n @NonNull final String providerName,\n @NonNull final Integer availabilityErrorCode) {\n this(type, providerName, type.name(), availabilityErrorCode);\n }\n\n public UnrecoverablePushError(@NonNull final Type type,\n @NonNull final String providerName,\n @NonNull final String errorId,\n @Nullable final Integer availabilityErrorCode) {\n super(type, providerName, errorId);\n this.availabilityErrorCode = availabilityErrorCode;\n }\n\n /**\n * Returns an availability error code, or {@code null} if a provider hasn't returned a specific availability error.\n * For GCM it corresponds to the {@code ConnectionResult} codes.\n *\n * @return The error code indicates the specific provider availability error. Can be {@code null}.\n */\n @Nullable\n public Integer getAvailabilityErrorCode() {\n return availabilityErrorCode;\n }\n\n @Override\n public boolean isRecoverable() {\n return false;\n }\n\n @Override\n public String toString() {\n return String.format(\n Locale.US,\n \"UnrecoverablePushError : \\n\"\n + \"{\\\"providerName\\\" : \\\"%1$s\\\",\\n\"\n + \"\\\"type\\\" : \\\"%2$s\\\",\\n\"\n + \"\\\"originalError\\\":\\\"%3$s\\\",\\n\"\n + \"\\\"availabilityErrorCode\\\":\\\"%4$s\\\"}\",\n providerName,\n type,\n originalError,\n availabilityErrorCode);\n }\n\n public enum Type implements ErrorType {\n\n /**\n * Invalid parameters have been sent to register provider.\n */\n INVALID_PARAMETERS,\n\n /**\n * An invalid sender ID has been used for the registration.\n */\n INVALID_SENDER,\n\n /**\n * The authentication failure.\n */\n AUTHENTICATION_FAILED,\n\n /**\n * A provider specific error has occurred while a registration.\n * Look {@link #getOriginalError()} for more information.\n */\n PROVIDER_SPECIFIC_ERROR,\n\n /**\n * Occurred when a provider is unavailable by provider specific error.\n * Use {@link #getAvailabilityErrorCode()} to know about the reason of a provider unavailability.\n */\n AVAILABILITY_ERROR\n }\n}", "public interface PushProvider {\n /**\n * Initiates the registration of the provider. Must be async.\n * <p/>\n * Intended for the internal use, should never be called directly.\n * To start the registration call {@link org.onepf.opfpush.OPFPushHelper#register()}.\n */\n void register();\n\n /**\n * Initiates the unregistering of the provider. Must be async.\n * <p/>\n * Intended for internal use, should never be called directly.\n * To start registration call {@link org.onepf.opfpush.OPFPushHelper#unregister()}.\n */\n void unregister();\n\n /**\n * Checks whether the provider is available.\n *\n * @return The instance of {@link org.onepf.opfpush.model.AvailabilityResult}\n * that contains result of availability check.\n */\n @NonNull\n AvailabilityResult getAvailabilityResult();\n\n /**\n * Checks whether the application was successfully registered on the service.\n *\n * @return {@code true} if the application was successfully registered on the service, otherwise false.\n */\n boolean isRegistered();\n\n /**\n * Returns the registration ID or null if provider isn't registered.\n *\n * @return The registration ID or null if provider isn't registered.\n */\n @Nullable\n String getRegistrationId();\n\n /**\n * Returns the name of the provider. Must be unique for all providers.\n *\n * @return The name of the provider.\n */\n @NonNull\n String getName();\n\n /**\n * Returns the package of the application that contains API of the provider.\n * Usually, this is a store application.\n *\n * @return The package of the application that contains API of the provider.\n */\n @Nullable\n String getHostAppPackage();\n\n /**\n * Returns the {@link NotificationMaker} object associated with provider.\n *\n * @return The {@link NotificationMaker} instance.\n */\n @NonNull\n NotificationMaker getNotificationMaker();\n\n /**\n * Verify that application manifest contains all needed permissions.\n *\n * @param checkManifestHandler If not null an exception isn't thrown.\n * @throws java.lang.IllegalStateException If not all required permissions and components have been\n * described in the AndroidManifest.xml file.\n */\n void checkManifest(@Nullable CheckManifestHandler checkManifestHandler);\n\n /**\n * Callback method, that called when the application state change, like update to new version,\n * or system state changed, like update firmware to a newer version.\n * <p/>\n * If this method is called, your registration becomes invalid\n * and you have to reset all saved registration data.\n */\n void onRegistrationInvalid();\n\n /**\n * Callback method for notify that the provider became unavailable.\n * In this method you have to reset all saved registration data.\n */\n void onUnavailable();\n}" ]
import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import junit.framework.Assert; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.onepf.opfpush.configuration.Configuration; import org.onepf.opfpush.listener.SimpleEventListener; import org.onepf.opfpush.mock.MockPushProvider; import org.onepf.opfpush.model.AvailabilityResult; import org.onepf.opfpush.model.UnrecoverablePushError; import org.onepf.opfpush.pushprovider.PushProvider; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR2;
package org.onepf.opfpush; /** * @author antonpp * @since 14.04.15 */ @Config(sdk = JELLY_BEAN_MR2, manifest = Config.NONE) @RunWith(RobolectricTestRunner.class) public class OPFPushHelperTest extends Assert { private static final String TAG = OPFPushHelperTest.class.getSimpleName(); private static final int BUFFER_INITIAL_CAPACITY = 80; @TargetApi(Build.VERSION_CODES.KITKAT) @After public void eraseSettingsInstance() { Field instanceField; synchronized (Settings.class) { try { instanceField = Settings.class.getDeclaredField("instance"); instanceField.setAccessible(true); instanceField.set(null, null); } catch (IllegalAccessException | NoSuchFieldException e) { Log.e(TAG, e.getMessage()); } } } @TargetApi(Build.VERSION_CODES.KITKAT) @Test public void testGetProviderName() { final String expected = "Courier"; final PushProvider provider = new MockPushProvider.Builder() .setName(expected)
.setAvailabilityResult(new AvailabilityResult(true))
3
grennis/MongoExplorer
app/src/main/java/com/innodroid/mongobrowser/ui/ConnectionEditDialogFragment.java
[ "public class Constants {\n\tpublic static final String LOG_TAG = \"mongoexp\";\n\n\tpublic static final String ARG_CONNECTION_ID = \"connid\";\n\tpublic static final String ARG_COLLECTION_INDEX = \"collname\";\n\tpublic static final String ARG_ACTIVATE_ON_CLICK = \"actonclick\";\n\tpublic static final String ARG_DOCUMENT_TITLE = \"doctitle\";\n\tpublic static final String ARG_DOCUMENT_INDEX = \"doccontent\";\n\tpublic static final String ARG_CONTENT = \"thecontent\";\n\n\tpublic static final long SLIDE_ANIM_DURATION = 600;\n\t\n\tpublic static final String NEW_DOCUMENT_CONTENT = \"{\\n \\n}\\n\";\n\tpublic static final String NEW_DOCUMENT_CONTENT_PADDED = \"{\\n \\n}\\n\\n\\n\\n\\n\";\n}", "public class Events {\n public static void postAddConnection() {\n EventBus.getDefault().post(new AddConnection());\n }\n\n public static void postConnectionSelected(long connectionID) {\n EventBus.getDefault().post(new ConnectionSelected(connectionID));\n }\n\n public static void postConnected(long connectionID) {\n EventBus.getDefault().post(new Connected(connectionID));\n }\n\n public static void postConnectionDeleted() {\n EventBus.getDefault().post(new ConnectionDeleted());\n }\n\n public static void postCollectionSelected(long connectionId, int index) {\n EventBus.getDefault().post(new CollectionSelected(connectionId, index));\n }\n\n public static void postAddDocument() {\n EventBus.getDefault().post(new AddDocument());\n }\n\n public static void postDocumentSelected(int index) {\n EventBus.getDefault().post(new DocumentSelected(index));\n }\n\n public static void postDocumentClicked(int index) {\n EventBus.getDefault().post(new DocumentClicked(index));\n }\n\n public static void postCreateCollection(String name) {\n EventBus.getDefault().post(new CreateCollection(name));\n }\n\n public static void postRenameCollection(String name) {\n EventBus.getDefault().post(new RenameCollection(name));\n }\n\n public static void postCollectionRenamed(String name) {\n EventBus.getDefault().post(new CollectionRenamed(name));\n }\n\n public static void postCollectionDropped() {\n EventBus.getDefault().post(new CollectionDropped());\n }\n\n public static void postConnectionAdded(long connectionId) {\n EventBus.getDefault().post(new ConnectionAdded(connectionId));\n }\n\n public static void postConnectionUpdated(long connectionId) {\n EventBus.getDefault().post(new ConnectionUpdated(connectionId));\n }\n\n public static void postEditDocument(int index) {\n EventBus.getDefault().post(new EditDocument(index));\n }\n\n public static void postDocumentEdited(int index) {\n EventBus.getDefault().post(new DocumentEdited(index));\n }\n\n public static void postDocumentCreated(String content) {\n EventBus.getDefault().post(new DocumentCreated(content));\n }\n\n public static void postDocumentDeleted() {\n EventBus.getDefault().post(new DocumentDeleted());\n }\n\n public static void postChangeDatabase(String name) {\n EventBus.getDefault().post(new ChangeDatabase(name));\n }\n\n public static void postQueryNamed(String name) {\n EventBus.getDefault().post(new QueryNamed(name));\n }\n\n public static void postQueryUpdated(String query) {\n EventBus.getDefault().post(new QueryUpdated(query));\n }\n\n public static void postSettingsChanged() {\n EventBus.getDefault().post(new SettingsChanged());\n }\n\n public static class AddConnection {\n }\n\n public static class AddDocument {\n }\n\n public static class DocumentDeleted {\n }\n\n public static class ConnectionSelected {\n public long ConnectionId;\n\n public ConnectionSelected(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class ConnectionDeleted {\n }\n\n public static class Connected {\n public long ConnectionId;\n\n public Connected(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class CollectionSelected {\n public long ConnectionId;\n public int Index;\n\n public CollectionSelected(long connectionId, int index) {\n ConnectionId = connectionId;\n Index = index;\n }\n }\n\n public static class DocumentSelected {\n public int Index;\n\n public DocumentSelected(int index) {\n Index = index;\n }\n }\n\n public static class DocumentClicked {\n public int Index;\n\n public DocumentClicked(int index) {\n Index = index;\n }\n }\n\n public static class EditDocument {\n public int Index;\n\n public EditDocument(int index) {\n Index = index;\n }\n }\n\n public static class DocumentCreated {\n public String Content;\n\n public DocumentCreated(String content) {\n Content = content;\n }\n }\n\n public static class ChangeDatabase {\n public String Name;\n\n public ChangeDatabase(String name) {\n Name = name;\n }\n }\n\n public static class QueryNamed {\n public String Name;\n\n public QueryNamed(String name) {\n Name = name;\n }\n }\n\n public static class QueryUpdated {\n public String Content;\n\n public QueryUpdated(String content) {\n Content = content;\n }\n }\n\n public static class DocumentEdited {\n public int Index;\n\n public DocumentEdited(int index) {\n Index = index;\n }\n }\n\n public static class CollectionRenamed {\n public String Name;\n\n public CollectionRenamed(String name) {\n Name = name;\n }\n }\n\n public static class RenameCollection {\n public String Name;\n\n public RenameCollection(String name) {\n Name = name;\n }\n }\n\n public static class CreateCollection {\n public String Name;\n\n public CreateCollection(String name) {\n Name = name;\n }\n }\n\n public static class CollectionDropped {\n }\n\n public static class ConnectionAdded {\n public long ConnectionId;\n\n public ConnectionAdded(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class ConnectionUpdated {\n public long ConnectionId;\n\n public ConnectionUpdated(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class SettingsChanged {\n }\n}", "public class MongoBrowserProvider extends ContentProvider {\n\n\tprivate static final String LOG_TAG = \"MongoBrowserProvider\";\n\tprivate static final String DATABASE_NAME = \"mongobrowser.db\";\n\tpublic static final String TABLE_NAME_CONNECTIONS = \"connections\";\n\tpublic static final String TABLE_NAME_QUERIES = \"queries\";\n\tprivate static final int DATABASE_VERSION = 20;\n\n\tpublic static final int INDEX_CONNECTION_ID = 0;\n\tpublic static final int INDEX_CONNECTION_NAME = 1;\n\tpublic static final int INDEX_CONNECTION_SERVER = 2;\n public static final int INDEX_CONNECTION_PORT = 3; \n public static final int INDEX_CONNECTION_DB = 4; \n\tpublic static final int INDEX_CONNECTION_USER = 5;\n\tpublic static final int INDEX_CONNECTION_PASSWORD = 6;\n\tpublic static final int INDEX_CONNECTION_FLAGS = 7;\n\tpublic static final int INDEX_CONNECTION_LAST_CONNECT = 8;\n\t\n\tpublic static final String NAME_CONNECTION_NAME = \"name\";\n\tpublic static final String NAME_CONNECTION_SERVER = \"server\";\n public static final String NAME_CONNECTION_PORT = \"port\"; \n public static final String NAME_CONNECTION_DB = \"dbname\"; \n\tpublic static final String NAME_CONNECTION_USER = \"usernm\";\n\tpublic static final String NAME_CONNECTION_PASSWORD = \"pass\";\n\tpublic static final String NAME_CONNECTION_FLAGS = \"cflags\";\n\tpublic static final String NAME_CONNECTION_LAST_CONNECT = \"lastconn\";\n\n\tpublic static final int INDEX_QUERY_ID = 0;\n\tpublic static final int INDEX_QUERY_NAME = 1;\n\tpublic static final int INDEX_QUERY_CONN_ID = 2;\n\tpublic static final int INDEX_QUERY_COLL_NAME = 3;\n\tpublic static final int INDEX_QUERY_TEXT = 4;\n\t\n\tpublic static final String NAME_QUERY_NAME = \"qname\";\n\tpublic static final String NAME_QUERY_CONN_ID = \"connid\";\n\tpublic static final String NAME_QUERY_COLL_NAME = \"coll\";\n\tpublic static final String NAME_QUERY_TEXT = \"qtext\";\n\n\t//setup authority for provider\n\tprivate static final String AUTHORITY = \"com.innodroid.provider.mongobrowser\";\n\n\t//URI's to consume this provider\n\tpublic static final Uri CONNECTION_URI = Uri.parse(\"content://\" + AUTHORITY + \"/connections\");\n\tpublic static final String CONNECTION_ITEM_TYPE = \"vnd.android.cursor.item/vnd.innodroid.connection\";\n public static final String CONNECTION_LIST_TYPE = \"vnd.android.cursor.dir/vnd.innodroid.connection\";\n\n\tpublic static final Uri QUERY_URI = Uri.parse(\"content://\" + AUTHORITY + \"/queries\");\n\tpublic static final String QUERY_ITEM_TYPE = \"vnd.android.cursor.item/vnd.innodroid.query\";\n public static final String QUERY_LIST_TYPE = \"vnd.android.cursor.dir/vnd.innodroid.query\";\n\n //Create the statics used to differentiate between the different URI requests\n private static final int CONNECTION_ONE = 1; \n private static final int CONNECTION_ALL = 2;\n private static final int QUERY_ONE = 3; \n private static final int QUERY_ALL = 4;\n\n\t//database members\n\tprivate SQLiteOpenHelper mOpenHelper;\n private SQLiteDatabase mDatabase;\n\n\tprivate static final UriMatcher URI_MATCHER;\n\t\n static \n\t{\n URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);\n\n URI_MATCHER.addURI(AUTHORITY, \"connections/#\", CONNECTION_ONE);\n URI_MATCHER.addURI(AUTHORITY, \"connections\", CONNECTION_ALL);\n URI_MATCHER.addURI(AUTHORITY, \"queries/#\", QUERY_ONE);\n URI_MATCHER.addURI(AUTHORITY, \"queries\", QUERY_ALL);\n }\n\n\t@Override\n\tpublic boolean onCreate() {\n\t\t mOpenHelper = new DatabaseHelper(getContext());\n\t\t mDatabase = mOpenHelper.getWritableDatabase();\n\t\t return true;\n\t}\n\n\t@Override\n\tpublic String getType(Uri uri) {\n\t\tswitch (URI_MATCHER.match(uri)) {\n\t\t\tcase CONNECTION_ALL:\n\t\t\t\treturn CONNECTION_LIST_TYPE;\n\t\t\tcase CONNECTION_ONE:\n\t\t\t\treturn CONNECTION_ITEM_TYPE;\n\t\t\tcase QUERY_ALL:\n\t\t\t\treturn QUERY_LIST_TYPE;\n\t\t\tcase QUERY_ONE:\n\t\t\t\treturn QUERY_ITEM_TYPE;\n\t\t\tdefault: \n\t\t\t\tthrow new IllegalArgumentException(\"Unsupported URI:\" + uri);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {\n\t\tCursor cursor;\n\t\t\n\t\tswitch (URI_MATCHER.match(uri)) {\n\t\t\tcase CONNECTION_ALL:\n\t\t\t\tcursor = mDatabase.query(TABLE_NAME_CONNECTIONS, projection, selection, selectionArgs, null, null, sortOrder);\n\t\t\t\tbreak;\n\t\t\tcase CONNECTION_ONE:\n\t\t\t\tString xid = uri.getPathSegments().get(1);\n\t\t\t\tcursor = mDatabase.query(TABLE_NAME_CONNECTIONS, projection, BaseColumns._ID + \" = ?\", new String[] { xid }, null, null, sortOrder);\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ALL:\n\t\t\t\tcursor = mDatabase.query(TABLE_NAME_QUERIES, projection, selection, selectionArgs, null, null, sortOrder);\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ONE:\n\t\t\t\tString yid = uri.getPathSegments().get(1);\n\t\t\t\tcursor = mDatabase.query(TABLE_NAME_QUERIES, projection, BaseColumns._ID + \" = ?\", new String[] { yid }, null, null, sortOrder);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unsupported URI:\" + uri);\t\t\t\t\n\t\t}\n\t\t\n\t\tcursor.setNotificationUri(getContext().getContentResolver(), uri);\t\t\t\t\t\n\t\treturn cursor;\n\t}\n\n\t@Override\n\tpublic Uri insert(Uri uri, ContentValues values) {\n\t\tString table;\n\t\tUri newUri;\n\t\t\n\t\tswitch (URI_MATCHER.match(uri)) {\n\t\t\tcase CONNECTION_ALL:\n\t\t\t\ttable = TABLE_NAME_CONNECTIONS;\n\t\t\t\tnewUri = CONNECTION_URI;\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ALL:\n\t\t\t\ttable = TABLE_NAME_QUERIES;\n\t\t\t\tnewUri = QUERY_URI;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unknown URI \" + uri);\t\t\t\n\t\t}\n\n\t\tlong id = mDatabase.insert(table, null, values);\n\t\tnewUri = ContentUris.withAppendedId(newUri, id);\n\t\tgetContext().getContentResolver().notifyChange(newUri, null);\n\t\tLog.d(LOG_TAG, \"Insert \" + id);\n\n\t\treturn newUri;\n\t}\n\t\n\t@Override\n\tpublic int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {\n\t\tint count = 0;\n\t\t\n\t\tswitch (URI_MATCHER.match(uri))\n\t\t{\n\t\t\tcase CONNECTION_ALL:\n\t\t\t\tcount = mDatabase.update(TABLE_NAME_CONNECTIONS, values, selection, selectionArgs);\n\t\t\t\tbreak;\n\t\t\tcase CONNECTION_ONE:\n\t\t\t\tString xid = uri.getPathSegments().get(1);\n\t\t\t\tcount = mDatabase.update(TABLE_NAME_CONNECTIONS, values, BaseColumns._ID + \" = ?\", new String[] { xid });\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ALL:\n\t\t\t\tcount = mDatabase.update(TABLE_NAME_QUERIES, values, selection, selectionArgs);\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ONE:\n\t\t\t\tString yid = uri.getPathSegments().get(1);\n\t\t\t\tcount = mDatabase.update(TABLE_NAME_QUERIES, values, BaseColumns._ID + \" = ?\", new String[] { yid });\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unsupported URI:\" + uri);\t\t\t\t\n\t\t}\n\n\t\tgetContext().getContentResolver().notifyChange(uri, null);\n\t\treturn count;\n\t}\n\n\t@Override\n\tpublic int delete(Uri uri, String where, String[] whereArgs) {\n\t\tint count=0;\n\n\t\tswitch (URI_MATCHER.match(uri))\n\t\t{\n\t\t\tcase CONNECTION_ALL:\n\t\t\t\tcount = mDatabase.delete(TABLE_NAME_CONNECTIONS, where, whereArgs);\n\t\t\t\tbreak;\n\t\t\tcase CONNECTION_ONE:\n\t\t\t\tString xid = uri.getPathSegments().get(1);\n\t\t\t\tcount = mDatabase.delete(TABLE_NAME_CONNECTIONS, BaseColumns._ID + \" = ?\", new String[] { xid });\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ALL:\n\t\t\t\tcount = mDatabase.delete(TABLE_NAME_QUERIES, where, whereArgs);\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ONE:\n\t\t\t\tString yid = uri.getPathSegments().get(1);\n\t\t\t\tcount = mDatabase.delete(TABLE_NAME_QUERIES, BaseColumns._ID + \" = ?\", new String[] { yid });\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unsupported URI:\" + uri);\t\t\t\t\n\t\t}\n\t\t\n\t\tgetContext().getContentResolver().notifyChange(uri, null);\n\t\treturn count;\n\t}\n\n\tprivate static class DatabaseHelper extends SQLiteOpenHelper {\n\t\tDatabaseHelper(Context context) {\n\t\t\tsuper(context, DATABASE_NAME, null, DATABASE_VERSION);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onCreate(SQLiteDatabase db) {\n\t\t createDatabase(db);\n\t\t}\n\n\t\tprivate void createDatabase(SQLiteDatabase db) {\n\t\t\tcreateConnectionsTable(db);\n\t\t\tcreateQueriesTable(db);\n\n\t\t\t/*\n\t\t\tinsertConnection(db, \"Lumenbox DEV\", \"dbh61.mongolab.com\", 27617, \"lumenbox_dev\", \"lumenuser\", \"hellolumen\");\n\t\t\tinsertConnection(db, \"Lumenbox PROD\", \"ds031277.mongolab.com\", 31277, \"lumenbox\", \"user\", \"user\");\n\t\t\tinsertConnection(db, \"imMeta DEV\", \"ds031637.mongolab.com\", 31637, \"immeta_dev\", \"imm3ta\", \"passw0rd\");\n\t\t\tinsertConnection(db, \"imMeta PROD\", \"ds029817.mongolab.com\", 29817, \"immeta_prod\", \"pr0dm3ta\", \"passw0rd\");\n\t\t\tinsertConnection(db, \"atWork DEV\", \"ds033487.mongolab.com\", 33487, \"atwork_dev\", \"atwork\", \"!hello1!\");\n\t\t\tinsertConnection(db, \"guag\", \"alex.mongohq.com\", 10053, \"getupandgreen\", \"admin\", \"hello123\");\t\n\t\t\t*/\t\n\t\t\t\n\t\t\t/* This used for screenshots */\n\t\t\t/*\n\t\t\tinsertConnection(db, \"Demo App QA\", \"demo.mongolab.com\", 57323, \"demo_qa\", \"app_login\", \"passw0rd\");\n\t\t\tinsertConnection(db, \"Demo App PROD\", \"demo.mongolab.com\", 33487, \"atwork_dev\", \"atwork\", \"!hello1!\");\n\t\t\tinsertConnection(db, \"Support Database\", \"alex.mongohq.com\", 10007, \"support\", \"app_login\", \"hello123\");\t\t\n\t\t\t */\t\t\t\n\t\t}\n\n\t\tprivate void createConnectionsTable(SQLiteDatabase db) {\n\t\t\tLog.w(LOG_TAG, \"Creating a new table - \" + TABLE_NAME_CONNECTIONS);\n\t\t\tdb.execSQL(\n\t\t\t\t\"CREATE TABLE \" + TABLE_NAME_CONNECTIONS + \"(\" + BaseColumns._ID + \" INTEGER PRIMARY KEY, \" \n\t\t\t\t + NAME_CONNECTION_NAME + \" TEXT, \"\n\t\t\t\t + NAME_CONNECTION_SERVER + \" TEXT, \"\n\t\t\t\t + NAME_CONNECTION_PORT + \" INTEGER, \"\n\t\t\t\t + NAME_CONNECTION_DB + \" TEXT, \"\n\t\t\t\t + NAME_CONNECTION_USER + \" TEXT, \"\n\t\t\t\t + NAME_CONNECTION_PASSWORD + \" TEXT, \"\n\t\t\t\t + NAME_CONNECTION_FLAGS + \" INTEGER, \"\n\t\t\t\t + NAME_CONNECTION_LAST_CONNECT + \" INTEGER\"\n\t\t\t\t + \" );\"\n\t\t\t);\t\t\t\n\t\t}\n\n\t\tprivate void createQueriesTable(SQLiteDatabase db) {\n\t\t\tLog.w(LOG_TAG, \"Creating a new table - \" + TABLE_NAME_QUERIES);\n\t\t\tdb.execSQL(\n\t\t\t\t\"CREATE TABLE \" + TABLE_NAME_QUERIES + \"(\" + BaseColumns._ID + \" INTEGER PRIMARY KEY, \" \n\t\t\t\t + NAME_QUERY_NAME + \" TEXT, \"\n\t\t\t\t + NAME_QUERY_CONN_ID + \" INTEGER, \"\n\t\t\t\t + NAME_QUERY_COLL_NAME + \" TEXT, \"\n\t\t\t\t + NAME_QUERY_TEXT + \" TEXT\"\n\t\t\t\t + \" );\"\n\t\t\t);\t\t\t\n\t\t}\n\t\t\n/*\n\t\tprivate long insertConnection(SQLiteDatabase dbx, String name, String server, int port, String db, String user, String pass) {\n\t\t\tContentValues cv = MongoBrowserProviderHelper.getContentValuesForConnection(name, server, port, db, user, pass);\n\t\t\treturn dbx.insert(TABLE_NAME_CONNECTIONS, null, cv);\n\t\t}\n*/\n\t\t\n\t\t@Override\n\t\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\tLog.w(LOG_TAG, \"Upgrade database\");\n\n\t\t\tif (oldVersion < 20) {\n\t\t\t\tcreateQueriesTable(db);\n\t\t\t}\n\t\t}\n\t}\n}", "public class MongoBrowserProviderHelper {\n\tprivate static final String LOG_TAG = \"MongoBrowserProviderHelper\";\n\tprivate ContentResolver mResolver;\n\n\tpublic MongoBrowserProviderHelper(ContentResolver resolver) {\n\t\tmResolver = resolver;\n\t}\n\n\tpublic long addConnection(String name, String server, int port, String db, String user, String pass) {\n\t\tLog.i(LOG_TAG, \"Adding Connection\");\n\n\t\tContentValues values = getContentValuesForConnection(name, server, port, db, user, pass);\n\t\tUri uri = mResolver.insert(MongoBrowserProvider.CONNECTION_URI, values);\n\t\treturn ContentUris.parseId(uri);\n\t}\n\t\n\tpublic void updateConnection(long id, String name, String server, int port, String db, String user, String pass) {\n\t\tLog.i(LOG_TAG, \"Updating Connection\");\n\n\t\tContentValues values = getContentValuesForConnection(name, server, port, db, user, pass);\n\t\tmResolver.update(MongoBrowserProvider.CONNECTION_URI, values, BaseColumns._ID + \" = ?\", new String[] { Long.toString(id) });\n\t}\n\n\tpublic void updateConnectionLastConnect(long id) {\n\t\tLog.i(LOG_TAG, \"Updating Connection\");\n\t\tlong lastConnect = System.currentTimeMillis();\n\n\t\tContentValues cv = new ContentValues();\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_LAST_CONNECT, lastConnect);\n\t\tmResolver.update(MongoBrowserProvider.CONNECTION_URI, cv, BaseColumns._ID + \" = ?\", new String[] { Long.toString(id) });\n\t}\n\n\tpublic long saveQuery(long id, String name, long connectionId, String collectionName, String text) {\n\t\tLog.i(LOG_TAG, \"Saving query\");\n\n\t\tContentValues cv = new ContentValues();\n\t\tcv.put(MongoBrowserProvider.NAME_QUERY_TEXT, text);\n\t\tcv.put(MongoBrowserProvider.NAME_QUERY_NAME, name);\n\t\tcv.put(MongoBrowserProvider.NAME_QUERY_CONN_ID, connectionId);\n\t\tcv.put(MongoBrowserProvider.NAME_QUERY_COLL_NAME, collectionName);\n\n\t\tif (id > 0) {\n\t\t\tUri uri = ContentUris.withAppendedId(MongoBrowserProvider.QUERY_URI, id);\n\t\t\tmResolver.update(uri, cv, null, null);\n\t\t\treturn id;\n\t\t} else {\n\t\t\tUri result = mResolver.insert(MongoBrowserProvider.QUERY_URI, cv);\t\t\t\n\t\t\treturn Long.parseLong(result.getLastPathSegment());\n\t\t}\n\t}\n\n\tpublic void deleteConnection(long id) {\n\t\tLog.i(LOG_TAG, \"Deleting Connection\");\n\n\t\tmResolver.delete(MongoBrowserProvider.CONNECTION_URI, BaseColumns._ID + \" = ?\", new String[] { Long.toString(id) });\n\t}\n\n\tpublic int deleteAllConnections() {\n\t\tLog.i(LOG_TAG, \"Deleting all Connections\");\n\t\treturn mResolver.delete(MongoBrowserProvider.CONNECTION_URI, null, null);\n\t}\n\t\n\tpublic Cursor findQuery(String name, long connectionId, String collectionName) {\n\t\treturn mResolver.query(MongoBrowserProvider.QUERY_URI, null, MongoBrowserProvider.NAME_QUERY_NAME + \" = ? and \" + MongoBrowserProvider.NAME_QUERY_CONN_ID + \" = ? and \" + MongoBrowserProvider.NAME_QUERY_COLL_NAME + \" = ?\", new String[] { name, Long.toString(connectionId), collectionName }, null);\n\t}\n\t\n\tpublic Cursor getNamedQueries(long connectionId, String collectionName) {\n\t\treturn mResolver.query(MongoBrowserProvider.QUERY_URI, null, MongoBrowserProvider.NAME_QUERY_CONN_ID + \" = ? and \" + MongoBrowserProvider.NAME_QUERY_COLL_NAME + \" = ?\", new String[] { Long.toString(connectionId), collectionName }, null);\n\t}\n\n\tpublic static ContentValues getContentValuesForConnection(String name, String server, int port, String db, String user, String pass) {\n\t\tContentValues cv = new ContentValues();\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_NAME, name);\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_SERVER, server);\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_PORT, port);\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_DB, db);\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_USER, user);\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_PASSWORD, pass);\n\t\treturn cv;\n\t}\n\n\tpublic int getConnectionCount() {\n\t\tCursor cursor = mResolver.query(MongoBrowserProvider.CONNECTION_URI, null, null, null, null);\n\t\tint count = cursor.getCount();\n\t\tcursor.close();\n\t\treturn count;\n\t}\n}", "public class UiUtils {\n\tpublic interface AlertDialogCallbacks {\n\t\tboolean onOK();\n\t\tboolean onNeutralButton();\n\t}\n\t\n\tpublic interface ConfirmCallbacks {\n\t\tboolean onConfirm();\n\t}\n\n\tpublic static AlertDialogCallbacks EmptyAlertCallbacks = new AlertDialogCallbacks() {\n\t\t@Override\n\t\tpublic boolean onOK() {\n\t\t\treturn true;\n\t\t}\t\t\n\n\t\t@Override\n\t\tpublic boolean onNeutralButton() {\n\t\t\treturn true;\n\t\t}\t\t\n\t};\n\t\n\tpublic static Dialog buildAlertDialog(View view, int icon, int title, boolean hasCancel, int middleButtonText, final AlertDialogCallbacks callbacks) {\n\t\treturn buildAlertDialog(view, icon, view.getResources().getString(title), hasCancel, middleButtonText, callbacks);\n\t}\n\t\n\tpublic static Dialog buildAlertDialog(View view, int icon, String title, boolean hasCancel, int middleButtonText, final AlertDialogCallbacks callbacks) {\n AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext())\n\t .setIcon(icon)\n\t .setView(view)\n\t .setTitle(title)\n\t .setPositiveButton(android.R.string.ok,\n\t new DialogInterface.OnClickListener() {\n\t public void onClick(DialogInterface dialog, int whichButton) {\n\t }\n\t }\n\t );\n \n if (hasCancel) {\n\t builder.setCancelable(true).setNegativeButton(android.R.string.cancel,\n\t\t new DialogInterface.OnClickListener() {\n\t\t public void onClick(DialogInterface dialog, int whichButton) {\n\t\t }\n\t\t }\n\t\t ); \t\n }\n\n if (middleButtonText != 0) {\n\t builder.setNeutralButton(middleButtonText,\n\t\t new DialogInterface.OnClickListener() {\n\t\t public void onClick(DialogInterface dialog, int whichButton) {\n\t\t }\n\t\t }\n\t\t ); \t\n }\n\n final AlertDialog dialog = builder.create();\n\n dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface di) {\n Button b = dialog.getButton(AlertDialog.BUTTON_POSITIVE);\n b.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n \tif (callbacks.onOK())\n \t\tdialog.dismiss();\n }\n });\n\n b = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);\n b.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n \tif (callbacks.onNeutralButton())\n \t\tdialog.dismiss();\n }\n });\n }\n }); \n \n return dialog;\n\t}\n\t\n\tpublic static Dialog buildAlertDialog(Context context, ListAdapter adapter, OnClickListener listener, int icon, String title) {\n AlertDialog.Builder builder = new AlertDialog.Builder(context)\n\t .setIcon(icon)\n\t .setAdapter(adapter, listener)\n\t .setTitle(title);\n \n builder.setCancelable(true);\n\n final AlertDialog dialog = builder.create();\n\n return dialog;\n\t}\n\n\tpublic static void message(Context context, int title, int message) {\n DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() {\n\t\t\tpublic void onClick(DialogInterface dialog, int whichButton) {\n\t\t\t}\n\t\t};\n\n\t\tmessage(context, title, message, onClick);\n\t}\n\n\tpublic static void message(Context context, int title, int message, DialogInterface.OnClickListener onClick) {\n\t\tnew AlertDialog.Builder(context)\n\t\t\t\t.setIcon(R.drawable.ic_info_black)\n\t\t\t\t.setMessage(message)\n\t\t\t\t.setTitle(title)\n\t\t\t\t.setCancelable(true)\n\t\t\t\t.setPositiveButton(android.R.string.ok, onClick)\n\t\t\t\t.create().show();\n\t}\n\n\tpublic static void confirm(Context context, int message, final ConfirmCallbacks callbacks) {\n new AlertDialog.Builder(context)\n\t .setIcon(R.drawable.ic_warning_black)\n\t .setMessage(message)\n\t .setTitle(R.string.title_confirm)\n\t .setCancelable(true)\n\t .setPositiveButton(android.R.string.ok,\n\t\t\t\t\tnew DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int whichButton) {\n\t\t\t\t\t\t\tcallbacks.onConfirm();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t)\n\t .setNegativeButton(android.R.string.cancel,\n\t\t\t\t\tnew DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int whichButton) {\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t)\n\t .create().show();\n\t}\n\n\tpublic static String getAppVersionString(Context context) {\n\t\ttry {\n\t\t\tPackageInfo info = context.getApplicationContext().getPackageManager().getPackageInfo(context.getPackageName(), 0);\n\t\t\treturn \"v\" + info.versionName + \" (Build \" + info.versionCode + \")\";\n\t\t} catch (PackageManager.NameNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn \"\";\n\t\t}\n\t}\n}" ]
import android.app.Activity; import android.app.Dialog; import android.content.ContentUris; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.innodroid.mongobrowser.Constants; import com.innodroid.mongobrowser.Events; import com.innodroid.mongobrowser.R; import com.innodroid.mongobrowser.data.MongoBrowserProvider; import com.innodroid.mongobrowser.data.MongoBrowserProviderHelper; import com.innodroid.mongobrowser.util.UiUtils; import butterknife.Bind;
package com.innodroid.mongobrowser.ui; public class ConnectionEditDialogFragment extends BaseDialogFragment implements LoaderCallbacks<Cursor> { @Bind(R.id.edit_connection_name) TextView mNameView; @Bind(R.id.edit_connection_server) TextView mServerView; @Bind(R.id.edit_connection_port) TextView mPortView; @Bind(R.id.edit_connection_db) TextView mDatabaseView; @Bind(R.id.edit_connection_user) TextView mUserView; @Bind(R.id.edit_connection_pass) TextView mPasswordView; public ConnectionEditDialogFragment() { super(); } public static ConnectionEditDialogFragment newInstance(long id) { ConnectionEditDialogFragment fragment = new ConnectionEditDialogFragment(); Bundle args = new Bundle(); args.putLong(Constants.ARG_CONNECTION_ID, id); fragment.setArguments(args); return fragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View view = super.onCreateDialog(R.layout.fragment_connection_edit); long id = getArguments().getLong(Constants.ARG_CONNECTION_ID, 0); if (id != 0) getLoaderManager().initLoader(0, getArguments(), this); return UiUtils.buildAlertDialog(view, R.drawable.ic_mode_edit_black, R.string.title_edit_connection, true, 0, new UiUtils.AlertDialogCallbacks() { @Override public boolean onOK() { return save(); } @Override public boolean onNeutralButton() { return false; } }); } private boolean save() { String name = mNameView.getText().toString(); String server = mServerView.getText().toString(); String porttxt = mPortView.getText().toString(); String db = mDatabaseView.getText().toString(); String user = mUserView.getText().toString(); String pass = mPasswordView.getText().toString(); if (name.length() == 0 || server.length() == 0 || porttxt.length() == 0 || db.length() == 0) { Toast.makeText(getActivity(), "Required values not provided", Toast.LENGTH_SHORT).show(); return false; } int port = 0; try { port = Integer.parseInt(porttxt); } catch (Exception e) { Toast.makeText(getActivity(), "Port must be a number", Toast.LENGTH_SHORT).show(); return false; } MongoBrowserProviderHelper helper = new MongoBrowserProviderHelper(getActivity().getContentResolver()); long id = getArguments().getLong(Constants.ARG_CONNECTION_ID, 0); if (id == 0) { id = helper.addConnection(name, server, port, db, user, pass);
Events.postConnectionAdded(id);
1
kecskemeti/dissect-cf
src/test/java/at/ac/uibk/dps/cloud/simulator/test/simple/cloud/ResourceConsumptionTest.java
[ "public abstract class Timed implements Comparable<Timed> {\n\n\t/**\n\t * The main container for all recurring events in the system\n\t */\n\tprivate static final PriorityQueue<Timed> timedlist = new PriorityQueue<Timed>();\n\t/**\n\t * If set to true, the event loop is processing this object at the moment.\n\t */\n\tprivate boolean underProcessing = false;\n\t/**\n\t * The actual time in the system. This is maintained in ticks!\n\t */\n\tprivate static long fireCounter = 0;\n\n\t/**\n\t * Determines if the actual timed object is going to receive recurring events\n\t * (through the tick() function).\n\t */\n\tprivate boolean activeSubscription = false;\n\t/**\n\t * Specifies the next time (in ticks) when the recurring event should be fired.\n\t * This is used to order the elements in the timedList event list.\n\t */\n\tprivate long nextEvent = 0;\n\t/**\n\t * The number of ticks that should pass between two tick() calls.\n\t * \n\t * This field is usually a positive number, if it is -1 then the frequency is\n\t * not yet initialized by the class.\n\t */\n\tprivate long frequency = -1;\n\t/**\n\t * Should two timed events occur on the same time instance this marker allows\n\t * Timed to determine which ones should be notified first.\n\t * \n\t * if this is true then all timed events (except other backpreferred ones) on\n\t * the same time instance will be fired first before this one is called. Just\n\t * like regular events, the notification order of backpreferred events is not\n\t * fixed!\n\t */\n\tprivate boolean backPreference = false;\n\n\t/**\n\t * Allows to determine if a particular timed object is receiving notifications\n\t * from the system\n\t * \n\t * @return\n\t * <ul>\n\t * <li><i>true</i> if this object will receive recurrign events in the\n\t * future\n\t * <li><i>false</i> otherwise\n\t * </ul>\n\t */\n\tpublic final boolean isSubscribed() {\n\t\treturn activeSubscription;\n\t}\n\n\t/**\n\t * Allows Timed objects to subscribe for recurring events with a particular\n\t * frequency. This function is protected so no external entities should be able\n\t * to modify the subscription for a timed object.\n\t * \n\t * @param freq the event frequency with which the tick() function should be\n\t * called on the particular implementation of timed.\n\t * @return\n\t * <ul>\n\t * <li><i>true</i> if the subscription succeeded\n\t * <li><i>false</i> otherwise (i.e. when there was already a\n\t * subscription). Please note that if you receive false, then the tick()\n\t * function will not be called with the frequency defined here!\n\t * </ul>\n\t */\n\tprotected final boolean subscribe(final long freq) {\n\t\tif (activeSubscription) {\n\t\t\treturn false;\n\t\t}\n\t\trealSubscribe(freq);\n\t\treturn true;\n\t}\n\n\t/**\n\t * The actual subscription function that is behind updateFreq or subcribe\n\t * \n\t * @param freq the event frequency with which the tick() function should be\n\t * called on the particular implementation of timed.\n\t */\n\tprivate void realSubscribe(final long freq) {\n\t\tactiveSubscription = true;\n\t\tupdateEvent(freq);\n\t\ttimedlist.offer(this);\n\t}\n\n\t/**\n\t * Cancels the future recurrance of this event.\n\t * \n\t * @return\n\t * <ul>\n\t * <li><i>true</i> if the unsubscription succeeded\n\t * <li><i>false</i> otherwise (i.e., this timed object was already\n\t * cancelled)\n\t * </ul>\n\t */\n\tprotected final boolean unsubscribe() {\n\t\tif (activeSubscription) {\n\t\t\tactiveSubscription = false;\n\t\t\tif (underProcessing) {\n\t\t\t\t// because of the poll during the fire function there is nothing\n\t\t\t\t// to remove from the list\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ttimedlist.remove(this);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Allows the alteration of the event frequency independently from subscription.\n\t * If the Timed object is not subscribed then the update function will ensure\n\t * the subscription happens\n\t * \n\t * @param freq the event frequency with which the tick() function should be\n\t * called on the particular implementation of timed.\n\t * @return the earilest time instance (in ticks) when the tick() function will\n\t * be called.\n\t */\n\tprotected final long updateFrequency(final long freq) {\n\t\tif (activeSubscription) {\n\t\t\tfinal long oldNE = nextEvent;\n\t\t\tupdateEvent(freq);\n\t\t\tif (!underProcessing && oldNE != nextEvent) {\n\t\t\t\ttimedlist.remove(this);\n\t\t\t\ttimedlist.offer(this);\n\t\t\t}\n\t\t} else {\n\t\t\trealSubscribe(freq);\n\t\t}\n\t\treturn nextEvent;\n\t}\n\n\t/**\n\t * A core function that actually manages the frequency and nextevent fields. It\n\t * contains several checks to reveal inproper handling of the Timed object.\n\t * \n\t * @param freq the event frequency with which the tick() function should be\n\t * called on the particular implementation of timed.\n\t * @throws IllegalStateException if the frequency specified is negative, or if\n\t * the next event would be in the indefinite\n\t * future\n\t */\n\tprivate void updateEvent(final long freq) {\n\t\tif (freq < 0) {\n\t\t\tthrow new IllegalStateException(\"ERROR: Negative event frequency cannot simulate further!\");\n\t\t} else {\n\t\t\tfrequency = freq;\n\t\t\tnextEvent = calcTimeJump(freq);\n\t\t\tif (nextEvent == Long.MAX_VALUE) {\n\t\t\t\tthrow new IllegalStateException(\"Event to never occur: \" + freq);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Allows the query of the next event at which the tick() function will be\n\t * called for this object\n\t * \n\t * @return the next event's time instance in ticks.\n\t */\n\tpublic long getNextEvent() {\n\t\treturn nextEvent;\n\t}\n\n\t/**\n\t * Determines the time distance (in ticks) between two tick() calls.\n\t * \n\t * If this object is unsubscribed then this call returns with the last\n\t * frequency.\n\t * \n\t * @return the frequency in ticks.\n\t */\n\tpublic long getFrequency() {\n\t\treturn frequency;\n\t}\n\n\t/**\n\t * Determines the next event at which point this object will receive a tick()\n\t * call.\n\t * \n\t * @return\n\t * <ul>\n\t * <li><i>if subscribed</i> the number of ticks till the next tick()\n\t * call arrives\n\t * <li><i>if not subscribed</i> Long.MAX_VALUE.\n\t * </ul>\n\t */\n\tpublic long nextEventDistance() {\n\t\treturn activeSubscription ? nextEvent - fireCounter : Long.MAX_VALUE;\n\t}\n\n\t/**\n\t * a comparator for timed objects based on next events and back preference\n\t * (those objects will be specified smaller that have an earlier next event - if\n\t * nextevents are the same then backpreference decides betwen events)\n\t */\n\t@Override\n\tpublic int compareTo(final Timed o) {\n\t\treturn nextEvent < o.nextEvent ? -1\n\t\t\t\t: nextEvent == o.nextEvent ? ((backPreference ^ o.backPreference) ? (backPreference ? 1 : -1) : 0) : 1;\n\t}\n\n\t/**\n\t * Enables to set the back preference of a particular timed object.\n\t * \n\t * @param backPreference\n\t * <ul>\n\t * <li><i>true</i> if this event should be processed\n\t * amongst the last events at any given time instance\n\t * <li><i>false</i> if the event should be processed\n\t * before the backpreferred events - this is the default\n\t * case for all events before calling this function!\n\t * </ul>\n\t */\n\tprotected void setBackPreference(final boolean backPreference) {\n\t\tthis.backPreference = backPreference;\n\t}\n\n\t/**\n\t * This function allows the manual operation of the event handling mechanism. It\n\t * is used to send out events that should occur at a particular time instance.\n\t * After the events are sent out the time will be advanced by 1 tick. If there\n\t * are no events due at the particular time instance then this function just\n\t * advances the time by one tick.\n\t */\n\tpublic static final void fire() {\n\t\twhile (!timedlist.isEmpty() && timedlist.peek().nextEvent == fireCounter) {\n\t\t\tfinal Timed t = timedlist.poll();\n\t\t\tt.underProcessing = true;\n\t\t\tt.tick(fireCounter);\n\t\t\tif (t.activeSubscription) {\n\t\t\t\tt.updateEvent(t.frequency);\n\t\t\t\ttimedlist.offer(t);\n\t\t\t}\n\t\t\tt.underProcessing = false;\n\t\t}\n\t\tfireCounter++;\n\t}\n\n\t/**\n\t * A simple approach to calculate time advances in the system\n\t * \n\t * @param jump the time (in ticks) to be advanced with\n\t * @return the time (in ticks) at which point the particular jump will be\n\t * complete\n\t */\n\tpublic static long calcTimeJump(long jump) {\n\t\tfinal long targettime = fireCounter + jump;\n\t\treturn targettime < 0 ? Long.MAX_VALUE : targettime;\n\t}\n\n\t/**\n\t * Increases the time with a specific amount of ticks. If there are some events\n\t * that would need to be called before the specific amount of ticks happen, then\n\t * the time is advanced to just the time instance before the next event should\n\t * be fired.\n\t * \n\t * This function allows a more manual handling of the simulation. But it is also\n\t * used by the simulateUntil* functions.\n\t * \n\t * @param desiredJump the amount of time to be jumped ahead.\n\t * @return the amount of time that still remains until desiredjump.\n\t */\n\tpublic static final long jumpTime(long desiredJump) {\n\t\tfinal long targettime = calcTimeJump(desiredJump);\n\t\tfinal long nextFire = getNextFire();\n\t\tif (targettime <= nextFire) {\n\t\t\tfireCounter = targettime;\n\t\t\treturn 0;\n\t\t} else {\n\t\t\tfireCounter = nextFire < 0 ? targettime : nextFire;\n\t\t\treturn targettime - fireCounter;\n\t\t}\n\t}\n\n\t/**\n\t * Jumps the time until the time given by the user. If some events supposed to\n\t * happen during the jumped time period, then this function cancels them. If\n\t * some events should be recurring during the period, then the first recurrence\n\t * of the event will be after the given time instance. If the given time\n\t * instance has already occurred then this function does nothing!\n\t * \n\t * @param desiredTime the time at which the simulation should continue after\n\t * this call. If the time given here already happened then\n\t * this function will have no effect.\n\t */\n\tpublic static final void skipEventsTill(final long desiredTime) {\n\t\tfinal long distance = desiredTime - fireCounter;\n\t\tif (distance > 0) {\n\t\t\tif (timedlist.peek() != null) {\n\t\t\t\twhile (timedlist.peek().nextEvent < desiredTime) {\n\t\t\t\t\tfinal Timed t = timedlist.poll();\n\t\t\t\t\tt.skip();\n\t\t\t\t\tfinal long oldfreq = t.frequency;\n\t\t\t\t\tlong tempFreq = distance;\n\t\t\t\t\tif (oldfreq != 0) {\n\t\t\t\t\t\ttempFreq += oldfreq - distance % oldfreq;\n\t\t\t\t\t}\n\t\t\t\t\tt.updateFrequency(tempFreq);\n\t\t\t\t\tt.frequency = oldfreq;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfireCounter = desiredTime;\n\t\t}\n\t}\n\n\t/**\n\t * Determines the simulated time that has already passed since the beginning of\n\t * the simulation (0).\n\t * \n\t * @return The number of ticks that has passed since the beginning of time.\n\t */\n\tpublic static final long getFireCount() {\n\t\treturn fireCounter;\n\t}\n\n\t/**\n\t * Determines the earliest time instance when there is any event in the system\n\t * to be performed.\n\t * \n\t * @return the time instance in ticks\n\t */\n\tpublic static final long getNextFire() {\n\t\tfinal Timed head = timedlist.peek();\n\t\treturn head == null ? -1 : head.nextEvent;\n\t}\n\n\t/**\n\t * Automatically advances the time in the simulation until there are no events\n\t * remaining in the event queue.\n\t * \n\t * This function is useful when the simulation is completely set up and there is\n\t * no user interaction expected before the simulation completes.\n\t * \n\t * The function is ensuring that all events are fired during its operation.\n\t * \n\t * <b>WARNING:</b> Please note calling this function could lead to infinite\n\t * loops if at least one of the timed objects in the system does not call its\n\t * unsubscribe() function.\n\t */\n\tpublic static final void simulateUntilLastEvent() {\n\t\tlong pnf = -1;\n\t\tlong cnf = 0;\n\t\twhile ((cnf = getNextFire()) >= 0 && (cnf > pnf)) {\n\t\t\tjumpTime(Long.MAX_VALUE);\n\t\t\tfire();\n\t\t\tpnf = cnf;\n\t\t}\n\t}\n\n\t/**\n\t * Automatically advances the time in the simulation until the specific time\n\t * instance.\n\t * \n\t * The function is ensuring that all events are fired during its operation.\n\t * \n\t * @param time the time instance that should not happen but the time should\n\t * advance to this point.\n\t */\n\tpublic static final void simulateUntil(final long time) {\n\t\twhile (timedlist.peek() != null && fireCounter < time) {\n\t\t\tjumpTime(time - fireCounter);\n\t\t\tif (getNextFire() == fireCounter) {\n\t\t\t\tfire();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Cancels all timed events and sets back the time to 0.\n\t */\n\tpublic static final void resetTimed() {\n\t\ttimedlist.clear();\n\t\tDeferredEvent.reset();\n\t\tfireCounter = 0;\n\t}\n\n\t/**\n\t * Prints out basic information about this timed object. Enables easy debugging\n\t * of complex simulations.\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn new StringBuilder(\"Timed(Freq: \").append(frequency).append(\" NE:\").append(nextEvent).append(\")\")\n\t\t\t\t.toString();\n\t}\n\n\t/**\n\t * This function will be called on all timed objects which asked for a recurring\n\t * event notification at a given time instance.\n\t * \n\t * @param fires The particular time instance when the function was called. The\n\t * time instance is passed so the tick functions will not need to\n\t * call getFireCount() if they need to operate on the actual time.\n\t */\n\tpublic abstract void tick(long fires);\n\n\t/**\n\t * Allows actions to be taken if the particular event is ignored\n\t * \n\t * This tells the user of the function that the tick function will not be called\n\t * at the time instance identified by nextEvent.\n\t * \n\t * The function does nothing by default\n\t * \n\t */\n\tprotected void skip() {\n\t}\n}", "public class MaxMinConsumer extends MaxMinFairSpreader {\n\n\t/**\n\t * Constructs a generic Max Min fairness based resource consumer.\n\t * \n\t * @param initialProcessing\n\t * determines the amount of resources this consumer could utilize\n\t * in a single tick\n\t */\n\tpublic MaxMinConsumer(final double initialProcessing) {\n\t\tsuper(initialProcessing);\n\t}\n\n\t/**\n\t * Translates the consumption limit update request to actually changing a\n\t * field in the resource consumption that is related to consumers.\n\t * \n\t * The limit set here is expected to reflect the processing this consumer\n\t * could utilize in the particular time instance with regards to the\n\t * particular resource consumption.\n\t */\n\t@Override\n\tprotected void updateConsumptionLimit(final ResourceConsumption con, final double limit) {\n\t\tcon.consumerLimit = limit;\n\t}\n\n\t/**\n\t * Determines what is the provider this consumer is connected with via the\n\t * resource consumption specified.\n\t */\n\t@Override\n\tprotected ResourceSpreader getCounterPart(final ResourceConsumption con) {\n\t\treturn con.getProvider();\n\t}\n\n\t/**\n\t * Determines what is the consumer referred by the resource consumption\n\t * specified.\n\t */\n\t@Override\n\tprotected ResourceSpreader getSamePart(final ResourceConsumption con) {\n\t\treturn con.getConsumer();\n\t}\n\n\t/**\n\t * Uses the resource consumption's consumer related processing operation to\n\t * actually use the results of a resource consumption (e.g. in case of a\n\t * network transfer this means the consumer actually receives the data that\n\t * so far just traveled through the network. In case of a virtual machine\n\t * this could mean that the virtual CPU of the VM actually executes some\n\t * instructions)\n\t */\n\t@Override\n\tprotected double processSingleConsumption(final ResourceConsumption con, final long ticksPassed) {\n\t\treturn con.doConsumerProcessing(ticksPassed);\n\t}\n\n\t/**\n\t * Tells the world that this particular resource spreader is a consumer.\n\t */\n\t@Override\n\tprotected boolean isConsumer() {\n\t\treturn true;\n\t}\n\n\t/**\n\t * provides some textual representation of this consumer, good for debugging\n\t * and tracing\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn \"MaxMinConsumer(Hash-\" + hashCode() + \" \" + super.toString() + \")\";\n\t}\n}", "public class MaxMinProvider extends MaxMinFairSpreader {\n\t/**\n\t * Constructs a generic Max Min fairness based resource producer.\n\t * \n\t * @param initialProcessing\n\t * determines the amount of resources this producer could offer\n\t * in a single tick\n\t */\n\tpublic MaxMinProvider(final double initialProcessing) {\n\t\tsuper(initialProcessing);\n\t}\n\n\t/**\n\t * Translates the consumption limit update request to actually changing a\n\t * field in the resource consumption that is related to providers.\n\t * \n\t * The limit set here is expected to reflect the processing this provider\n\t * could offer in the particular time instance with regards to the\n\t * particular resource consumption.\n\t */\n\n\t@Override\n\tprotected void updateConsumptionLimit(final ResourceConsumption con, final double limit) {\n\t\tcon.providerLimit = limit;\n\t}\n\n\t/**\n\t * Uses the resource consumption's provider related processing operation to\n\t * actually offer the resources to those who are in need of them (e.g. in\n\t * case of a network transfer this means the provider actually pushes the\n\t * data to the network. In case of a virtual machine this could mean that\n\t * the physical CPU of offers some computational resources for the VM to\n\t * actually execute some instructions)\n\t */\n\t@Override\n\tprotected double processSingleConsumption(final ResourceConsumption con, final long ticksPassed) {\n\t\treturn con.doProviderProcessing(ticksPassed);\n\t}\n\n\t/**\n\t * Determines what is the consumer this provider is connected with via the\n\t * resource consumption specified.\n\t */\n\t@Override\n\tprotected ResourceSpreader getCounterPart(final ResourceConsumption con) {\n\t\treturn con.getConsumer();\n\t}\n\n\t/**\n\t * Determines what is the provider referred by the resource consumption\n\t * specified.\n\t */\n\t@Override\n\tprotected ResourceSpreader getSamePart(final ResourceConsumption con) {\n\t\treturn con.getProvider();\n\t}\n\n\t/**\n\t * Tells the world that this particular resource spreader is a provider.\n\t */\n\t@Override\n\tprotected boolean isConsumer() {\n\t\treturn false;\n\t}\n\n\t/**\n\t * provides some textual representation of this provider, good for debugging\n\t * and tracing\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn \"MaxMinProvider(Hash-\" + hashCode() + \" \" + super.toString() + \")\";\n\t}\n}", "public class ResourceConsumption {\n\n\t/**\n\t * This comparator class provides a simple comparison tool for two resource\n\t * consumptions based on their real limits. Useful for sorting the consumptions.\n\t */\n\tpublic static final Comparator<ResourceConsumption> limitComparator = new Comparator<ResourceConsumption>() {\n\t\t@Override\n\t\tpublic int compare(final ResourceConsumption o1, final ResourceConsumption o2) {\n\t\t\tfinal double upOth = o1.realLimit;\n\t\t\tfinal double upThis = o2.realLimit;\n\t\t\treturn upOth < upThis ? -1 : (upOth == upThis ? 0 : 1);\n\t\t}\n\t};\n\n\t/**\n\t * If a resource consumption is not supposed to be limited by anything but the\n\t * actual resource providers/consumers then this limit could be used in its\n\t * constructor.\n\t */\n\tpublic static final double unlimitedProcessing = Double.MAX_VALUE;\n\n\t/**\n\t * This interface allows its implementors to get notified when a consumption\n\t * completes. Note: the objects will only receive a single call on the below\n\t * interfaces depending on the outcome of the resouece consumption's execution.\n\t * \n\t * @author \"Gabor Kecskemeti, Distributed and Parallel Systems Group, University\n\t * of Innsbruck (c) 2013\"\n\t * \n\t */\n\tpublic interface ConsumptionEvent {\n\t\t/**\n\t\t * This function is called when the resource consumption represented by the\n\t\t * ResourceConsumption object is fulfilled\n\t\t */\n\t\tvoid conComplete();\n\n\t\t/**\n\t\t * This function is called when the resource consumption cannot be handled\n\t\t * properly - if a consumption is suspended (allowing its migration to some\n\t\t * other consumers/providers then this function is <b>not</b> called.\n\t\t */\n\t\tvoid conCancelled(ResourceConsumption problematic);\n\t}\n\n\t/**\n\t * The currently processing entities (e.g., a network buffer)\n\t * \n\t * <i>NOTE:</i> as this consumption is generic, it is actually the\n\t * provider/consumer pair that determines what is the unit of this field\n\t */\n\tprivate double underProcessing;\n\t/**\n\t * The remaining unprocessed entities (e.g., remaining bytes of a transfer)\n\t *\n\t * <i>NOTE:</i> as this consumption is generic, it is actually the\n\t * provider/consumer pair that determines what is the unit of this field\n\t */\n\tprivate double toBeProcessed;\n\n\t/**\n\t * the maximum amount of processing that could be sent from toBeProcessed to\n\t * underProcessing in a tick\n\t */\n\tprivate double processingLimit;\n\t/**\n\t * the user requested processing limit\n\t */\n\tprivate double requestedLimit;\n\t/**\n\t * the minimum of the perTickProcessing power of the provider/consumer\n\t */\n\tprivate double hardLimit;\n\t/**\n\t * The processing limit at the particular moment of time (this is set by the\n\t * scheduler)\n\t * \n\t * This limit is derived from the provider/consumerLimits.\n\t * \n\t * <i>WARNING:</i> this is necessary for the internal behavior of\n\t * MaxMinFairSpreader\n\t */\n\tprivate double realLimit;\n\t/**\n\t * 1/2*realLimit\n\t */\n\tprivate double halfRealLimit;\n\t/**\n\t * The number of ticks it is expected to take that renders both underProcessing\n\t * and toBeProcessed as 0 (i.e., the time when the initially specified amount of\n\t * resources are completely utilized).\n\t */\n\tprivate long completionDistance;\n\t/**\n\t * The processing limit imposed because of the provider\n\t * \n\t * <i>WARNING:</i> this is necessary for the internal behavior of\n\t * MaxMinFairSpreader\n\t */\n\tdouble providerLimit;\n\t/**\n\t * the processing limit imposed because of the consumer\n\t * \n\t * <i>WARNING:</i> this is necessary for the internal behavior of\n\t * MaxMinFairSpreader\n\t */\n\tdouble consumerLimit;\n\t/**\n\t * the amount of processing that can be surely done by both the provider and the\n\t * consumer. This is a temporary variable used by the MaxMinFairSpreader to\n\t * determine the provider/consumerLimits.\n\t * \n\t * <i>WARNING:</i> this is necessary for the internal behavior of\n\t * MaxMinFairSpreader\n\t */\n\tdouble limithelper;\n\t/**\n\t * A helper field to show if the particular resource consumption still\n\t * participates in the scheduling process or if it has already finalized its\n\t * realLimit value.\n\t * \n\t * <i>WARNING:</i> this is necessary for the internal behavior of\n\t * MaxMinFairSpreader\n\t */\n\tboolean unassigned;\n\t/**\n\t * A helper field to show if the consumer/providerLimit fields are under update\n\t * by MaxMinFairSpreader.assignProcessingPower()\n\t * \n\t * <i>WARNING:</i> this is necessary for the internal behavior of\n\t * MaxMinFairSpreader\n\t */\n\tboolean inassginmentprocess;\n\n\t/**\n\t * Added for live migration memDirtyingRate: percentage of memory dirtied\n\t */\n\tprotected double memDirtyingRate = 0.0;\n\tprotected long memSize = 0;\n\n\t/**\n\t * The event to be fired when there is nothing left to process in this\n\t * consumption.\n\t */\n\tprivate final ConsumptionEvent ev;\n\n\t/**\n\t * The consumer which receives the resources of this consumption.\n\t * \n\t * If null, then the consumer must be set before proper operation of the\n\t * consumption. As this can be null the resource consumption objects could be\n\t * created in multiple phases allowing to first determine the amount of\n\t * consumption to be made before actually assigning to a particular consumer.\n\t */\n\tprivate ResourceSpreader consumer;\n\t/**\n\t * The provider which offers the resources for this consumption.\n\t * \n\t * If null, then the provider must be set before proper operation of the\n\t * consumption. As this can be null the resource consumption objects could be\n\t * created in multiple phases allowing to first determine the amount of\n\t * consumption to be made before actually assigning to a particular provider.\n\t */\n\tprivate ResourceSpreader provider;\n\n\t/**\n\t * shows if the consumption was suspended (<i>true</i>) or not.\n\t */\n\tprivate boolean resumable = true;\n\t/**\n\t * shows if the consumption object actually participates in the resource sharing\n\t * machanism.\n\t */\n\tprivate boolean registered = false;\n\t/**\n\t * shows if the consumption event was already sent out to the listener\n\t */\n\tprivate boolean eventNotFired = true;\n\n\t/**\n\t * This constructor describes the basic properties of an individual resource\n\t * consumption.\n\t * \n\t * @param total\n\t * The amount of processing to be done during the lifetime of the\n\t * just created object\n\t * @param limit\n\t * the maximum amount of processing allowable for this particular\n\t * resource consumption (this allows the specification of an upper\n\t * limit of any consumption). If there is no upper limit needed then\n\t * this value should be set with the value of the unlimitedProcessing\n\t * field.\n\t * @param consumer\n\t * the consumer that will benefit from the resource consumption. This\n\t * field could be null, then the consumer must be set with the\n\t * setConsumer() function.\n\t * @param provider\n\t * the provider which will offer its resources for the consumer. This\n\t * field could be null, then the provider must be set with the\n\t * setProvider() function.\n\t * @param e\n\t * Specify here the event to be fired when the just created object\n\t * completes its transfers. With this event it is possible to notify\n\t * the entity who initiated the transfer. This event object cannot be\n\t * null. If there is no special event handling is needed then just\n\t * create a ConsumptionEventAdapter.\n\t */\n\tpublic ResourceConsumption(final double total, final double limit, final ResourceSpreader consumer,\n\t\t\tfinal ResourceSpreader provider, final ConsumptionEvent e) {\n\t\tunderProcessing = 0;\n\t\ttoBeProcessed = total;\n\t\tthis.consumer = consumer;\n\t\tthis.provider = provider;\n\t\tif (e == null) {\n\t\t\tthrow new IllegalStateException(\"Cannot create a consumption without an event to be fired\");\n\t\t} else if (total < 0 || limit < 0) {\n\t\t\tthrow new IllegalArgumentException(\"Cannot create negative consumptions\");\n\t\t}\n\t\tev = e;\n\t\trequestedLimit = limit;\n\t}\n\n\t/**\n\t * Provides a unified update method for the hard processing limit (which will\n\t * become the minimum of the provider's/consumer's per tick processing power) of\n\t * this consumption. All values that depend on hard limit (the real and\n\t * processing limits) are also updated.\n\t * \n\t * This function can be called even if the provider/consumer is not set yet in\n\t * that case the processing limit for the non-set spreader will be unlimited.\n\t */\n\tprivate void updateHardLimit() {\n\t\tfinal double provLimit = provider == null ? unlimitedProcessing : provider.perTickProcessingPower;\n\t\tfinal double conLimit = consumer == null ? unlimitedProcessing : consumer.perTickProcessingPower;\n\t\thardLimit = requestedLimit < provLimit ? requestedLimit : provLimit;\n\t\tif (hardLimit > conLimit) {\n\t\t\thardLimit = conLimit;\n\t\t}\n\t\tprocessingLimit = requestedLimit < hardLimit ? requestedLimit : hardLimit;\n\t\tsetRealLimit(hardLimit);\n\t}\n\n\t/**\n\t * Initiates the processing of a resource consumption. By calling this function\n\t * the resource consumption object will be participating in the unified resource\n\t * sharing mechanism's scheduling and spreading operations.\n\t * \n\t * Before the registration actually happens, it updates the hard limit of the\n\t * consumption so the spreaders could now operate using its values.\n\t * \n\t * <i>NOTE:</i> this function is also used for resuming a suspended consumption\n\t * \n\t * @return\n\t * <ul>\n\t * <li><i>true</i> if the registration was successful\n\t * <li><i>false</i> otherwise. For example: if the provider/consumer is\n\t * not yet set, if the consumption cannot be registered between the\n\t * particular provider/consumer pair or if the consumption was already\n\t * registered.\n\t * </ul>\n\t */\n\tpublic boolean registerConsumption() {\n\t\tif (!registered) {\n\t\t\tif (getUnProcessed() == 0) {\n\t\t\t\tfireCompleteEvent();\n\t\t\t\treturn true;\n\t\t\t} else if (resumable && provider != null && consumer != null) {\n\t\t\t\tupdateHardLimit();\n\t\t\t\tif (ResourceSpreader.registerConsumption(this)) {\n\t\t\t\t\tregistered = true;\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\n\t/**\n\t * Returns the amount of processing still remaining in this resource\n\t * consumption.\n\t * \n\t * @return the remaining processing\n\t */\n\tpublic double getUnProcessed() {\n\t\treturn underProcessing + toBeProcessed;\n\t}\n\n\t/**\n\t * terminates the consumption, deregisters it from its consumer/provider pair\n\t * and ensures that it can no longer be registered\n\t */\n\tpublic void cancel() {\n\t\tboolean wasRegistered = registered;\n\t\tsuspend();\n\t\tresumable = false;\n\t\tif (!wasRegistered) {\n\t\t\tfireCancelEvent();\n\t\t}\n\t}\n\n\t/**\n\t * Terminates the consumption but ensures that it will be resumable later on. If\n\t * a consumption needs to be resumed then it must be re-registered, there is no\n\t * special function for resume.\n\t */\n\tpublic void suspend() {\n\t\tif (registered) {\n\t\t\tResourceSpreader.cancelConsumption(this);\n\t\t\tregistered = false;\n\t\t}\n\t}\n\n\t/**\n\t * Allows to set a provider for the consumption if the consumption is not yet\n\t * under way.\n\t * \n\t * @param provider\n\t * the provider to be used for offering the resources for the\n\t * consumption\n\t */\n\tpublic void setProvider(final ResourceSpreader provider) {\n\t\tif (!registered) {\n\t\t\tthis.provider = provider;\n\t\t\tupdateHardLimit();\n\t\t\treturn;\n\t\t} else {\n\t\t\tthrow new IllegalStateException(\"Attempted consumer change with a registered consumption\");\n\t\t}\n\t}\n\n\t/**\n\t * Allows to set a consumer for the consumption if the consumption is not yet\n\t * under way.\n\t * \n\t * @param consumer\n\t * the consumer to be used for utilizing the resources received\n\t * through this resource consumption object.\n\t */\n\tpublic void setConsumer(final ResourceSpreader consumer) {\n\t\tif (!registered) {\n\t\t\tthis.consumer = consumer;\n\t\t\tupdateHardLimit();\n\t\t\treturn;\n\t\t} else {\n\t\t\tthrow new IllegalStateException(\"Attempted consumer change with a registered consumption\");\n\t\t}\n\t}\n\n\t/**\n\t * Updates the completion distance field, should be called every time the real\n\t * limit is updated or when the amount of unprocessed consumption changes.\n\t */\n\tprivate void calcCompletionDistance() {\n\t\tcompletionDistance = Math.round(getUnProcessed() / realLimit);\n\t}\n\n\t/**\n\t * This function simulates how the provider offers the resources for its\n\t * consumer. The offered resources are put in the underprocessing field from the\n\t * toBeprocessed.\n\t * \n\t * If the processing is really close to completion (determined by using\n\t * halfreallimit), then this function cheats a bit and offers the resources for\n\t * the last remaining processable consumption. This is actually ensuring that we\n\t * don't need to simulate sub-tick processing operations.\n\t * \n\t * <i>WARNING:</i> this is necessary for the internal behavior of\n\t * MaxMinFairSpreader\n\t * \n\t * @param ticksPassed\n\t * the number of ticks to be simulated (i.e. how many times we should\n\t * multiply realLimit) before offering the resources to the\n\t * underprocessing field.\n\t * @return the amount of resources actually offered for consumption. Negative\n\t * values mark the end of this resource consumption (i.e. when there is\n\t * no more processing to be done for this consumption). Albeit such\n\t * values are negative, their negativeness is just used as a flag and\n\t * their absolute value still represent the amount of offered resources.\n\t */\n\tdouble doProviderProcessing(final long ticksPassed) {\n\t\tdouble processed = 0;\n\t\tif (toBeProcessed > 0) {\n\t\t\tfinal double possiblePush = ticksPassed * realLimit;\n\t\t\tprocessed = possiblePush < toBeProcessed ? possiblePush : toBeProcessed;\n\t\t\ttoBeProcessed -= processed;\n\t\t\tunderProcessing += processed;\n\t\t\tif (toBeProcessed < halfRealLimit) {\n\t\t\t\t// ensure that tobeprocessed is 0!\n\t\t\t\tprocessed += toBeProcessed;\n\t\t\t\tunderProcessing += toBeProcessed;\n\t\t\t\ttoBeProcessed = 0;\n\t\t\t\treturn -processed;\n\t\t\t}\n\t\t}\n\t\treturn processed;\n\t}\n\n\t/**\n\t * This function simulates how the consumer utilizes the resources from its\n\t * provider. The utilized resources are used from the underprocessing field.\n\t * \n\t * If the processing is really close to completion (determined by calculating\n\t * the completion distance), then this function cheats a bit and utilizes the\n\t * resources for the last remaining underprocessing. This is actually ensuring\n\t * that we don't need to simulate sub-tick processing operations.\n\t * \n\t * <i>WARNING:</i> this is necessary for the internal behavior of\n\t * MaxMinFairSpreader\n\t * \n\t * @param ticksPassed\n\t * the number of ticks to be simulated (i.e. how many times we should\n\t * multiply realLimit) before utilizing the resources from the\n\t * underprocessing field.\n\t * @return the amount of resources actually utilized by the consumer. Negative\n\t * values mark the end of this resource consumption (i.e. when there is\n\t * no more processing to be done for this consumption). Albeit such\n\t * values are negative, their negativeness is just used as a flag and\n\t * their absolute value still represent the amount of utilized\n\t * resources.\n\t */\n\tdouble doConsumerProcessing(final long ticksPassed) {\n\t\tdouble processed = 0;\n\t\tif (underProcessing > 0) {\n\t\t\tfinal double possibleProcessing = ticksPassed * realLimit;\n\t\t\tprocessed = possibleProcessing < underProcessing ? possibleProcessing : underProcessing;\n\t\t\tunderProcessing -= processed;\n\t\t\tcalcCompletionDistance();\n\t\t\tif (completionDistance == 0) {\n\t\t\t\t// ensure that tobeprocessed is 0!\n\t\t\t\tprocessed += underProcessing;\n\t\t\t\tunderProcessing = 0;\n\t\t\t\treturn -processed;\n\t\t\t}\n\t\t}\n\t\treturn processed;\n\t}\n\n\t/**\n\t * Determines the amount of processing for which no resources were offered from\n\t * the provider so far.\n\t * \n\t * @return the tobeprocessed value\n\t */\n\tpublic double getToBeProcessed() {\n\t\treturn toBeProcessed;\n\t}\n\n\t/**\n\t * Determines the amount of resoruces already offered by the provider but not\n\t * yet used by the consumer.\n\t * \n\t * @return the underprocessing value\n\t */\n\tpublic double getUnderProcessing() {\n\t\treturn underProcessing;\n\t}\n\n\t/**\n\t * Retrieves the maximum amount of processing that could be sent from\n\t * toBeProcessed to underProcessing in a single tick\n\t */\n\n\tpublic double getProcessingLimit() {\n\t\treturn processingLimit;\n\t}\n\n\t/**\n\t * Retrieves the processing limit at the particular moment of time (just queries\n\t * the value last set by the scheduler)\n\t */\n\tpublic double getRealLimit() {\n\t\treturn realLimit;\n\t}\n\n\t/**\n\t * Retrieves the number of ticks it is expected to take that renders both\n\t * underProcessing and toBeProcessed as 0 (i.e., the time when the initially\n\t * specified amount of resources are completely utilized). This is again just\n\t * the value that is derived from the real limit last set by the scheduler.\n\t */\n\tpublic long getCompletionDistance() {\n\t\treturn completionDistance;\n\t}\n\n\t/**\n\t * Queries the consumer associated with this resource consumption.\n\t * \n\t * @return the consumer which will utilize the resources received through this\n\t * consumption object\n\t */\n\tpublic ResourceSpreader getConsumer() {\n\t\treturn consumer;\n\t}\n\n\t/**\n\t * Queries the provider associated with this resource consumption.\n\t * \n\t * @return the provider which will offer the resources for this particular\n\t * resource consumption object.\n\t */\n\tpublic ResourceSpreader getProvider() {\n\t\treturn provider;\n\t}\n\n\t/**\n\t * Simultaneously updates the real limit (the instantaneous processing limit\n\t * determined by the low level scheduler of the unified resoruce sharing model\n\t * of DISSECT-CF) value as well as the halfreallimit field.\n\t * \n\t * @param rL\n\t * the value to be set as real limit\n\t */\n\tprivate void setRealLimit(final double rL) {\n\t\trealLimit = rL;\n\t\thalfRealLimit = rL / 2;\n\t}\n\n\t/**\n\t * Sets the real limit based on the scheduler set provider and consumer limits\n\t * (the smaller is used as real).\n\t * \n\t * Updates the completion distance if instructed.\n\t * \n\t * @param updateCD\n\t * <i>true</i> tells the system to update the completion distance\n\t * alongside the real limit setup. This more frequent update on the\n\t * real limit than the completion distance is calculated.\n\t * \n\t * <i>IMPORTANT:</i> if set to false then it is expected that the\n\t * scheduler will call the updateRealLimit at least once more with a\n\t * true parameter. Failing to do so the consumption object will\n\t * become broken.\n\t * @return the real limit that was actually determined and set by this function\n\t * @throws IllegalStateException\n\t * if the real limit would become 0\n\t */\n\tdouble updateRealLimit(final boolean updateCD) {\n\t\tfinal double rlTrial = providerLimit < consumerLimit ? providerLimit : consumerLimit;\n\t\tif (rlTrial == 0) {\n\t\t\tthrow new IllegalStateException(\n\t\t\t\t\t\"Cannot calculate the completion distance for a consumption without a real limit! \" + this);\n\t\t}\n\t\tsetRealLimit(rlTrial);\n\t\tif (updateCD) {\n\t\t\tcalcCompletionDistance();\n\t\t}\n\t\treturn realLimit;\n\t}\n\n\t/**\n\t * Determines the dirtying rate of this process in a single tick\n\t * \n\t * @return the current dirtying rate\n\t */\n\tpublic double getMemDirtyingRate() {\n\t\treturn memDirtyingRate;\n\t}\n\n\t/**\n\t * Sets the dirtying rate for this RC.\n\t * \n\t * <p>\n\t * <i>Note</i>, the value set here only considered just before a live migration\n\t * round, if it changes during a particular round, the last set dirtying rate\n\t * will be used by the VM.\n\t * \n\t * @param memDirtyingRate\n\t */\n\tpublic void setMemDirtyingRate(double memDirtyingRate) {\n\t\tif (memDirtyingRate < 0.0 || memDirtyingRate > 1.0)\n\t\t\tthrow new IllegalArgumentException(\"Dirtying rate must be between 0.0 and 1.0\");\n\t\tthis.memDirtyingRate = memDirtyingRate;\n\t}\n\n\t/**\n\t * The amount of memory used by the task\n\t * \n\t * @return\n\t */\n\tpublic long getMemSize() {\n\t\treturn memSize;\n\t}\n\n\t/**\n\t * Change the amount of memory used by the task.\n\t * <p>\n\t * <i>Note</i>, the value set here only considered just before a live migration\n\t * round, if it changes during a particular round, the last set size will be\n\t * used by the VM.\n\t * \n\t * @param newMemSize\n\t */\n\tpublic void setMemSize(long newMemSize) {\n\t\tmemSize = newMemSize;\n\t}\n\n\t/**\n\t * Provides a nice formatted output of the resource consumption showing how much\n\t * processing is under way, how much is still held back and what is the current\n\t * real limit set by the scheduler.\n\t * \n\t * Intended for debugging and tracing outputs.\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn \"RC(C:\" + underProcessing + \" T:\" + toBeProcessed + \" L:\" + realLimit + \")\";\n\t}\n\n\t/**\n\t * Determines if the object is registered and resources are used because of this\n\t * consumption object\n\t * \n\t * @return <i>true</i> if the object is registered.\n\t */\n\tpublic boolean isRegistered() {\n\t\treturn registered;\n\t}\n\n\t/**\n\t * Allows to query whether this resource consumption was cancelled or not\n\t * \n\t * @return <i>false</i> if the resource consumption was cancelled and it can no\n\t * longer be registered within the unified resource sharing model of the\n\t * simulator.\n\t */\n\tpublic boolean isResumable() {\n\t\treturn resumable;\n\t}\n\n\t/**\n\t * Determines the hard processing limit for this resource consumption.\n\t * \n\t * @return the hard limit\n\t */\n\tpublic double getHardLimit() {\n\t\treturn hardLimit;\n\t}\n\n\t/**\n\t * Sends out the completion event to the listener\n\t * \n\t * @return false if the event was not sent\n\t */\n\tboolean fireCompleteEvent() {\n\t\tif (eventNotFired && getUnProcessed() == 0) {\n\t\t\teventNotFired = false;\n\t\t\tev.conComplete();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Sends out the cancellation event to the listener\n\t * \n\t * @return false if the event was not sent\n\t */\n\tboolean fireCancelEvent() {\n\t\tif (eventNotFired) {\n\t\t\teventNotFired = false;\n\t\t\tev.conCancelled(this);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n}", "public interface ConsumptionEvent {\n\t/**\n\t * This function is called when the resource consumption represented by the\n\t * ResourceConsumption object is fulfilled\n\t */\n\tvoid conComplete();\n\n\t/**\n\t * This function is called when the resource consumption cannot be handled\n\t * properly - if a consumption is suspended (allowing its migration to some\n\t * other consumers/providers then this function is <b>not</b> called.\n\t */\n\tvoid conCancelled(ResourceConsumption problematic);\n}" ]
import at.ac.uibk.dps.cloud.simulator.test.ConsumptionEventAssert; import at.ac.uibk.dps.cloud.simulator.test.ConsumptionEventFoundation; import hu.mta.sztaki.lpds.cloud.simulator.DeferredEvent; import hu.mta.sztaki.lpds.cloud.simulator.Timed; import hu.mta.sztaki.lpds.cloud.simulator.iaas.resourcemodel.ConsumptionEventAdapter; import hu.mta.sztaki.lpds.cloud.simulator.iaas.resourcemodel.MaxMinConsumer; import hu.mta.sztaki.lpds.cloud.simulator.iaas.resourcemodel.MaxMinProvider; import hu.mta.sztaki.lpds.cloud.simulator.iaas.resourcemodel.ResourceConsumption; import hu.mta.sztaki.lpds.cloud.simulator.iaas.resourcemodel.ResourceConsumption.ConsumptionEvent; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test;
/* * ======================================================================== * DIScrete event baSed Energy Consumption simulaTor * for Clouds and Federations (DISSECT-CF) * ======================================================================== * * This file is part of DISSECT-CF. * * DISSECT-CF 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. * * DISSECT-CF 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 DISSECT-CF. If not, see <http://www.gnu.org/licenses/>. * * (C) Copyright 2014, Gabor Kecskemeti ([email protected], * [email protected]) */ package at.ac.uibk.dps.cloud.simulator.test.simple.cloud; public class ResourceConsumptionTest extends ConsumptionEventFoundation { public static final double processingTasklen = 1; public static final double permsProcessing = processingTasklen / aSecond;
MaxMinProvider offer;
2
sdenier/GecoSI
src/test/net/gecosi/dataframe/Si5DataFrameTest.java
[ "public class Si5DataFrame extends SiAbstractDataFrame {\n\t\n\tprivate static final int SI5_TIMED_PUNCHES = 30;\n\n\tpublic Si5DataFrame(SiMessage message) {\n\t\tthis.dataFrame = extractDataFrame(message);\n\t\tthis.siNumber = extractSiNumber();\n\t}\n\n\tprotected byte[] extractDataFrame(SiMessage message) {\n\t\treturn Arrays.copyOfRange(message.sequence(), 5, 133);\n\t}\n\n\t@Override\n\tpublic SiDataFrame startingAt(long zerohour) {\n\t\tstartTime = advanceTimePast(rawStartTime(), zerohour);\n\t\tcheckTime = advanceTimePast(rawCheckTime(), zerohour);\n\t\tlong refTime = newRefTime(zerohour, startTime);\n\t\tpunches = computeShiftedPunches(refTime);\n\t\tif( punches.length > 0) {\n\t\t\tSiPunch lastTimedPunch = punches[nbTimedPunches(punches) - 1];\n\t\t\trefTime = newRefTime(refTime, lastTimedPunch.timestamp());\n\t\t}\n\t\tfinishTime = advanceTimePast(rawFinishTime(), refTime);\n\t\treturn this;\n\t}\n\t\n\tpublic long advanceTimePast(long timestamp, long refTime) {\n\t\treturn advanceTimePast(timestamp, refTime, TWELVE_HOURS);\n\t}\n\n\tprivate SiPunch[] computeShiftedPunches(long startTime) {\n\t\tint nbPunches = rawNbPunches();\n\t\tSiPunch[] punches = new SiPunch[nbPunches];\n\t\tint nbTimedPunches = nbTimedPunches(punches);\n\t\tlong refTime = startTime;\n\t\tfor (int i = 0; i < nbTimedPunches; i++) {\n\t\t\t// shift each punch time after the previous\n\t\t\tlong punchTime = advanceTimePast(getPunchTime(i), refTime);\n\t\t\tpunches[i] = new SiPunch(getPunchCode(i), punchTime);\n\t\t\trefTime = newRefTime(refTime, punchTime);\n\t\t}\n\t\tfor (int i = 0; i < nbPunches - SI5_TIMED_PUNCHES; i++) {\n\t\t\tpunches[i + SI5_TIMED_PUNCHES] = new SiPunch(getNoTimePunchCode(i), NO_TIME);\n\t\t}\n\t\treturn punches;\n\t}\n\n\tprivate int nbTimedPunches(SiPunch[] punches) {\n\t\treturn Math.min(punches.length, SI5_TIMED_PUNCHES);\n\t}\n\n\tprotected String extractSiNumber() {\n\t\tint siNumber = wordAt(0x04);\n\t\tint cns = byteAt(0x06);\n\t\tif( cns > 0x01 ) {\n\t\t\tsiNumber = siNumber + cns * 100000;\n\t\t}\n\t\treturn Integer.toString(siNumber);\n\t}\n\t\n\tprotected int rawNbPunches() {\n\t\treturn byteAt(0x17) - 1;\n\t}\n\n\tprivate long rawStartTime() {\n\t\treturn timestampAt(0x13);\n\t}\n\n\tprivate long rawFinishTime() {\n\t\treturn timestampAt(0x15);\n\t}\n\n\tprivate long rawCheckTime() {\n\t\treturn timestampAt(0x19);\n\t}\n\n\tprotected int punchOffset(int i) {\n\t\treturn 0x21 + (i / 5) * 0x10 + (i % 5) * 0x03;\n\t}\n\t\n\tprotected int getPunchCode(int i) {\n\t\treturn byteAt(punchOffset(i));\n\t}\n\t\n\tprotected int getNoTimePunchCode(int i) {\n\t\treturn byteAt(0x20 + i * 0x10);\n\t}\t\n\t\n\tprotected long getPunchTime(int i) {\n\t\treturn timestampAt(punchOffset(i) + 1);\n\t}\n\n\t@Override\n\tpublic String getSiSeries() {\n\t\treturn \"SiCard 5\";\n\t}\n\n}", "public interface SiDataFrame {\n\n\tpublic final static long NO_TIME = -1;\n\n\tpublic SiDataFrame startingAt(long zerohour);\n\n\tpublic int getNbPunches();\n\n\tpublic String getSiNumber();\n\n\tpublic String getSiSeries();\n\n\tpublic long getStartTime();\n\n\tpublic long getFinishTime();\n\n\tpublic long getCheckTime();\n\n\tpublic SiPunch[] getPunches();\n\n\tpublic void printString();\n\n}", "public class SiPunch {\n\n\tprivate int code;\n\tprivate long timestamp;\n\n\tpublic SiPunch(int code, long timestamp) {\n\t\tthis.code = code;\n\t\tthis.timestamp = timestamp;\n\t}\n\t\n\tpublic int code() {\n\t\treturn this.code;\n\t}\n\t\n\tpublic long timestamp() {\n\t\treturn this.timestamp;\n\t}\n\t\n}", "public class SiMessage {\n\n\tprivate final byte[] sequence;\n\t\n\tpublic SiMessage(byte[] sequence) {\n\t\tthis.sequence = sequence;\n\t}\n\n\tpublic byte[] sequence() {\n\t\treturn sequence;\n\t}\n\n\tpublic byte sequence(int i) {\n\t\treturn sequence[i];\n\t}\n\t\n\tpublic byte[] data() {\n\t\tint cmd_length = sequence.length - 4;\n\t\tbyte[] command = new byte[cmd_length];\n\t\tSystem.arraycopy(sequence, 1, command, 0, cmd_length);\n\t\treturn command;\n\t}\n\n\tpublic byte commandByte() {\n\t\treturn sequence[1];\n\t}\n\n\tpublic byte startByte() {\n\t\treturn sequence[0];\n\t}\n\n\tpublic byte endByte() {\n\t\treturn sequence[sequence.length - 1];\n\t}\n\n\tpublic int extractCRC() {\n\t\tint i = sequence.length;\n\t\treturn (sequence[i-3] << 8 & 0xFFFF) | (sequence[i-2] & 0xFF); \n\t}\n\t\n\tpublic int computeCRC() {\n\t\treturn CRCCalculator.crc(data());\n\t}\n\t\n\tpublic boolean check(byte command) {\n\t\treturn valid() && commandByte() == command;\n\t}\n\t\n\tpublic boolean valid() {\n\t\treturn startByte() == STX && endByte() == ETX && validCRC();\n\t}\n\t\n\tpublic boolean validCRC() {\n\t\treturn computeCRC() == extractCRC();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringWriter buf = new StringWriter(sequence.length);\n\t\tfor (int i = 0; i < sequence.length; i++) {\n\t\t\tbuf.write(String.format(\"%02X \", sequence[i]));// & 0xFF);\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tpublic String toStringCRC() {\n\t\tif( sequence.length >= 6 ) {\n\t\t\treturn String.format(\"%04X\", computeCRC());\n\t\t} else {\n\t\t\treturn \"none\";\n\t\t}\n\t}\n\n\n\t/*\n\t * Basic protocol instructions\n\t */\n\tpublic static final byte WAKEUP = (byte) 0xFF;\n\tpublic static final byte STX = 0x02;\n\tpublic static final byte ETX = 0x03;\n\tpublic static final byte ACK = 0x06;\n\tpublic static final byte NAK = 0x15;\n\n\t/*\n\t * Command instructions\n\t */\n\tpublic static final byte GET_SYSTEM_VALUE = (byte) 0x83;\n\tpublic static final byte SET_MASTER_MODE = (byte) 0xF0;\n\tpublic static final byte DIRECT_MODE = 0x4d;\n\tpublic static final byte BEEP = (byte) 0xF9;\n\n\t/*\n\t * Card detected/removed\n\t */\n\tpublic static final byte SI_CARD_5_DETECTED = (byte) 0xE5;\n\tpublic static final byte SI_CARD_6_PLUS_DETECTED = (byte) 0xE6;\n\tpublic static final byte SI_CARD_8_PLUS_DETECTED = (byte) 0xE8;\n\tpublic static final byte SI_CARD_REMOVED = (byte) 0xE7;\n\t\n\t/*\n\t * Card Readout instructions\n\t */\n\tpublic static final byte GET_SI_CARD_5 = (byte) 0xB1;\n\tpublic static final byte GET_SI_CARD_6_BN = (byte) 0xE1;\n\tpublic static final byte GET_SI_CARD_8_PLUS_BN = (byte) 0xEF;\n\n\t/*\n\t * SiCard special data\n\t */\n\tpublic static final int SI3_NUMBER_INDEX = 5;\n\tpublic static final byte SI_CARD_10_PLUS_SERIES = 0x0F;\n\t\n\t/*\n\t * Command messages\n\t */\n\tpublic static final SiMessage startup_sequence = new SiMessage(new byte[] {\n\t\tWAKEUP, STX, STX, SET_MASTER_MODE, 0x01, DIRECT_MODE, 0x6D, 0x0A, ETX\n\t});\n\n\tpublic static final SiMessage get_protocol_configuration = new SiMessage(new byte[] {\n\t\tSTX, GET_SYSTEM_VALUE, 0x02, 0x74, 0x01, 0x04, 0x14, ETX\n\t});\n\n\tpublic static final SiMessage get_cardblocks_configuration = new SiMessage(new byte[] {\n\t\tSTX, GET_SYSTEM_VALUE, 0x02, 0x33 , 0x01, 0x16, 0x11, ETX\n\t});\n\t\n\tpublic static final SiMessage ack_sequence = new SiMessage(new byte[] {\n\t\tACK\n\t});\n\n\tpublic static final SiMessage read_sicard_5 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_5, 0x00, GET_SI_CARD_5, 0x00, ETX\t\n\t});\n\n\tpublic static final SiMessage read_sicard_6_b0 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_6_BN, 0x01, 0x00, 0x46, 0x0A, ETX\n\t});\n\n\tpublic static final SiMessage read_sicard_6_plus_b2 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_6_BN, 0x01, 0x02, 0x44, 0x0A, ETX\n\t});\n\n\tpublic static final SiMessage read_sicard_6_plus_b3 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_6_BN, 0x01, 0x03, 0x45, 0x0A, ETX\n\t});\n\n\tpublic static final SiMessage read_sicard_6_plus_b4 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_6_BN, 0x01, 0x04, 0x42, 0x0A, ETX\n\t});\n\n\tpublic static final SiMessage read_sicard_6_plus_b5 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_6_BN, 0x01, 0x05, 0x43, 0x0A, ETX\n\t});\n\n\tpublic static final SiMessage read_sicard_6_b6 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_6_BN, 0x01, 0x06, 0x40, 0x0A, ETX\n\t});\n\n\tpublic static final SiMessage read_sicard_6_b7 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_6_BN, 0x01, 0x07, 0x41, 0x0A, ETX\n\t});\n\n\tpublic static final SiMessage read_sicard_6_b8 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_6_BN, 0x01, 0x08, 0x4E, 0x0A, ETX\n\t});\n\t\n\tpublic static final SiMessage read_sicard_8_plus_b0 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_8_PLUS_BN, 0x01, 0x00, (byte) 0xE2, 0x09, ETX\t\n\t});\n\n\tpublic static final SiMessage read_sicard_8_plus_b1 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_8_PLUS_BN, 0x01, 0x01, (byte) 0xE3, 0x09, ETX\t\n\t});\n\n\tpublic static final SiMessage read_sicard_10_plus_b0 = read_sicard_8_plus_b0;\n\n\tpublic static final SiMessage read_sicard_10_plus_b4 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_8_PLUS_BN, 0x01, 0x04, (byte) 0xE6, 0x09, ETX\n\t});\n\n\tpublic static final SiMessage read_sicard_10_plus_b5 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_8_PLUS_BN, 0x01, 0x05, (byte) 0xE7, 0x09, ETX\n\t});\n\n\tpublic static final SiMessage read_sicard_10_plus_b6 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_8_PLUS_BN, 0x01, 0x06, (byte) 0xE4, 0x09, ETX\n\t});\n\n\tpublic static final SiMessage read_sicard_10_plus_b7 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_8_PLUS_BN, 0x01, 0x07, (byte) 0xE5, 0x09, ETX\n\t});\n\n\tpublic static final SiMessage read_sicard_10_plus_b8 = new SiMessage(new byte[] {\n\t\tSTX, GET_SI_CARD_8_PLUS_BN, 0x01, 0x08, (byte) 0xEA, 0x09, ETX\t\n\t});\n\n\tpublic static final SiMessage beep_twice = new SiMessage(new byte[] {\n\t\tSTX, BEEP, 0x01, 0x02, 0x14, 0x0A, ETX\n\t});\n\t\n}", "public class SiMessageFixtures {\n\n\tpublic final static SiMessage startup_answer = new SiMessage(\n\t\t\tnew byte[]{0x02, (byte) 0xF0, 0x03, 0x00, 0x01, 0x4D, 0x0D, 0x11, 0x03});\n\n\tpublic final static SiMessage ok_ext_protocol_answer = new SiMessage(\n\t\t\tnew byte[]{0x02, (byte) 0x83, 0x04, 0x00, 0x01, 0x74, 0x05, (byte) 0xB1, 0x64, 0x03});\n\n\tpublic final static SiMessage no_ext_protocol_answer = new SiMessage(new byte[]{\n\t\t\t0x02, (byte) 0x83, 0x04, 0x00, 0x01, 0x74, 0x04, (byte) 0x31, 0x61, 0x03});\n\n\tpublic final static SiMessage no_handshake_answer = new SiMessage(new byte[]{\n\t\t\t0x02, (byte) 0x83, 0x04, 0x00, 0x01, 0x74, 0x03, (byte) 0xB1, 0x70, 0x03});\n\n\tpublic final static SiMessage si6_64_punches_answer = new SiMessage(new byte[]{\n\t\t\t0x02, (byte) 0x83, 0x04, 0x00, 0x01, 0x33, (byte) 0xC1, 0x21, (byte) 0xFA, 0x03});\n\n\tpublic final static SiMessage si6_192_punches_answer = new SiMessage(new byte[]{\n\t\t\t0x02, (byte) 0x83, 0x04, 0x00, 0x01, 0x33, (byte) 0xFF, (byte) 0xA1, 0x7D, 0x03});\n\t\n\tpublic final static SiMessage sicard5_detected = new SiMessage(new byte[]{\n\t\t\t0x02, (byte) 0xE5, 0x06, 0x00, 0x01, 0x00, 0x03, 0x10, (byte) 0x93, (byte) 0xB7, 0x37, 0x03});\n\t\n\tpublic final static SiMessage sicard5_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xB1, (byte) 0x82, 0x00, 0x01, (byte) 0xAA, 0x2E, 0x00, 0x01, 0x10, (byte) 0x93, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x65, 0x10, (byte) 0x93, (byte) 0xEE, (byte) 0xEE, (byte) 0x01, (byte) 0xF8, 0x0B, 0x56, (byte) 0xEE, (byte) 0xEE, 0x28, 0x03,\n\t\t\t(byte) 0xA6, 0x00, 0x07, 0x00, 0x24, (byte) 0x9C, 0x7B, 0x26, (byte) 0x9C, (byte) 0x8C, 0x22, (byte) 0x9C, (byte) 0x8D, 0x28, (byte) 0x9C,\n\t\t\t(byte) 0x8F, 0x34, (byte) 0x9C, (byte) 0x9B, 0x00, 0x36, (byte) 0x9C, (byte) 0x9F, 0x33, (byte) 0x9C, (byte) 0xA1, 0x35, (byte) 0x9C,\n\t\t\t(byte) 0xA2, 0x3C, (byte) 0x9C, (byte) 0xA7, 0x3B, (byte) 0x9C, (byte) 0xA8, 0x00, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE,\n\t\t\t(byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, 0x00, (byte) 0xEE,\n\t\t\t(byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE,\n\t\t\t0x00, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE,\n\t\t\t0x00,(byte) 0xEE, (byte) 0xEE, 0x00, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE,\n\t\t\t0x00, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xEE, (byte) 0xEE, (byte) 0x86, (byte) 0xC8, 0x03});\n\n\tpublic final static SiMessage sicard5_removed = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE7, 0x06, 0x00, 0x01, 0x00, 0x03, 0x10, (byte) 0x93, (byte) 0x97, 0x3B, 0x03});\n\n\tpublic final static SiMessage sicard6_detected = new SiMessage(new byte[]{\n\t\t\t0x02, (byte) 0xE6, 0x06, 0x00, 0x01, 0x00, 0x07, (byte) 0xA1, 0x20, (byte) 0xB0, (byte) 0xFE, 0x03});\n\n\tpublic final static SiMessage sicard6Star_detected = new SiMessage(new byte[]{\n\t\t\t0x02, (byte) 0xE6, 0x06, 0x00, 0x01, 0x00, (byte) 0xFF, 0x00, 0x00, (byte) 0x68, (byte) 0x64, 0x03});\n\n\tpublic final static SiMessage sicard6_b0_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE1, (byte) 0x83, 0x00, 0x06, 0x00, 0x01, 0x01, 0x01, 0x01, (byte) 0xED, (byte) 0xED, (byte) 0xED, (byte) 0xED, 0x55,\n\t\t\t(byte) 0xAA, 0x00, 0x0C, (byte) 0x87, 0x0B, (byte) 0xBA, (byte) 0xA3, 0x00, 0x23, 0x05, 0x06, 0x06, 0x0A, (byte) 0x8B, 0x44, 0x06,\n\t\t\t0x07, (byte) 0x8A, (byte) 0xED, 0x06, 0x04, (byte) 0x8A, (byte) 0xEB, 0x06, 0x06, (byte) 0x8A, (byte) 0xD9, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, 0x00, 0x00, 0x00, 0x00, 0x20, 0x20, 0x20, 0x20, 0x4D, 0x61, 0x72, 0x69, 0x71, 0x75, 0x65, 0x20, 0x20, 0x20,\n\t\t\t0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x52, 0x6F, 0x62, 0x65, 0x72, 0x74, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,\n\t\t\t0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x48, 0x65, 0x72, 0x6D, 0x61, 0x74, 0x68, 0x65, 0x6E, 0x61,\n\t\t\t0x65, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,\n\t\t\t0x20, 0x20, 0x20, 0x20, (byte) 0x9E, (byte) 0xB7, 0x03});\n\t\n\tpublic final static SiMessage sicard6_b6_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE1, (byte) 0x83, 0x00, 0x06, 0x06, 0x06, 0x1F, (byte) 0x8B, 0x05, 0x06, 0x20, (byte) 0x8B, 0x12, 0x06, 0x21, (byte) 0x8B,\n\t\t\t0x1D, 0x06, 0x22, (byte) 0x8B, 0x28, 0x06, 0x23, (byte) 0x8B, 0x33, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xBD, 0x11, 0x03});\n\t\n\tpublic final static SiMessage sicard6_b7_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE1, (byte) 0x83, 0x00, 0x06, 0x07, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0x86, (byte) 0xE3, 0x03});\n\t\n\tpublic final static SiMessage sicard8_detected = new SiMessage(new byte[]{\n\t\t\t0x02, (byte) 0xE8, 0x06, 0x00, 0x01, 0x02, 0x1E, (byte) 0x99, 0x5B, (byte) 0xFA, 0x04, 0x03});\n\n\tpublic final static SiMessage sicard8_b0_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x00, (byte) 0xDA, (byte) 0xEE, (byte) 0xA7, 0x71, (byte) 0xEA, (byte) 0xEA, (byte) 0xEA,\n\t\t\t(byte) 0xEA, 0x35, 0x03, 0x70, 0x4D, 0x35, 0x01, 0x70, 0x4E, 0x35, 0x02, 0x70, 0x78, 0x00, 0x1F, 0x01, (byte) 0xF2, 0x02, 0x1E,\n\t\t\t(byte) 0x99, 0x53, 0x0C, (byte) 0xFF, (byte) 0xDD, 0x6F, 0x32, 0x30, 0x30, 0x35, 0x33, 0x33, 0x31, 0x3B, 0x43, 0x68, 0x72, 0x6F, 0x6E,\n\t\t\t0x6F, 0x52, 0x41, 0x49, 0x44, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x67, (byte) 0x90, 0x03});\n\t\n\tpublic final static SiMessage sicard8_b1_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x35, 0x1F, 0x70, 0x62, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, \n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, \n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, \n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, \n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, \n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, \n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, \n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, \n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, 0x6C, 0x64, 0x03\n\t});\n\t\n\tpublic final static SiMessage sicard9_b0_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x00, (byte) 0xAD, (byte) 0xC3, (byte) 0xAC, 0x72, (byte) 0xEA, (byte) 0xEA, (byte) 0xEA,\n\t\t\t(byte) 0xEA, 0x20, 0x04, (byte) 0x9D, (byte) 0xA7, 0x10, (byte) 0xCE, (byte) 0x9E, 0x71, 0x11, (byte) 0xC9,\t0x03, (byte) 0xAF, 0x00,\n\t\t\t(byte) 0xC8, 0x13, (byte) 0x83, 0x01, 0x10, 0x32, (byte) 0x87, 0x0C, (byte) 0xFF, (byte) 0xBE, 0x10, 0x53, 0x69, 0x6D, 0x6F, 0x6E, 0x3B,\n\t\t\t0x44, 0x45, 0x4E, 0x49,\t0x45, 0x52, 0x3B, 0x00, 0x00, 0x00, 0x49, 0x44, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, (byte) 0x86, (byte) 0x9E,\n\t\t\t(byte) 0xE7, 0x30, (byte) 0x8D, (byte) 0x9F, 0x3F, 0x30, (byte) 0x8F, (byte) 0x9F, (byte) 0x8C, 0x30, (byte) 0x90, (byte) 0x9F, (byte) 0xE7,\n\t\t\t0x30, (byte) 0x95, (byte) 0xA0, 0x37, 0x30, (byte) 0x97, (byte) 0xA0, (byte) 0xF7, 0x30, (byte) 0x98, (byte) 0xA1, 0x62, 0x30, (byte) 0x9C,\n\t\t\t(byte) 0xA1, (byte) 0xDA, 0x30, (byte) 0x9E, (byte) 0xA6, (byte) 0xAB, 0x30, (byte) 0xA0, (byte) 0xA7, (byte) 0xAA, 0x30, (byte) 0xA1,\n\t\t\t(byte) 0xA8, 0x16, 0x31, (byte) 0xA4, 0x00, 0x08, 0x31, (byte) 0xA5, 0x00, (byte) 0x9E, 0x31, (byte) 0xA3, 0x01, 0x1F, 0x11, (byte) 0xAB,\n\t\t\t0x02, 0x78, 0x11, (byte) 0xAD, 0x03, 0x11, 0x11, (byte) 0xAF, 0x03, 0x3D, 0x31, (byte) 0xA9, 0x03, (byte) 0x85, (byte) 0x87, 0x1E, 0x03});\n\n\tpublic final static SiMessage sicard9_b1_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x01, 0x11, (byte) 0xC8, 0x03, (byte) 0xA3, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, 0x23, (byte) 0xCA, 0x03});\n\n\tpublic final static SiMessage sicard10_detected = new SiMessage(new byte[]{\n\t\t\t0x02, (byte) 0xE8, 0x06, 0x00, 0x01, 0x0F, 0x76, (byte) 0x9E, 0x72, 0x0B, (byte) 0xD2, 0x03});\n\n\tpublic final static SiMessage sicard10_b0_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x00, (byte) 0x89, (byte) 0xB9, 0x4E, (byte) 0x99, (byte) 0xEA, (byte) 0xEA, (byte) 0xEA,\n\t\t\t(byte) 0xEA, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, 0x02, (byte) 0xFE, 0x03, (byte) 0xE3, 0x0F, 0x76, (byte) 0x9E, 0x72, 0x01, 0x0D, (byte) 0xB8,\n\t\t\t0x14, 0x45, 0x72, 0x69, 0x63, 0x3B, 0x4D, 0x45, 0x52, 0x4D, 0x49, 0x4E, 0x3B, 0x6D, 0x3B, 0x31, 0x39, 0x36, 0x31, 0x3B, 0x4F, 0x52,\n\t\t\t0x49, 0x45, 0x4E, 0x74, (byte) 0x99, 0x27, 0x41, 0x4C, 0x50, 0x3B, 0x65, 0x72, 0x69, 0x63, 0x2E, 0x6D, 0x65, 0x72, 0x6D, 0x69, 0x6E,\n\t\t\t0x40, 0x66, 0x72, 0x65, 0x65, 0x2E, 0x66, 0x72, 0x3B, 0x3B, 0x56, 0x49, 0x5A, 0x49, 0x4C, 0x4C, 0x45, 0x3B, 0x33, 0x30, 0x34, 0x20,\n\t\t\t0x61, 0x76, 0x65, 0x6E, 0x75, 0x65, 0x20, 0x61, 0x72, 0x69, 0x73, 0x74, 0x69, 0x64, 0x65, 0x20, 0x62, 0x72, 0x69, 0x61, 0x6E, 0x64,\n\t\t\t0x3B, 0x33, 0x38, 0x32, 0x32, 0x30, 0x3B, 0x46, 0x52, 0x41, 0x61, (byte) 0xAA, 0x03});\n\t\n\tpublic final static SiMessage sicard10_b1_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x01, 0x3B, 0x00, 0x00, 0x00, 0x52, 0x41, 0x3B, 0x00, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEB, (byte) 0xEB, (byte) 0xEB, (byte) 0xEB, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xDA, (byte) 0x9A, 0x03});\n\n\tpublic final static SiMessage sicard10_b2_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x02, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEC, (byte) 0xEC,\n\t\t\t(byte) 0xEC, (byte) 0xEC, 0x17, (byte) 0xAA, 0x03});\n\t\n\tpublic final static SiMessage sicard10_b3_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x03, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, 0x0D, 0x01, 0x08, 0x01, 0x01, 0x02, 0x02, 0x05, (byte) 0xFF, (byte) 0xFF,\n\t\t\t(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 0x18, 0x00, 0x05, 0x4A, 0x08, 0x00, 0x05, 0x0A, 0x05,\n\t\t\t(byte) 0xAA, 0x01, (byte) 0x8E, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xCA, (byte) 0xAA, (byte) 0xCC, (byte) 0xAC, (byte) 0xAC, (byte) 0xCA, (byte) 0xAA, (byte) 0xAC, (byte) 0xCA, (byte) 0xAA,\n\t\t\t(byte) 0xCA, (byte) 0xAC, (byte) 0xCC, (byte) 0xCC, (byte) 0xAA, (byte) 0xAA, 0x73, 0x69, 0x61, 0x63, (byte) 0xFF, (byte) 0xFF,\n\t\t\t(byte) 0xFF, (byte) 0xFF, (byte) 0x87, (byte) 0xE4, (byte) 0xE8, 0x02, 0x06, (byte) 0xDE, 0x00, 0x00, 0x3E, (byte) 0xD9, 0x03});\n\n\tpublic final static SiMessage sicard10_b4_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x04, 0x05, 0x2A, 0x09, (byte) 0xCA, 0x05, 0x26, 0x09, (byte) 0xD1, 0x29, 0x20, 0x14,\n\t\t\t0x4D, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, 0x78, 0x0A, 0x03});\n\t\n\tpublic final static SiMessage sicard10_b5_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x05, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xFB, (byte) 0x8D, 0x03});\n\n\tpublic final static SiMessage sicard10_b6_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x06, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xC1, (byte) 0x8D, 0x03});\n\n\tpublic final static SiMessage sicard10_b7_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x07, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xC4, 0x00,\n\t\t\t(byte) 0xC4, (byte) 0x8E, (byte) 0xB2, 0x03});\n\n\tpublic final static SiMessage sicard11_detected = new SiMessage(new byte[]{\n\t\t\t0x02, (byte) 0xE8, 0x06, 0x00, 0x01, 0x0F, (byte) 0x98, 0x7E, 0x52, (byte) 0xC6, 0x45, 0x03});\n\t\n\tpublic final static SiMessage sicard11_b0_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x00, (byte) 0xB2, 0x23, (byte) 0xE1, (byte) 0x98, (byte) 0xEA, (byte) 0xEA, (byte) 0xEA,\n\t\t\t(byte) 0xEA, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, 0x12, 0x01, 0x7F,\n\t\t\t(byte) 0xB9, 0x03, (byte) 0xE3, 0x04, (byte) 0xB0, 0x0F, (byte) 0x98, 0x7E, 0x52, 0x01, 0x0D, 0x0A, (byte) 0xB0, 0x45, 0x72, 0x69, 0x63,\n\t\t\t0x3B, 0x4D, 0x45, 0x52, 0x4D, 0x49, 0x4E, 0x3B, 0x6D, 0x3B, 0x31, 0x39, 0x36, 0x31, 0x3B, 0x3B, 0x65, 0x72, 0x69, 0x63, 0x2E, 0x6D, 0x65,\n\t\t\t0x72, 0x6D, 0x69, 0x6E, 0x40, 0x66, 0x72, 0x65, 0x65, 0x2E, 0x66, 0x72, 0x3B, 0x3B, 0x56, 0x49, 0x5A, 0x49, 0x4C, 0x4C, 0x45, 0x3B, 0x33,\n\t\t\t0x30, 0x34, 0x20, 0x61, 0x76, 0x65, 0x6E, 0x75, 0x65, 0x20, 0x61, 0x72, 0x69, 0x73, 0x74, 0x69, 0x64, 0x65, 0x20, 0x62, 0x72, 0x69, 0x61,\n\t\t\t0x6E, 0x64, 0x3B, 0x33, 0x38, 0x32, 0x32, 0x30, 0x3B, 0x46, 0x52, 0x41, 0x3B, 0x00, 0x00, 0x46, 0x52, 0x41, 0x3B, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, 0x78, (byte) 0x95, 0x03});\n\n\tpublic final static SiMessage sicard11_b4_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x04, 0x09, 0x26, 0x2D, (byte) 0xB7, 0x05, 0x2A, 0x0B, 0x7F, 0x05, 0x26, 0x0B, (byte) 0x8A,\n\t\t\t0x29, 0x20, 0x14, (byte) 0xC0, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xD0, (byte) 0xED, 0x03});\n\n\tpublic final static SiMessage sicard11_b5_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x05, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xFB, (byte) 0x8D, 0x03});\n\n\tpublic final static SiMessage sicard11_b6_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x06, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xC1, (byte) 0x8D, 0x03});\n\n\tpublic final static SiMessage sicard11_b7_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xEF, (byte) 0x83, 0x00, 0x01, 0x07, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, 0x00, (byte) 0xC4, 0x00,\n\t\t\t(byte) 0xC4, (byte) 0x8E, (byte) 0xB2, 0x03});\n\n\tpublic final static SiMessage sicard6_192p_b0_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE1, (byte) 0x83, 0x00, 0x06, 0x00, 0x01, 0x01, 0x01, 0x02, (byte) 0xED, (byte) 0xED, (byte) 0xED, (byte) 0xED, 0x55,\n\t\t\t(byte) 0xAA, 0x00, 0x0C, (byte) 0x87, 0x0B, (byte) 0xBA, (byte) 0xA3, (byte) 0x80, 0x7A, 0x65, 0x66, 0x0D, 0x0A, 0x15, 0x6C, 0x06, 0x08,\n\t\t\t(byte) 0x8F, (byte) 0x90, 0x06, 0x04, (byte) 0x8F, (byte) 0x8E, 0x06, 0x07, (byte) 0x8F, (byte) 0x8B, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, 0x00, 0x00, 0x00, 0x00, 0x20, 0x20, 0x20, 0x20, 0x4D, 0x61, 0x72, 0x69, 0x71, 0x75, 0x65, 0x20, 0x20, 0x20,\n\t\t\t0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x52, 0x6F, 0x62, 0x65, 0x72, 0x74, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,\n\t\t\t0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x48, 0x65, 0x72, 0x6D, 0x61, 0x74, 0x68, 0x65, 0x6E, 0x61,\n\t\t\t0x65, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,\n\t\t\t0x20, 0x20, 0x20, 0x20, (byte) 0xF0, 0x22, 0x03});\n\n\tpublic final static SiMessage sicard6_192p_b1_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE1, (byte) 0x83, 0x00, 0x06, 0x01, 0x33, 0x37, 0x30, 0x35, 0x43, 0x45, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,\n\t\t\t0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x6D, 0x61, 0x40,\n\t\t\t0x68, 0x65, 0x6C, 0x67, 0x61, 0x2D, 0x6F, 0x2E, 0x63, 0x6F, 0x6D, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,\n\t\t\t0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,\n\t\t\t0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,\n\t\t\t0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x30, 0x30, 0x30, 0x6D, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,\n\t\t\t0x06, 0x03, 0x14, 0x06, 0x31, 0x29, 0x03});\n\t\n\tpublic final static SiMessage sicard6_192p_b2_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE1, (byte) 0x83, 0x00, 0x06, 0x02, 0x06, 0x23, (byte) 0x90, 0x4F, 0x06, 0x1F, (byte) 0x90, 0x53, 0x06, 0x20, (byte) 0x90,\n\t\t\t0x55, 0x06, 0x21, (byte) 0x90, 0x57, 0x06, 0x22, (byte) 0x90, 0x59, 0x06, 0x23, (byte) 0x90, 0x5C, 0x06, 0x1F, (byte) 0x90, 0x60, 0x06,\n\t\t\t0x20, (byte) 0x90, 0x62, 0x06, 0x21, (byte) 0x90, 0x64, 0x06, 0x22, (byte) 0x90, 0x66, 0x06, 0x23, (byte) 0x90, 0x69, 0x06, 0x1F,\n\t\t\t(byte) 0x90, 0x6E, 0x06, 0x20, (byte) 0x90, 0x72, 0x06, 0x21, (byte) 0x90, 0x77, 0x06, 0x22, (byte) 0x90, 0x7A, 0x06, 0x23,\t(byte) 0x90,\n\t\t\t0x7D, 0x06, 0x1F, (byte) 0x90, (byte) 0x82, 0x06, 0x20, (byte) 0x90, (byte) 0x84, 0x06, 0x21, (byte) 0x90, (byte) 0x87, 0x06, 0x22,\n\t\t\t(byte) 0x90, (byte) 0x89, 0x06, 0x23, (byte) 0x90, (byte) 0x8B, 0x06, 0x1F, (byte) 0x90, (byte) 0x8F, 0x06, 0x20, (byte) 0x90,\n\t\t\t(byte) 0x91, 0x06, 0x21, (byte) 0x90, (byte) 0x93, 0x06, 0x22, (byte) 0x90, (byte) 0x96, 0x06, 0x23, (byte) 0x90, (byte) 0x98, 0x06,\n\t\t\t0x1F, (byte) 0x90, (byte) 0x9C, 0x06, 0x20, (byte) 0x90, (byte) 0x9D, 0x06, 0x21, (byte) 0x90, (byte) 0x9F, 0x06, 0x22, (byte) 0x90,\n\t\t\t(byte) 0xA2, 0x06, 0x23, (byte) 0x90, (byte) 0xA4, 0x06, 0x1F, (byte) 0x90, (byte) 0xA8, (byte) 0xF2, 0x19, 0x03});\n\t\n\tpublic final static SiMessage sicard6_192p_b3_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE1, (byte) 0x83, 0x00, 0x06, 0x03, 0x06, 0x20, (byte) 0x90, (byte) 0xAA, 0x06, 0x21, (byte) 0x90, (byte) 0xAC, 0x06, 0x22,\n\t\t\t(byte) 0x90, (byte) 0xAE, 0x06, 0x23, (byte) 0x90, (byte) 0xB0, (byte) 0x8D, 0x7A, 0x15, 0x31, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xB5, (byte) 0x9B, 0x03});\n\t\n\tpublic final static SiMessage sicard6_192p_b4_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE1, (byte) 0x83, 0x00, 0x06, 0x04, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xBC, (byte) 0xE3, 0x03});\n\t\n\tpublic final static SiMessage sicard6_192p_b5_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE1, (byte) 0x83, 0x00, 0x06, 0x05, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE, (byte) 0xEE,\n\t\t\t(byte) 0xEE, (byte) 0xEE, (byte) 0xAA, (byte) 0xE3, 0x03});\n\t\n\tpublic final static SiMessage sicard6_192p_b6_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE1, (byte) 0x83, 0x00, 0x06, 0x06, 0x06, 0x1F, (byte) 0x8F, (byte) 0x9A, 0x06, 0x20, (byte) 0x8F, (byte) 0x9C, 0x06,\n\t\t\t0x21, (byte) 0x8F, (byte) 0x9E, 0x06, 0x22, (byte) 0x8F, (byte) 0xA0, 0x06, 0x23, (byte) 0x8F, (byte) 0xA3, 0x06, 0x1F, (byte) 0x8F,\n\t\t\t(byte) 0xAB, 0x06, 0x20, (byte) 0x8F, (byte) 0xAD, 0x06, 0x21, (byte) 0x8F, (byte) 0xAF, 0x06, 0x22, (byte) 0x8F, (byte) 0xB1, 0x06,\n\t\t\t0x23, (byte) 0x8F, (byte) 0xB3, 0x06, 0x1F, (byte) 0x8F, (byte) 0xB7, 0x06, 0x20, (byte) 0x8F, (byte) 0xB9, 0x06, 0x21, (byte) 0x8F,\n\t\t\t(byte) 0xBB, 0x06, 0x22, (byte) 0x8F, (byte) 0xBE, 0x06, 0x23, (byte) 0x8F, (byte) 0xC1, 0x06, 0x1F, (byte) 0x8F, (byte) 0xC6, 0x06,\n\t\t\t0x20, (byte) 0x8F, (byte) 0xC9, 0x06, 0x21, (byte) 0x8F, (byte) 0xCB, 0x06, 0x22, (byte) 0x8F, (byte) 0xCD, 0x06, 0x23, (byte) 0x8F,\n\t\t\t(byte) 0xD0, 0x06, 0x1F, (byte) 0x8F, (byte) 0xD5, 0x06, 0x20, (byte) 0x8F, (byte) 0xD7, 0x06, 0x21, (byte) 0x8F, (byte) 0xD9, 0x06,\n\t\t\t0x22, (byte) 0x8F, (byte) 0xDB, 0x06, 0x23, (byte) 0x8F, (byte) 0xDD, 0x06, 0x1F, (byte) 0x8F, (byte) 0xE2, 0x06, 0x20, (byte) 0x8F,\n\t\t\t(byte) 0xE4, 0x06, 0x21, (byte) 0x8F, (byte) 0xE6, 0x06, 0x22, (byte) 0x8F, (byte) 0xE8, 0x06, 0x23, (byte) 0x8F, (byte) 0xEA, 0x06,\n\t\t\t0x1F, (byte) 0x8F, (byte) 0xEF, 0x06, 0x20, (byte) 0x8F, (byte) 0xF1, (byte) 0xE7, (byte) 0xF0, 0x03});\n\t\n\tpublic final static SiMessage sicard6_192p_b7_data = new SiMessage(new byte[] {\n\t\t\t0x02, (byte) 0xE1, (byte) 0x83, 0x00, 0x06, 0x07, 0x06, 0x21, (byte) 0x8F, (byte) 0xF3, 0x06, 0x22, (byte) 0x8F, (byte) 0xF5, 0x06,\n\t\t\t0x23, (byte) 0x8F, (byte) 0xF8, 0x06, 0x1F, (byte) 0x8F, (byte) 0xFD, 0x06, 0x20, (byte) 0x8F, (byte) 0xFF, 0x06, 0x21, (byte) 0x90,\n\t\t\t0x01, 0x06, 0x22, (byte) 0x90, 0x03, 0x06, 0x23, (byte) 0x90, 0x06, 0x06, 0x1F, (byte) 0x90, 0x0A, 0x06, 0x20, (byte) 0x90, 0x0D,\n\t\t\t0x06, 0x21, (byte) 0x90, 0x0F, 0x06, 0x22, (byte) 0x90, 0x12, 0x06, 0x23, (byte) 0x90, 0x15, 0x06, 0x1F, (byte) 0x90, 0x1A, 0x06,\n\t\t\t0x20, (byte) 0x90, 0x1C, 0x06, 0x21, (byte) 0x90, 0x1F, 0x06, 0x22, (byte) 0x90, 0x22, 0x06, 0x23, (byte) 0x90, 0x24, 0x06, 0x1F,\n\t\t\t(byte) 0x90, 0x29, 0x06, 0x20, (byte) 0x90, 0x2B, 0x06, 0x21, (byte) 0x90, 0x2E, 0x06, 0x22, (byte) 0x90, 0x30, 0x06, 0x23, (byte) 0x90,\n\t\t\t0x33, 0x06, 0x1F, (byte) 0x90, 0x37, 0x06, 0x20, (byte) 0x90, 0x3A, 0x06, 0x21, (byte) 0x90, 0x3C, 0x06, 0x22, (byte) 0x90, 0x3F, 0x06,\n\t\t\t0x23, (byte) 0x90, 0x41, 0x06, 0x1F, (byte) 0x90, 0x45, 0x06, 0x20, (byte) 0x90, 0x47, 0x06, 0x21, (byte) 0x90, 0x49, 0x06, 0x22,\n\t\t\t(byte) 0x90, 0x4C, (byte) 0x8D, (byte) 0xC9, 0x03});\n\t\n}" ]
import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import net.gecosi.dataframe.Si5DataFrame; import net.gecosi.dataframe.SiDataFrame; import net.gecosi.dataframe.SiPunch; import net.gecosi.internal.SiMessage; import org.junit.Test; import test.net.gecosi.SiMessageFixtures;
/** * Copyright (c) 2013 Simon Denier */ package test.net.gecosi.dataframe; /** * @author Simon Denier * @since Mar 15, 2013 * */ public class Si5DataFrameTest { @Test public void getSiCardNumber() { assertThat(subject304243().getSiNumber(), equalTo("304243")); assertThat(subject36353().getSiNumber(), equalTo("36353")); } @Test public void getSiCardSeries() { assertThat(subject36353().getSiSeries(), equalTo("SiCard 5")); } @Test public void getStartTime() { assertThat(subject36353().getStartTime(), equalTo(1234000L)); } @Test public void getFinishTime() { assertThat(subject36353().getFinishTime(), equalTo(4321000L)); } @Test public void getCheckTime() { assertThat(subject36353().getCheckTime(), equalTo(4444000L)); } @Test public void getNbPunches() { assertThat(subject36353().getNbPunches(), equalTo(36)); } @Test public void getPunches() { SiPunch[] punches = subject36353().getPunches(); assertThat(punches[0].code(), equalTo(36)); assertThat(punches[0].timestamp(), equalTo(40059000L)); assertThat(punches[9].code(), equalTo(59)); assertThat(punches[9].timestamp(), equalTo(40104000L)); } @Test public void getPunches_with36Punches() { SiPunch[] punches = subject36353().getPunches(); assertThat(punches[30].code(), equalTo(31)); assertThat(punches[30].timestamp(), equalTo(Si5DataFrame.NO_TIME)); assertThat(punches[35].code(), equalTo(36)); assertThat(punches[35].timestamp(), equalTo(Si5DataFrame.NO_TIME)); } @Test public void getPunches_withZeroHourShift() { SiDataFrame subject = subject36353().startingAt(41400000L); assertThat(subject.getStartTime(), equalTo(44434000L)); assertThat(subject.getFinishTime(), equalTo(47521000L)); SiPunch[] punches = subject.getPunches(); assertThat(punches[9].timestamp(), equalTo(83304000L)); assertThat(punches[10].timestamp(), equalTo(Si5DataFrame.NO_TIME)); assertThat(punches[35].timestamp(), equalTo(Si5DataFrame.NO_TIME)); } @Test public void getPunches_withoutStartTime() { SiDataFrame subject = subject304243(); assertThat(subject.getStartTime(), equalTo(SiDataFrame.NO_TIME)); assertThat(subject.getFinishTime(), equalTo(43704000L)); SiPunch[] punches = subject.getPunches(); assertThat(punches[0].timestamp(), equalTo(40059000L)); assertThat(punches[9].timestamp(), equalTo(40104000L)); } @Test public void getPunches_withoutStartTime_withMidnightShift() { SiDataFrame subject = subject304243().startingAt(82800000L); assertThat(subject.getStartTime(), equalTo(SiDataFrame.NO_TIME)); assertThat(subject.getFinishTime(), equalTo(86904000L)); SiPunch[] punches = subject.getPunches(); assertThat(punches[0].timestamp(), equalTo(83259000L)); assertThat(punches[9].timestamp(), equalTo(83304000L)); } @Test public void advanceTimePast_doesNotChangeTimeWhen() { Si5DataFrame subject = (Si5DataFrame) subject36353(); assertThat("Time already past Ref", subject.advanceTimePast(1000, 0), equalTo(1000L)); assertThat("Time less than 1 hour behind Ref", subject.advanceTimePast(1000, 1500), equalTo(1000L)); assertThat("No time for Ref", subject.advanceTimePast(1000, SiDataFrame.NO_TIME), equalTo(1000L)); } @Test public void advanceTimePast_advancesBy12HoursStep() { Si5DataFrame subject = (Si5DataFrame) subject36353(); assertThat(subject.advanceTimePast(0, 3600001), equalTo(43200000L)); assertThat(subject.advanceTimePast(3600000, 100000000L), equalTo(133200000L)); // + 36 hours } @Test public void advanceTimePast_returnsNoTime() { Si5DataFrame subject = (Si5DataFrame) subject36353(); assertThat("Time is unknown", subject.advanceTimePast(0xEEEE * 1000, 0), equalTo(SiDataFrame.NO_TIME)); } private SiDataFrame subject304243() {
return new Si5DataFrame(SiMessageFixtures.sicard5_data).startingAt(0);
4
brutusin/wava
wava-core/src/main/java/org/brutusin/wava/core/io/CommandLineRequestExecutor.java
[ "public enum OpName {\n submit,\n cancel,\n jobs,\n group,\n exit\n}", "public enum Event {\r\n\r\n id,\r\n queued,\r\n priority,\r\n running,\r\n niceness,\r\n retcode,\r\n cancelled,\r\n ping,\r\n error,\r\n exceed_tree,\r\n shutdown,\r\n maxrss,\r\n maxswap,\r\n starvation_relaunch,\r\n starvation_stop;\r\n}\r", "public class Utils {\r\n\r\n public final static DateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\r\n private final static File LOCK_FILE = new File(WavaTemp.getInstance().getTemp(), \".lock\");\r\n\r\n public static List<String> parseEventLine(String line) {\r\n List<String> ret = new ArrayList<>();\r\n int start = 0;\r\n boolean inString = false;\r\n for (int i = 0; i < line.length(); i++) {\r\n if (line.charAt(i) == '\"' && (i == 0 || line.charAt(i - 1) != '\\\\')) {\r\n inString = !inString;\r\n }\r\n if (!inString && line.charAt(i) == ':') {\r\n ret.add(line.substring(start, i));\r\n start = i + 1;\r\n }\r\n }\r\n if (start < line.length()) {\r\n ret.add(line.substring(start));\r\n }\r\n return ret;\r\n }\r\n\r\n public static FileLock tryWavaLock() throws IOException {\r\n return tryLock(LOCK_FILE);\r\n }\r\n\r\n private static FileLock tryLock(File f) throws IOException {\r\n synchronized (f) {\r\n if (!f.exists()) {\r\n Miscellaneous.createFile(f.getAbsolutePath());\r\n }\r\n RandomAccessFile raf = new RandomAccessFile(f, \"rws\");\r\n return raf.getChannel().tryLock();\r\n }\r\n }\r\n\r\n public static boolean isCoreRunning() throws IOException {\r\n synchronized (LOCK_FILE) {\r\n FileLock lock = tryWavaLock();\r\n if (lock != null) {\r\n lock.release();\r\n }\r\n return lock == null;\r\n }\r\n }\r\n\r\n public static int getJVMPid() {\r\n try {\r\n String[] cmd = {\"/bin/bash\", \"-c\", \"echo $PPID\"};\r\n return Integer.valueOf(ProcessUtils.executeProcess(cmd));\r\n } catch (Exception ex) {\r\n throw new RuntimeException(ex);\r\n }\r\n }\r\n}\r", "public enum EnvEntry {\r\n WAVA_HOME,\r\n WAVA_JOB_ID,\r\n STDIN_TTY\r\n}\r", "public class Input {\r\n\r\n private final int clientPid = Utils.getJVMPid();\r\n\r\n public int getClientPid() {\r\n return clientPid;\r\n }\r\n}\r", "public interface EventListener {\n\n public void onEvent(Event evt, String value, long time);\n}", "public interface LineListener {\r\n\r\n public void onNewLine(String line);\r\n}\r", "public class RequestExecutor {\r\n\r\n private static final Logger LOGGER = Logger.getLogger(RequestExecutor.class.getName());\r\n private static final File COUNTER_FILE = new File(WavaTemp.getInstance().getTemp(), \"state/.seq\");\r\n\r\n\r\n public Integer executeRequest(OpName opName, Input input, final InputStream stdinStream, final OutputStream stdoutStream, final LineListener stderrListener, final EventListener eventListener) throws IOException {\r\n long id = Miscellaneous.getGlobalAutoIncremental(COUNTER_FILE);\r\n String json = JsonCodec.getInstance().transform(input);\r\n File streamRoot = new File(WavaTemp.getInstance().getTemp(), \"streams/\" + id);\r\n Miscellaneous.createDirectory(streamRoot);\r\n final File stdinNamedPipe = new File(streamRoot, NamedPipe.stdin.name());\r\n final File eventsNamedPipe = new File(streamRoot, NamedPipe.events.name());\r\n final File stdoutNamedPipe = new File(streamRoot, NamedPipe.stdout.name());\r\n final File stderrNamedPipe = new File(streamRoot, NamedPipe.stderr.name());\r\n try {\r\n ProcessUtils.createPOSIXNamedPipes(stdinNamedPipe, eventsNamedPipe, stderrNamedPipe, stdoutNamedPipe);\r\n } catch (Exception ex) {\r\n throw new RuntimeException(ex);\r\n }\r\n final Bean<Integer> retCode = new Bean<>();\r\n final Bean<FileOutputStream> stdinStreamBean = new Bean<>();\r\n final Bean<FileInputStream> eventsStreamBean = new Bean<>();\r\n final Bean<FileInputStream> stdoutStreamBean = new Bean<>();\r\n final Bean<FileInputStream> stderrStreamBean = new Bean<>();\r\n\r\n final Bean<Boolean> timeoutBean = new Bean<>();\r\n\r\n Thread stdinThread = new Thread() {\r\n @Override\r\n public void run() {\r\n FileOutputStream os = null;\r\n try {\r\n os = new FileOutputStream(stdinNamedPipe);\r\n synchronized (timeoutBean) {\r\n if (timeoutBean.getValue() == null) {\r\n timeoutBean.setValue(false);\r\n } else if (timeoutBean.getValue() == true) {\r\n return;\r\n }\r\n }\r\n stdinStreamBean.setValue(os);\r\n if (stdinStream != null) {\r\n Miscellaneous.pipeSynchronously(stdinStream, true, os);\r\n }\r\n } catch (Throwable th) {\r\n LOGGER.log(Level.SEVERE, th.getMessage(), th);\r\n } finally {\r\n if (os != null) {\r\n try {\r\n os.close();\r\n } catch (IOException ex) {\r\n LOGGER.log(Level.SEVERE, null, ex);\r\n }\r\n }\r\n }\r\n }\r\n };\r\n stdinThread.setDaemon(true);\r\n stdinThread.start();\r\n\r\n Thread eventsThread = new Thread() {\r\n @Override\r\n public void run() {\r\n FileInputStream is = null;\r\n try {\r\n is = new FileInputStream(eventsNamedPipe);\r\n synchronized (timeoutBean) {\r\n if (timeoutBean.getValue() == null) {\r\n timeoutBean.setValue(false);\r\n } else if (timeoutBean.getValue() == true) {\r\n return;\r\n }\r\n }\r\n eventsStreamBean.setValue(is);\r\n BufferedReader br = new BufferedReader(new InputStreamReader(is));\r\n String line;\r\n while ((line = br.readLine()) != null) {\r\n List<String> tokens = Utils.parseEventLine(line);\r\n Event evt = Event.valueOf(tokens.get(1));\r\n String value;\r\n if (tokens.size() > 2) {\r\n value = tokens.get(2);\r\n if (evt == Event.retcode) {\r\n retCode.setValue(Integer.valueOf(value));\r\n }\r\n } else {\r\n value = null;\r\n }\r\n if (eventListener != null) {\r\n eventListener.onEvent(evt, value, Long.valueOf(tokens.get(0)));\r\n }\r\n }\r\n } catch (Throwable th) {\r\n LOGGER.log(Level.SEVERE, th.getMessage(), th);\r\n } finally {\r\n if (is != null) {\r\n try {\r\n is.close();\r\n } catch (IOException ex) {\r\n LOGGER.log(Level.SEVERE, null, ex);\r\n }\r\n }\r\n }\r\n }\r\n };\r\n eventsThread.start();\r\n Thread outThread = new Thread() {\r\n @Override\r\n public void run() {\r\n FileInputStream is = null;\r\n try {\r\n is = new FileInputStream(stdoutNamedPipe);\r\n synchronized (timeoutBean) {\r\n if (timeoutBean.getValue() == null) {\r\n timeoutBean.setValue(false);\r\n } else if (timeoutBean.getValue() == true) {\r\n return;\r\n }\r\n }\r\n stdoutStreamBean.setValue(is);\r\n Miscellaneous.pipeSynchronously(is, true, stdoutStream);\r\n } catch (Throwable th) {\r\n LOGGER.log(Level.SEVERE, th.getMessage(), th);\r\n } finally {\r\n if (is != null) {\r\n try {\r\n is.close();\r\n } catch (IOException ex) {\r\n LOGGER.log(Level.SEVERE, null, ex);\r\n }\r\n }\r\n }\r\n }\r\n };\r\n outThread.start();\r\n Thread errThread = new Thread() {\r\n @Override\r\n public void run() {\r\n FileInputStream is = null;\r\n try {\r\n is = new FileInputStream(stderrNamedPipe);\r\n synchronized (timeoutBean) {\r\n if (timeoutBean.getValue() == null) {\r\n timeoutBean.setValue(false);\r\n } else if (timeoutBean.getValue() == true) {\r\n return;\r\n }\r\n }\r\n stderrStreamBean.setValue(is);\r\n BufferedReader br = new BufferedReader(new InputStreamReader(is));\r\n String line;\r\n while ((line = br.readLine()) != null) {\r\n if (stderrListener != null) {\r\n stderrListener.onNewLine(line);\r\n }\r\n }\r\n } catch (Throwable th) {\r\n LOGGER.log(Level.SEVERE, th.getMessage(), th);\r\n } finally {\r\n if (is != null) {\r\n try {\r\n is.close();\r\n } catch (IOException ex) {\r\n LOGGER.log(Level.SEVERE, null, ex);\r\n }\r\n }\r\n }\r\n }\r\n };\r\n errThread.start();\r\n\r\n Thread timeoutThread = new Thread() {\r\n @Override\r\n public void run() {\r\n try {\r\n Thread.sleep(10 * 1000); // If after this time the pipes have not been open for reading (nobody is using the other side) discard all\r\n synchronized (timeoutBean) {\r\n if (timeoutBean.getValue() == null) {\r\n timeoutBean.setValue(true);\r\n try {\r\n new FileOutputStream(eventsNamedPipe).close();\r\n } catch (Exception ex) {\r\n }\r\n try {\r\n new FileOutputStream(stdoutNamedPipe).close();\r\n } catch (Exception ex) {\r\n }\r\n try {\r\n new FileOutputStream(stderrNamedPipe).close();\r\n } catch (Exception ex) {\r\n }\r\n try {\r\n new FileInputStream(stdinNamedPipe).close();\r\n } catch (Exception ex) {\r\n }\r\n }\r\n }\r\n } catch (InterruptedException ex) {\r\n LOGGER.log(Level.SEVERE, null, ex);\r\n }\r\n }\r\n };\r\n timeoutThread.setDaemon(true);\r\n timeoutThread.start();\r\n\r\n File tempFile = new File(WavaTemp.getInstance().getTemp(), \"temp/\" + id + \"-\" + opName);\r\n File requestFile = new File(WavaTemp.getInstance().getTemp(), \"request/\" + id + \"-\" + opName);\r\n\r\n Files.write(tempFile.toPath(), json.getBytes());\r\n Files.move(tempFile.toPath(), requestFile.toPath());\r\n\r\n try {\r\n errThread.join();\r\n eventsThread.join();\r\n outThread.join();\r\n } catch (InterruptedException i) {\r\n } finally {\r\n if (stdinStreamBean.getValue() != null) {\r\n try {\r\n stdinStreamBean.getValue().close();\r\n } catch (IOException ex) {\r\n LOGGER.log(Level.SEVERE, ex.getMessage(), ex);\r\n }\r\n }\r\n if (eventsStreamBean.getValue() != null) {\r\n try {\r\n eventsStreamBean.getValue().close();\r\n } catch (IOException ex) {\r\n LOGGER.log(Level.SEVERE, ex.getMessage(), ex);\r\n }\r\n }\r\n if (stdoutStreamBean.getValue() != null) {\r\n try {\r\n stdoutStreamBean.getValue().close();\r\n } catch (IOException ex) {\r\n LOGGER.log(Level.SEVERE, ex.getMessage(), ex);\r\n }\r\n }\r\n if (stderrStreamBean.getValue() != null) {\r\n try {\r\n stderrStreamBean.getValue().close();\r\n } catch (IOException ex) {\r\n LOGGER.log(Level.SEVERE, ex.getMessage(), ex);\r\n }\r\n }\r\n }\r\n return retCode.getValue();\r\n }\r\n\r\n}\r", "public enum ANSICode {\r\n\r\n BLACK(\"\\u001B[30m\"),\r\n RED(\"\\u001B[31m\"),\r\n GREEN(\"\\u001B[32m\"),\r\n YELLOW(\"\\u001B[33m\"),\r\n BLUE(\"\\u001B[34m\"),\r\n PURPLE(\"\\u001B[35m\"),\r\n CYAN(\"\\u001B[36m\"),\r\n WHITE(\"\\u001B[37m\"),\r\n BG_GREEN(\"\\u001b[42m\"),\r\n BG_BLACK(\"\\u001b[40m\"),\r\n BG_RED(\"\\u001b[41m\"),\r\n BG_YELLOW(\"\\u001b[43m\"),\r\n BG_BLUE(\"\\u001b[44m\"),\r\n BG_MAGENTA(\"\\u001b[45m\"),\r\n BG_CYAN(\"\\u001b[46m\"),\r\n BG_WHITE(\"\\u001b[47m\"),\r\n RESET(\"\\u001B[0m\"),\r\n BOLD(\"\\u001b[1m\"),\r\n UNDERLINED(\"\\u001b[4m\"),\r\n BLINK(\"\\u001b[5m\"),\r\n REVERSED(\"\\u001b[7m\"),\r\n INVISIBLE(\"\\u001b[8m\"),\r\n END_OF_LINE(\"\\u001b[K\"),\r\n MOVE_TO_TOP(\"\\u001b[0;0f\"),\r\n NO_WRAP(\"\\u001b[?7l\"),\r\n WRAP(\"\\u001b[?7h\"),\r\n CLEAR(\"\\u001b[2J\");\r\n\r\n private final String code;\r\n\r\n private static final ThreadLocal<Boolean> ACTIVE = new ThreadLocal<Boolean>() {\r\n\r\n @Override\r\n protected Boolean initialValue() {\r\n return Config.getInstance().getuICfg().isAnsiColors();\r\n }\r\n\r\n };\r\n\r\n ANSICode(String code) {\r\n this.code = code;\r\n }\r\n\r\n public static void setActive(boolean active) {\r\n ACTIVE.set(active && Config.getInstance().getuICfg().isAnsiColors());\r\n }\r\n\r\n public static boolean isActive() {\r\n return ACTIVE.get();\r\n }\r\n\r\n public String getCode() {\r\n if (isActive()) {\r\n return code;\r\n } else {\r\n return \"\";\r\n }\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return getCode();\r\n }\r\n}\r" ]
import org.brutusin.wava.io.LineListener; import org.brutusin.wava.io.RequestExecutor; import org.brutusin.wava.utils.ANSICode; import org.brutusin.wava.io.OpName; import org.brutusin.wava.io.Event; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import org.brutusin.json.ParseException; import org.brutusin.json.spi.JsonCodec; import org.brutusin.json.spi.JsonNode; import org.brutusin.wava.Utils; import org.brutusin.wava.env.EnvEntry; import org.brutusin.wava.input.Input; import org.brutusin.wava.io.EventListener;
/* * Copyright 2016 Ignacio del Valle Alles [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.brutusin.wava.core.io; /** * * @author Ignacio del Valle Alles [email protected] */ public class CommandLineRequestExecutor extends RequestExecutor { public Integer executeRequest(OpName opName, Input input) throws IOException, InterruptedException { if (input == null) { input = new Input(); } return executeRequest(opName, input, null, false); } public Integer executeRequest(OpName opName, Input input, final OutputStream eventStream, boolean prettyEvents) throws IOException, InterruptedException { EventListener evtListener = null; if (eventStream != null) { evtListener = new EventListener() { @Override public void onEvent(Event evt, String value, long time) { if (evt == Event.ping) { return; } if (!prettyEvents) { synchronized (eventStream) { try { if (value == null) { eventStream.write((time + ":" + evt.name() + "\n").getBytes()); } else { eventStream.write((time + ":" + evt.name() + ":" + value + "\n").getBytes()); } } catch (IOException ex) { Logger.getLogger(CommandLineRequestExecutor.class.getName()).log(Level.SEVERE, null, ex); } } } else { Date date = new Date(time); ANSICode color = ANSICode.CYAN; if (evt == Event.id || evt == Event.running) { color = ANSICode.GREEN; } else if (evt == Event.queued) { color = ANSICode.YELLOW; } else if (evt == Event.cancelled) { color = ANSICode.YELLOW; } else if (evt == Event.retcode) { if (value.equals("0")) { color = ANSICode.GREEN; } else { color = ANSICode.RED; } } else if (evt == Event.error) { color = ANSICode.RED; if (value != null) { try { JsonNode node = JsonCodec.getInstance().parse(value); value = node.asString(); } catch (ParseException ex) { Logger.getLogger(CommandLineRequestExecutor.class.getName()).log(Level.SEVERE, null, ex); } } } else if (evt == Event.shutdown) { color = ANSICode.RED; } synchronized (eventStream) { try { eventStream.write((color.getCode() + "[wava] [" + Utils.DATE_FORMAT.format(date) + "] [" + evt + (value != null ? (":" + value) : "") + "]" + ANSICode.RESET.getCode() + "\n").getBytes()); } catch (IOException ex) { Logger.getLogger(CommandLineRequestExecutor.class.getName()).log(Level.SEVERE, null, ex); } } } } }; }
LineListener sterrListener = new LineListener() {
6
naotawool/salary-calculation
src/test/java/salarycalculation/database/EmployeeDaoTest.java
[ "public static EmployeeRecordAssert assertThat(EmployeeRecord actual) {\n return new EmployeeRecordAssert(actual);\n}", "public static RecordNotFoundExceptionMatcher isClass(Class<?> expectEntityClass) {\n return new RecordNotFoundExceptionMatcher(expectEntityClass, null, null);\n}", "public static RecordNotFoundExceptionMatcher isKey(Object expectKey) {\n return new RecordNotFoundExceptionMatcher(null, expectKey, null);\n}", "public class EmployeeRecord {\n\n /** 社員番号 */\n private int no;\n\n /** 社員名 */\n private String name;\n\n /** 組織コード */\n private String organization;\n\n /** 生年月日 */\n private Date birthday;\n\n /** 入社年月日 */\n private Date joinDate;\n\n /** 役割等級 */\n private String roleRank;\n\n /** 能力等級 */\n private String capabilityRank;\n\n /** 通勤手当金額 */\n private int commuteAmount;\n\n /** 住宅手当金額 */\n private int rentAmount;\n\n /** 健康保険金額 */\n private int healthInsuranceAmount;\n\n /** 厚生年金金額 */\n private int employeePensionAmount;\n\n /** 所得税金額 */\n private int incomeTaxAmount;\n\n /** 住民税金額 */\n private int inhabitantTaxAmount;\n\n /** 1時間当たりの時間外手当金額 */\n private int workOverTime1hAmount;\n\n /**\n * 社員番号を取得する。\n *\n * @return 社員番号\n */\n public int getNo() {\n return no;\n }\n\n /**\n * 社員番号を設定する。\n *\n * @param no 社員番号\n */\n public void setNo(int no) {\n this.no = no;\n }\n\n /**\n * 社員名を取得する。\n *\n * @return 社員名\n */\n public String getName() {\n return name;\n }\n\n /**\n * 社員名を設定する。\n *\n * @param name 社員名\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * 組織コードを取得する。\n *\n * @return 組織コード\n */\n public String getOrganization() {\n return organization;\n }\n\n /**\n * 組織コードを設定する。\n *\n * @param organization 組織コード\n */\n public void setOrganization(String organization) {\n this.organization = organization;\n }\n\n /**\n * 生年月日を取得する。\n *\n * @return 生年月日\n */\n public Date getBirthday() {\n return birthday;\n }\n\n /**\n * 生年月日を設定する。\n *\n * @param birthday 生年月日\n */\n public void setBirthday(Date birthday) {\n this.birthday = birthday;\n }\n\n /**\n * 入社年月日を取得する。\n *\n * @return 入社年月日\n */\n public Date getJoinDate() {\n return joinDate;\n }\n\n /**\n * 入社年月日を設定する。\n *\n * @param joinDate 入社年月日\n */\n public void setJoinDate(Date joinDate) {\n this.joinDate = joinDate;\n }\n\n /**\n * 役割等級を取得する。\n *\n * @return 役割等級\n */\n public String getRoleRank() {\n return roleRank;\n }\n\n /**\n * 役割等級を設定する。\n *\n * @param roleRank 役割等級\n */\n public void setRoleRank(String roleRank) {\n this.roleRank = roleRank;\n }\n\n /**\n * 能力等級を取得する。\n *\n * @return 能力等級\n */\n public String getCapabilityRank() {\n return capabilityRank;\n }\n\n /**\n * 能力等級を設定する。\n *\n * @param capabilityRank 能力等級\n */\n public void setCapabilityRank(String capabilityRank) {\n this.capabilityRank = capabilityRank;\n }\n\n /**\n * 通勤手当金額を取得する。\n *\n * @return 通勤手当金額\n */\n public int getCommuteAmount() {\n return commuteAmount;\n }\n\n /**\n * 通勤手当金額を設定する。\n *\n * @param commuteAmount 通勤手当金額\n */\n public void setCommuteAmount(int commuteAmount) {\n this.commuteAmount = commuteAmount;\n }\n\n /**\n * 住宅手当金額を取得する。\n *\n * @return 住宅手当金額\n */\n public int getRentAmount() {\n return rentAmount;\n }\n\n /**\n * 住宅手当金額を設定する。\n *\n * @param rentAmount 住宅手当金額\n */\n public void setRentAmount(int rentAmount) {\n this.rentAmount = rentAmount;\n }\n\n /**\n * 健康保険金額を取得する。\n *\n * @return 健康保険金額\n */\n public int getHealthInsuranceAmount() {\n return healthInsuranceAmount;\n }\n\n /**\n * 健康保険金額を設定する。\n *\n * @param healthInsuranceAmount 健康保険金額\n */\n public void setHealthInsuranceAmount(int healthInsuranceAmount) {\n this.healthInsuranceAmount = healthInsuranceAmount;\n }\n\n /**\n * 厚生年金金額を取得する。\n *\n * @return 厚生年金金額\n */\n public int getEmployeePensionAmount() {\n return employeePensionAmount;\n }\n\n /**\n * 厚生年金金額を設定する。\n *\n * @param employeePensionAmount 厚生年金金額\n */\n public void setEmployeePensionAmount(int employeePensionAmount) {\n this.employeePensionAmount = employeePensionAmount;\n }\n\n /**\n * 所得税金額を取得する。\n *\n * @return 所得税金額\n */\n public int getIncomeTaxAmount() {\n return incomeTaxAmount;\n }\n\n /**\n * 所得税金額を設定する。\n *\n * @param incomeTaxAmount 所得税金額\n */\n public void setIncomeTaxAmount(int incomeTaxAmount) {\n this.incomeTaxAmount = incomeTaxAmount;\n }\n\n /**\n * 住民税金額を取得する。\n *\n * @return 住民税金額\n */\n public int getInhabitantTaxAmount() {\n return inhabitantTaxAmount;\n }\n\n /**\n * 住民税金額を設定する。\n *\n * @param inhabitantTaxAmount 住民税金額\n */\n public void setInhabitantTaxAmount(int inhabitantTaxAmount) {\n this.inhabitantTaxAmount = inhabitantTaxAmount;\n }\n\n /**\n * 1時間当たりの時間外手当金額を取得する。\n *\n * @return 1時間当たりの時間外手当金額\n */\n public int getWorkOverTime1hAmount() {\n return workOverTime1hAmount;\n }\n\n /**\n * 1時間当たりの時間外手当金額を設定する。\n *\n * @param workOverTime1hAmount 1時間当たりの時間外手当金額\n */\n public void setWorkOverTime1hAmount(int workOverTime1hAmount) {\n this.workOverTime1hAmount = workOverTime1hAmount;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append(no).append(name)\n .append(organization).append(birthday).append(joinDate).append(roleRank)\n .append(capabilityRank).append(commuteAmount).append(rentAmount)\n .append(healthInsuranceAmount).append(employeePensionAmount)\n .append(incomeTaxAmount).append(inhabitantTaxAmount).toString();\n }\n}", "public interface CapabilitySetupSupport {\n\n default Operation capabilityInsert() {\n Operation capability = insertInto(\"capability\").columns(\"rank\", \"amount\")\n .values(\"AS\", 50000)\n .values(\"PG\", 100000)\n .values(\"SE\", 150000)\n .values(\"PL\", 270000)\n .values(\"PM\", 300000).build();\n return capability;\n }\n}", "public interface OrganizationSetupSupport {\n\n default Operation organizationInsert() {\n Operation organization = insertInto(\"organization\").columns(\"code\", \"name\")\n .values(\"DEV1\", \"開発部1\")\n .values(\"DEV2\", \"開発部2\")\n .values(\"DEV3\", \"開発部3\")\n .values(\"DEV\", \"開発部\").build();\n return organization;\n }\n}", "public interface RoleSetupSupport {\n\n default Operation roleInsert() {\n Operation role = insertInto(\"role\").columns(\"rank\", \"amount\")\n .values(\"A1\", 190000)\n .values(\"A2\", 192000)\n .values(\"A3\", 195000)\n .values(\"C1\", 200000)\n .values(\"C2\", 201000)\n .values(\"C3\", 202000)\n .values(\"C4\", 203000)\n .values(\"C5\", 204000)\n .values(\"M1\", 300000)\n .values(\"M2\", 320000)\n .values(\"M3\", 350000)\n .values(\"CE\", 500000).build();\n return role;\n }\n}" ]
import static com.ninja_squad.dbsetup.Operations.deleteAllFrom; import static com.ninja_squad.dbsetup.Operations.insertInto; import static com.ninja_squad.dbsetup.Operations.sequenceOf; import static com.ninja_squad.dbsetup.destination.DriverManagerDestination.with; import static org.assertj.core.api.Assertions.assertThat; import static salarycalculation.assertions.EmployeeRecordAssert.assertThat; import static salarycalculation.matchers.RecordNotFoundExceptionMatcher.isClass; import static salarycalculation.matchers.RecordNotFoundExceptionMatcher.isKey; import java.sql.Connection; import java.sql.DriverManager; import java.util.List; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.internal.util.reflection.Whitebox; import com.ninja_squad.dbsetup.DbSetup; import com.ninja_squad.dbsetup.DbSetupTracker; import com.ninja_squad.dbsetup.operation.Operation; import salarycalculation.database.model.EmployeeRecord; import salarycalculation.dbsetup.CapabilitySetupSupport; import salarycalculation.dbsetup.OrganizationSetupSupport; import salarycalculation.dbsetup.RoleSetupSupport; import salarycalculation.exception.RecordNotFoundException;
package salarycalculation.database; /** * {@link EmployeeDao}に対するテストクラス。 * * @author naotake */ @RunWith(Enclosed.class) public class EmployeeDaoTest { public static class 社員情報を1件取得する場合 extends EmployeeDaoTestBase { @BeforeClass public static void setUpOnce() throws Exception { dbSetupTracker = new DbSetupTracker(); } @Rule public ExpectedException expect = ExpectedException.none(); @Test public void 社員情報を取得できること() { dbSetupTracker.skipNextLaunch(); EmployeeRecord actual = testee.get("1");
assertThat(actual).isNotNull().hasNo(1).hasName("愛媛 蜜柑");
0
TrumanDu/AutoProgramming
src/main/java/com/aibibang/web/system/service/impl/SysRoleServiceImpl.java
[ "public class Page<T> extends RowBounds {\r\n\r\n\tprivate int pageNo = 1;\t\t\t\t// 当前页数\r\n\tprivate int pageSize = 10;\t\t\t// 每页显示行数\r\n\tprivate int totalCount;\t\t\t\t// 总行数\r\n\tprivate int totalPages;\t\t\t\t// 总页数\r\n\t\r\n\tprivate List<T> result = new ArrayList<T>();// 查询结果\r\n\t\r\n\tprivate int offset;\t\t\t\t\t// 偏移量 : 第一条数据在表中的位置\r\n\tprivate int limit;\t\t\t\t\t// 限定数 : 每页的数量\r\n\t\r\n\tprivate int length = 8;\t\t\t\t// 页显示数\r\n\tprivate String funcName\t= \"page\";\t// 点击页码调用的js函数名称,默认为page\r\n\tprivate int prev;\t\t\t\t\t// 上一页\r\n\tprivate int next;\t\t\t\t\t// 下一页\r\n\t\r\n\tpublic Page() {\r\n\t\tsuper();\r\n\t\tthis.offset = (this.pageNo - 1) * this.pageSize;\r\n\t\tthis.limit = this.pageSize;\r\n\t}\r\n\tpublic int getPageNo() {\r\n\t\treturn pageNo;\r\n\t}\r\n\tpublic void setPageNo(int pageNo) {\r\n\t\t\r\n\t\tthis.pageNo = pageNo <= 0 ? 1 : pageNo;\r\n\t\tthis.offset = (this.pageNo - 1) * this.pageSize;\r\n\t\tthis.limit = this.pageSize;\r\n\t}\r\n\tpublic int getPageSize() {\r\n\t\treturn pageSize;\r\n\t}\r\n\tpublic void setPageSize(int pageSize) {\r\n\t\tthis.pageSize = pageSize;\r\n\t}\r\n\tpublic int getTotalCount() {\r\n\t\treturn totalCount;\r\n\t}\r\n\tpublic void setTotalCount(int totalCount) {\r\n\t\t\r\n\t\tthis.totalCount = totalCount;\r\n\t\t\r\n\t\tif (totalCount < 0) {\r\n\r\n\t\t\tthis.totalPages = -1;\r\n\t\t}\r\n\r\n\t\tint pages = totalCount / this.pageSize;\r\n\t\t\r\n\t\tthis.totalPages = totalCount % this.pageSize > 0 ? pages + 1 : pages;\r\n\t\t\r\n\t\tthis.prev = this.pageNo == 1 ? 1 : (this.pageNo - 1);\r\n\t\tthis.next = (this.pageNo + 1) > this.totalPages ? this.totalPages : (this.pageNo + 1);\r\n\t}\r\n\tpublic int getTotalPages() {\r\n\t\treturn totalPages;\r\n\t}\r\n\tpublic void setTotalPages(int totalPages) {\r\n\t\tthis.totalPages = totalPages;\r\n\t}\r\n\tpublic List<T> getResult() {\r\n\t\treturn result;\r\n\t}\r\n\tpublic void setResult(List<T> result) {\r\n\t\tthis.result = result;\r\n\t}\r\n\tpublic int getOffset() {\r\n\t\treturn offset;\r\n\t}\r\n\tpublic void setOffset(int offset) {\r\n\t\tthis.offset = offset;\r\n\t}\r\n\tpublic int getLimit() {\r\n\t\treturn limit;\r\n\t}\r\n\tpublic void setLimit(int limit) {\r\n\t\tthis.limit = limit;\r\n\t}\r\n\tpublic int getLength() {\r\n\t\treturn length;\r\n\t}\r\n\tpublic void setLength(int length) {\r\n\t\tthis.length = length;\r\n\t}\r\n\tpublic String getFuncName() {\r\n\t\treturn funcName;\r\n\t}\r\n\tpublic void setFuncName(String funcName) {\r\n\t\tthis.funcName = funcName;\r\n\t}\r\n\tpublic int getPrev() {\r\n\t\treturn prev;\r\n\t}\r\n\tpublic void setPrev(int prev) {\r\n\t\tthis.prev = prev;\r\n\t}\r\n\tpublic int getNext() {\r\n\t\treturn next;\r\n\t}\r\n\tpublic void setNext(int next) {\r\n\t\tthis.next = next;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic String toString(){\r\n\t\tStringBuilder sb = new StringBuilder();\r\n\t\t\r\n\t\tsb.append(\"<div class=\\\"div-left\\\">共&nbsp;\"+this.totalCount+\"&nbsp;条记录,当前显示&nbsp;\");\r\n\t\tsb.append(\"<input type=\\\"text\\\" size=\\\"1\\\" value=\\\"\"+this.pageNo+\"\\\"\");\r\n\t\tsb.append(\" onkeypress=\\\"var e=window.event||this;var c=e.keyCode||e.which;if(c==13)\");\r\n\t\tsb.append(this.funcName+\"(this.value);\\\"/>&nbsp;/&nbsp;\"+this.totalPages+\"&nbsp;页</div>\\n\");\r\n\t\t\r\n\t\tsb.append(\"<div class=\\\"div-right\\\">\\n\");\r\n\t\tsb.append(\"<ul class=\\\"pagination\\\" style=\\\"visibility: visible;\\\">\\n\");\r\n\t\t\r\n\t\t// 首页\r\n\t\tif(this.pageNo <= 1){\r\n\t\t\tsb.append(\"<li class=\\\"prev disabled\\\"><a href=\\\"javascript:\\\">\");\r\n\t\t\tsb.append(\"<i class=\\\"fa fa-angle-double-left\\\"></i></a></li>\\n\");\r\n\t\t\t\r\n\t\t\tsb.append(\"<li class=\\\"prev disabled\\\"><a href=\\\"javascript:\\\">\");\r\n\t\t\tsb.append(\"<i class=\\\"fa fa-angle-left\\\"></i></a></li>\\n\");\r\n\t\t}\r\n\t\telse{\r\n\t\t\tsb.append(\"<li class=\\\"prev\\\"><a href=\\\"javascript:\\\" \");\r\n\t\t\tsb.append(\"onclick=\\\"\"+this.funcName+\"(1);\\\">\");\r\n\t\t\tsb.append(\"<i class=\\\"fa fa-angle-double-left\\\"></i></a></li>\\n\");\r\n\t\t\t\r\n\t\t\tsb.append(\"<li class=\\\"prev\\\"><a href=\\\"javascript:\\\" \");\r\n\t\t\tsb.append(\"onclick=\\\"\"+this.funcName+\"(\"+this.prev+\");\\\">\");\r\n\t\t\tsb.append(\"<i class=\\\"fa fa-angle-left\\\"></i></a></li>\\n\");\r\n\t\t}\r\n\t\t\r\n\t\tint begin = this.pageNo - (this.length/2);\r\n\t\t\r\n\t\tif(begin < 1){\r\n\t\t\tbegin = 1;\r\n\t\t}\r\n\t\t\r\n\t\tint end = begin + this.length - 1;\r\n\t\t\r\n\t\tif(end >= this.totalPages){\r\n\t\t\tend = this.totalPages;\r\n\t\t}\r\n\t\t\r\n\t\tif(begin > 1){\r\n\t\t\tsb.append(\"<li class=\\\"disabled\\\"><a href=\\\"javascript:\\\">...</a></li>\\n\");\r\n\t\t}\r\n\t\t\r\n\t\tfor (int i = begin; i <= end; i++) {\r\n\t\t\tif (i == this.pageNo) {\r\n\t\t\t\tsb.append(\"<li class=\\\"active\\\"><a href=\\\"javascript:\\\">\"+this.pageNo+\"</a></li>\\n\");\r\n\t\t\t} else {\r\n\t\t\t\tsb.append(\"<li><a href=\\\"javascript:\\\" onclick=\\\"\"+funcName+\"(\"+i+\");\\\">\"+i+\"</a></li>\\n\");\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif(end < this.totalPages){\r\n\t\t\tsb.append(\"<li class=\\\"disabled\\\"><a href=\\\"javascript:\\\">...</a></li>\\n\");\r\n\t\t}\r\n\t\t\r\n\t\tif(this.pageNo >= this.totalPages){\r\n\t\t\tsb.append(\"<li class=\\\"next disabled\\\"><a href=\\\"javascript:\\\">\");\r\n\t\t\tsb.append(\"<i class=\\\"fa fa-angle-right\\\"></i></a></li>\\n\");\r\n\t\t\t\r\n\t\t\tsb.append(\"<li class=\\\"next disabled\\\"><a href=\\\"javascript:\\\">\");\r\n\t\t\tsb.append(\"<i class=\\\"fa fa-angle-double-right\\\"></i></a></li>\\n\");\r\n\t\t}\r\n\t\telse{\r\n\t\t\tsb.append(\"<li class=\\\"next\\\"><a href=\\\"javascript:\\\" \");\r\n\t\t\tsb.append(\"onclick=\\\"\"+this.funcName+\"(\"+this.next+\");\\\">\");\r\n\t\t\tsb.append(\"<i class=\\\"fa fa-angle-right\\\"></i></a></li>\\n\");\r\n\t\t\t\r\n\t\t\tsb.append(\"<li class=\\\"next\\\"><a href=\\\"javascript:\\\" \");\r\n\t\t\tsb.append(\"onclick=\\\"\"+this.funcName+\"(\"+this.totalPages+\");\\\">\");\r\n\t\t\tsb.append(\"<i class=\\\"fa fa-angle-double-right\\\"></i></a></li>\\n\");\r\n\t\t}\r\n\t\t\r\n\t\tsb.append(\"</ul>\\n</div>\");\r\n\t\t\r\n\t\treturn sb.toString();\r\n\t}\r\n\t\r\n}\r", "public interface SysRoleDao extends BaseDao<SysRole, Long> {\r\n\r\n\r\n}", "public interface SysRoleMenuDao extends BaseDao<SysRoleMenu, Long> {\r\n\r\n\t/**\r\n\t * 获取角色所有菜单权限\r\n\t * @param roleId\r\n\t * @return\r\n\t */\r\n\tpublic List<Long> findByRoleId(Long roleId);\r\n\t\r\n\t/**\r\n\t * 删除角色下所有的菜单\r\n\t * @param roleId\r\n\t */\r\n\tpublic void deleteByRoleId(Long roleId);\r\n\t\r\n\t/**\r\n\t * 获取用户所有的有权限的菜单\r\n\t * @param userId\r\n\t * @return\r\n\t */\r\n\tpublic List<Long> findMenuIdByUserId(Long userId);\r\n}", "public class SysRole extends BaseEntity implements Serializable {\r\n\t\r\n\tprivate static final long serialVersionUID = 1L;\r\n\t\r\n\t/**角色编码*/\r\n\tprivate String roleCode;\r\n\t/**角色名称*/\r\n\tprivate String roleName;\r\n\t/**备注*/\r\n\tprivate String description;\r\n\t\r\n\t/** 用户是否有此角色权限 */\r\n\tprivate boolean userHas;\r\n\t/** 菜单ID,逗号分隔 */\r\n\tprivate String menuIds;\r\n\t\r\n\t/**\r\n\t *方法: 取得String\r\n\t *@return: String 角色编码\r\n\t */\r\n\tpublic String getRoleCode(){\r\n\t\treturn this.roleCode;\r\n\t}\r\n\r\n\t/**\r\n\t *方法: 设置String\r\n\t *@param: String 角色编码\r\n\t */\r\n\tpublic void setRoleCode(String roleCode){\r\n\t\tthis.roleCode = roleCode;\r\n\t}\r\n\t\r\n\t/**\r\n\t *方法: 取得String\r\n\t *@return: String 角色名称\r\n\t */\r\n\tpublic String getRoleName(){\r\n\t\treturn this.roleName;\r\n\t}\r\n\r\n\t/**\r\n\t *方法: 设置String\r\n\t *@param: String 角色名称\r\n\t */\r\n\tpublic void setRoleName(String roleName){\r\n\t\tthis.roleName = roleName;\r\n\t}\r\n\t\r\n\t/**\r\n\t *方法: 取得String\r\n\t *@return: String 备注\r\n\t */\r\n\tpublic String getDescription(){\r\n\t\treturn this.description;\r\n\t}\r\n\r\n\t/**\r\n\t *方法: 设置String\r\n\t *@param: String 备注\r\n\t */\r\n\tpublic void setDescription(String description){\r\n\t\tthis.description = description;\r\n\t}\r\n\r\n\t\r\n\tpublic boolean isUserHas() {\r\n\t\treturn userHas;\r\n\t}\r\n\r\n\tpublic void setUserHas(boolean userHas) {\r\n\t\tthis.userHas = userHas;\r\n\t}\r\n\r\n\tpublic String getMenuIds() {\r\n\t\treturn menuIds;\r\n\t}\r\n\r\n\tpublic void setMenuIds(String menuIds) {\r\n\t\tthis.menuIds = menuIds;\r\n\t}\r\n\t\r\n\t\r\n}\r", "public class SysRoleMenu extends BaseEntity implements Serializable {\r\n\t\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\t/**roleId*/\r\n\tprivate Long roleId;\r\n\t/**menuId*/\r\n\tprivate Long menuId;\r\n\t\r\n\r\n\t/**\r\n\t *方法: 取得Long\r\n\t *@return: Long roleId\r\n\t */\r\n\tpublic Long getRoleId(){\r\n\t\treturn this.roleId;\r\n\t}\r\n\r\n\t/**\r\n\t *方法: 设置Long\r\n\t *@param: Long roleId\r\n\t */\r\n\tpublic void setRoleId(Long roleId){\r\n\t\tthis.roleId = roleId;\r\n\t}\r\n\t\r\n\t/**\r\n\t *方法: 取得Long\r\n\t *@return: Long menuId\r\n\t */\r\n\tpublic Long getMenuId(){\r\n\t\treturn this.menuId;\r\n\t}\r\n\r\n\t/**\r\n\t *方法: 设置Long\r\n\t *@param: Long menuId\r\n\t */\r\n\tpublic void setMenuId(Long menuId){\r\n\t\tthis.menuId = menuId;\r\n\t}\r\n\t\r\n}\r", "public interface SysRoleService{\n\t\n \t/**\n\t * \n\t * <pre>\n\t * \t2016-08-01 22:42 King\n\t * \t分页查询\n\t * </pre>\n\t * \n\t * @param sysRole\n\t * @param page\n\t * @return\n\t */\n\tpublic Page<SysRole> findByPage(SysRole sysRole,Page<SysRole> page);\n\t\n\t/**\n\t * \n\t * <pre>\n\t * \t2016-08-01 22:42 King\n\t * \t查询\n\t * </pre>\n\t * \n\t * @param sysRole\n\t * @return\n\t */\n\tpublic List<SysRole> findBySearch(SysRole sysRole);\n\t\n\t/**\n\t * \n\t * <pre>\n\t * \t2016-08-01 22:42 King\n\t * \t通过ID查询\n\t * </pre>\n\t * \n\t * @param SysRole\n\t * @return\n\t */\n\tpublic SysRole getById(Long id);\n\t\n\t/**\n\t * \n\t * <pre>\n\t * \t2016-08-01 22:42 King\n\t * \t新增\n\t * </pre>\n\t * \n\t * @param sysRole\n\t */\n\tpublic void add(SysRole sysRole);\n\t\n\t/**\n\t * \n\t * <pre>\n\t * \t2016-08-01 22:42 King\n\t * \t修改\n\t * </pre>\n\t * \n\t * @param sysRole\n\t */\n\tpublic void update(SysRole sysRole);\n\t\n\t/**\n\t * \n\t * <pre>\n\t * \t2016-08-01 22:42 King\n\t * \t删除\n\t * </pre>\n\t * \n\t * @param id\n\t */\n\tpublic void delete(Long id);\n\t\n\t/**\n\t * 根据角色id获取所有菜单权限\n\t * @param roleId\n\t * @return\n\t */\n\tpublic List<Long> findByRoleId(Long roleId);\n}" ]
import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import com.aibibang.common.persistence.Page; import com.aibibang.web.system.dao.SysRoleDao; import com.aibibang.web.system.dao.SysRoleMenuDao; import com.aibibang.web.system.entity.SysRole; import com.aibibang.web.system.entity.SysRoleMenu; import com.aibibang.web.system.service.SysRoleService;
package com.aibibang.web.system.service.impl; /** * * 角色管理service实现类 * * <pre> * 历史记录: * 2016-08-01 22:42 King * 新建文件 * </pre> * * @author * <pre> * SD * King * PG * King * UT * * MA * </pre> * @version $Rev$ * * <p/> $Id$ * */ @Service("sysRoleService") public class SysRoleServiceImpl implements SysRoleService { @Resource private SysRoleDao sysRoleDao; @Resource private SysRoleMenuDao sysRoleMenuDao; @Override
public Page<SysRole> findByPage(SysRole sysRole, Page<SysRole> page) {
3
nullpointerexceptionapps/TeamCityDownloader
java/com/raidzero/teamcitydownloader/activities/BuildInfoActivity.java
[ "public class TeamCityBuild implements Parcelable {\n private static final String tag = \"TeamCityBuild\";\n\n private String number;\n private String status;\n private String url;\n private String webUrl;\n private String branch;\n\n public TeamCityBuild(String number, String status, String url, String branch, String weburl) {\n this.number = number;\n this.status = status;\n this.url = url;\n this.branch = branch;\n this.webUrl = weburl;\n\n //Debug.Log(tag, \"instance created. Number: \" + number + \" Status: \" + status + \" URL: \" + url);\n }\n\n public String getNumber() {\n return this.number;\n }\n public String getStatus() {\n return this.status;\n }\n public String getUrl() {\n return this.url;\n }\n public String getWebUrl() {\n return this.webUrl;\n }\n\n public String getBranch() {\n if (branch.isEmpty()) {\n return \"\";\n } else {\n return branch;\n }\n }\n\n public void setUrl(String url) {\n this.url = url;\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(number);\n dest.writeString(status);\n dest.writeString(url);\n dest.writeString(branch);\n dest.writeString(webUrl);\n }\n\n // this is needed to make the parcel\n public TeamCityBuild(Parcel source) {\n number = source.readString();\n status = source.readString();\n url = source.readString();\n branch = source.readString();\n webUrl = source.readString();\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator<TeamCityBuild>() {\n public TeamCityBuild createFromParcel(Parcel source) {\n return new TeamCityBuild(source);\n }\n public TeamCityBuild[] newArray(int size) {\n return new TeamCityBuild[size];\n }\n };\n}", "public class WebResponse {\n private String responseDocument;\n private StatusLine status;\n private String requestUrl;\n\n public WebResponse(StatusLine statusLine, String requestUrl, String response) {\n this.status = statusLine;\n this.requestUrl = requestUrl;\n this.responseDocument = response;\n }\n\n public int getStatusCode() {\n return this.status.getStatusCode();\n }\n\n public String getStatusReason(Context context) {\n // find the matching item in the web_response array\n String[] reasons = context.getResources().getStringArray(R.array.web_responses);\n\n for (String reason : reasons) {\n if (reason.startsWith(String.valueOf(status.getStatusCode()))) {\n return reason;\n }\n }\n\n return status.getReasonPhrase();\n }\n\n public void setReasonPhrase(final String reason) {\n final ProtocolVersion protoVersion = status.getProtocolVersion();\n final int statusCode = status.getStatusCode();\n\n status = new StatusLine() {\n @Override\n public ProtocolVersion getProtocolVersion() {\n return protoVersion;\n }\n\n @Override\n public int getStatusCode() {\n return statusCode;\n }\n\n @Override\n public String getReasonPhrase() {\n return reason;\n }\n };\n }\n\n public String getResponseDocument() {\n return this.responseDocument;\n }\n\n public String getRequestUrl() {\n return this.requestUrl;\n }\n}", "public class DateUtility {\n\n public static String friendlyDate(String timestamp) throws ParseException {\n String oldTimeFormat = \"yyyyMMdd'T'HHmmssZ\";\n String newTimeFormat = \"yyyy-MM-dd hh:mm a z\";\n\n SimpleDateFormat sdf = new SimpleDateFormat(oldTimeFormat);\n\n // get Date objects from server data\n Date date = sdf.parse(timestamp);\n\n sdf.applyPattern(newTimeFormat);\n return sdf.format(date);\n }\n}", "public class Debug {\n //private static final boolean debug = false;\n //private static final boolean debug = true;\n\n private static final boolean debug = BuildConfig.DEBUG;\n\n public static void Log(String tag, String msg) {\n if (debug) {\n Log.d(tag, msg);\n }\n }\n\n public static void Log(String tag, String msg, Exception e) {\n if (debug) {\n Log.d(tag, msg);\n e.printStackTrace();\n }\n }\n}", "public class QueryUtility implements TeamCityTask.OnWebRequestCompleteListener {\n private static final String tag = \"QueryUtility\";\n private Context context;\n private AppHelper helper;\n private String query;\n private TeamCityServer server;\n private QueryCallbacks callbacks;\n private boolean isQuerying;\n private boolean onSettingsScreen;\n\n // interface\n public interface QueryCallbacks {\n void onQueryComplete(WebResponse response);\n void startSpinning();\n void stopSpinning();\n void setActivityTitle(String title);\n }\n\n // constructor\n public QueryUtility(Context context, String query) {\n this.context = context;\n this.query = query;\n\n helper = (AppHelper) context.getApplicationContext();\n server = helper.getTcServer();\n\n callbacks = (QueryCallbacks) context;\n }\n\n public boolean isQuerying() {\n return isQuerying;\n }\n\n public void setQuery(String url) {\n this.query = url;\n }\n\n public void setOnSettingsScreen(boolean b) {\n onSettingsScreen = b;\n }\n\n public void queryServer(boolean forceRefresh) {\n Debug.Log(tag, \"queryServer(\" + query + \")...\");\n\n // refresh button\n if (forceRefresh) {\n Debug.Log(tag, \"forcing query for \" + query);\n // clear this cached request\n helper.removeReponseFromCache(query);\n\n runTask(query);\n return;\n }\n\n // see if we have cached this request\n WebResponse cachedResponse = helper.getResponseFromCache(query);\n\n if (cachedResponse != null) {\n if (cachedResponse.getResponseDocument() != null) {\n Debug.Log(tag, \"got cached response for queryUrl \" + query);\n\n // invoke listener with cached response\n onWebRequestComplete(cachedResponse);\n return;\n }\n }\n\n // if we got here there is no cached response\n runTask(query);\n }\n\n private void runTask(String queryUrl) {\n isQuerying = true;\n Debug.Log(tag, \"runTask on query \" + queryUrl);\n Debug.Log(tag, \"server is null? \" + (server == null));\n callbacks.startSpinning();\n callbacks.setActivityTitle(context.getString(R.string.querying));\n\n if (server != null) {\n // run task\n server.setContext(this);\n server.setOnSettingsScreen(onSettingsScreen);\n TeamCityTask task = server.getRequestTask(queryUrl);\n task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);\n } else {\n TeamCityServer.serverMisconfigured(context, onSettingsScreen);\n if (onSettingsScreen) {\n SettingsServerActivity.querying = false;\n }\n\n callbacks.stopSpinning();\n }\n }\n\n @Override\n public void onWebRequestComplete(WebResponse response) {\n Debug.Log(tag, \"onWebRequestComplete\");\n callbacks.stopSpinning();\n isQuerying = false;\n callbacks.onQueryComplete(response);\n }\n}", "public class TeamCityXmlParser {\n private static final String tag = \"TeamCityXmlParser\";\n\n private Document doc;\n\n public TeamCityXmlParser(String xml) {\n // parse this xml string into a Document\n this.doc = parseXmlString(xml);\n }\n\n private Document parseXmlString(String xml) {\n try {\n DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();\n InputSource is = new InputSource();\n is.setCharacterStream(new StringReader(xml));\n return db.parse(is);\n } catch (Exception e) {\n Debug.Log(tag, \"Document error: \", e);\n }\n\n return null;\n }\n\n public NodeList getNodes(String elementName) {\n NodeList nodes = doc.getElementsByTagName(elementName);\n Debug.Log(tag, \"getNodes(\" + elementName + \") returning \" + nodes.getLength() + \" nodes.\");\n return nodes;\n }\n\n public NodeList getNodes(Element element, String elementName) {\n NodeList nodes = element.getElementsByTagName(elementName);\n Debug.Log(tag, \"getNodes(\" + elementName + \") returning \" + nodes.getLength() + \" nodes.\");\n return nodes;\n }\n\n public String getAttribute(Element element, String attribute) {\n return element.getAttribute(attribute);\n }\n\n\n}", "public class ThemeUtility {\n private static final String tag = \"ThemeUtility\";\n\n public static void setAppTheme(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String themeName = prefs.getString(\"theme\", \"\");\n\n // if it doesnt exist in prefs, create it, as dark\n if (prefs.getString(\"theme\", \"\").isEmpty()) {\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(\"theme\", \"dark\");\n editor.apply();\n themeName = \"dark\";\n }\n\n if (themeName.equalsIgnoreCase(\"light\")) {\n context.setTheme(R.style.Light);\n } else {\n context.setTheme(R.style.Dark);\n }\n }\n\n public static int getDialogActivityTheme(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String themeName = prefs.getString(\"theme\", \"\");\n\n // if it doesnt exist in prefs, create it, as dark\n if (prefs.getString(\"theme\", \"\").isEmpty()) {\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(\"theme\", \"dark\");\n editor.apply();\n themeName = \"dark\";\n }\n\n if (themeName.equalsIgnoreCase(\"light\")) {\n return R.style.LightDialogActivity;\n } else {\n return R.style.DarkDialogActivity;\n }\n }\n public static int getThemeId(Context context) {\n TypedValue outValue = new TypedValue();\n context.getTheme().resolveAttribute(R.attr.themeName, outValue, true);\n if (\"Dark\".equals(outValue.string)) {\n return R.style.Dark;\n } else {\n return R.style.Light;\n }\n }\n\n public static int getHoloDialogTheme(Context context) {\n if (getThemeId(context) == R.style.Dark) {\n Debug.Log(tag, \"returning dark theme\");\n return AlertDialog.THEME_HOLO_DARK;\n } else {\n Debug.Log(tag, \"returning light theme\");\n return AlertDialog.THEME_HOLO_LIGHT;\n }\n }\n\n public static Drawable getThemedDrawable(Context context, int resId) {\n TypedArray a = context.getTheme().obtainStyledAttributes(getThemeId(context), new int[]{resId});\n\n if (a != null) {\n int attributeResourceId = a.getResourceId(0, 0);\n return context.getResources().getDrawable(attributeResourceId);\n }\n\n return null;\n }\n\n public static int getThemedColor(Context context, int resId) {\n TypedArray a = context.getTheme().obtainStyledAttributes(getThemeId(context), new int[]{resId});\n\n if (a != null) {\n int attributeResourceId = a.getResourceId(0, 0);\n return context.getResources().getColor(attributeResourceId);\n }\n\n return -1;\n }\n}" ]
import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.raidzero.teamcitydownloader.R; import com.raidzero.teamcitydownloader.data.TeamCityBuild; import com.raidzero.teamcitydownloader.data.WebResponse; import com.raidzero.teamcitydownloader.global.DateUtility; import com.raidzero.teamcitydownloader.global.Debug; import com.raidzero.teamcitydownloader.global.QueryUtility; import com.raidzero.teamcitydownloader.global.TeamCityXmlParser; import com.raidzero.teamcitydownloader.global.ThemeUtility; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.text.ParseException; import java.util.HashMap; import java.util.Map;
package com.raidzero.teamcitydownloader.activities; /** * Created by raidzero on 8/14/14. */ public class BuildInfoActivity extends TeamCityActivity { private static final String tag = "BuildInfoActivity"; private TeamCityBuild build; private QueryUtility queryUtility; private TextView txt_triggered; private TextView txt_agent; private TextView txt_project; private TextView txt_queued; private TextView txt_started; private TextView txt_finished; private TextView txt_branch; private TextView txt_status; private TextView custom_properties_header; private LinearLayout custom_properties_container; // build info container private class TeamCityBuildInfo { public String branchName; public String webUrl; // not displayed public Map<String, String> buildProperties = new HashMap<String, String>(); public Map<String, String> customProperties = new HashMap<String, String>(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); build = intent.getParcelableExtra("selectedBuild"); queryUtility = new QueryUtility(this, build.getUrl()); setContentView(R.layout.build_info); } @Override public boolean onCreateOptionsMenu(Menu menu) {
Debug.Log(tag, "onCreateOptionsMenu()");
3
trond-arve-wasskog/nytt-folkeregister-atom
datomic/src/main/java/ske/folkeregister/dw/Server.java
[ "@SuppressWarnings(\"unchecked\")\npublic class FeedGenerator implements Runnable {\n\n private static final Logger log = LoggerFactory.getLogger(FeedGenerator.class);\n\n private static final Abdera abdera = Abdera.getInstance();\n private static final String attr_query =\n \"[:find ?attrname :in $ ?attr :where [?attr :db/ident ?attrname]]\";\n public static final String ssn_query =\n \"[:find ?ssn :in $ ?entity :where [?entity :person/ssn ?ssn]]\";\n\n private final BlockingQueue<Map> txReportQueue;\n private final WebResource feedResource;\n\n public FeedGenerator(Connection conn, WebResource feedResource) {\n this.feedResource = feedResource;\n txReportQueue = conn.txReportQueue();\n }\n\n @Override\n public void run() {\n while (true) {\n try {\n final Map tx = txReportQueue.take();\n final List<Datum> txData = (List<Datum>) tx.get(TX_DATA);\n\n log.info(\"Create feed entries tx: {}\", txData.get(0).v());\n\n txData\n .stream()\n .skip(1)\n .collect(Collectors.groupingBy(Datum::e))\n .entrySet()\n .stream()\n .map(e -> {\n Entry entry = abdera.newEntry();\n\n String ssn = queryForSSN(tx, e.getKey());\n entry.addLink(entry.addLink(\"/person/\" + ssn, \"person\"));\n entry.setTitle(\"Person \" + ssn + \" oppdatert\");\n\n e.getValue().forEach(datum -> {\n if (datum.added()) {\n entry.addCategory(\n \"added\",\n queryForAttrName(tx.get(DB_AFTER), datum.a()),\n datum.v().toString()\n );\n } else {\n entry.addCategory(\n \"removed\",\n queryForAttrName(tx.get(DB_BEFORE), datum.a()),\n datum.v().toString()\n );\n }\n });\n\n return entry;\n })\n .forEach(entry -> {\n try {\n feedResource.type(MediaType.APPLICATION_ATOM_XML_TYPE).post(entry);\n } catch (Exception e) {\n log.error(\"Problem posting feed entry: {} ({})\", entry, e.getMessage());\n }\n });\n } catch (Exception e) {\n log.error(\"Problem reading tx-report\", e);\n }\n }\n }\n\n private String queryForSSN(Map tx, Object entity) {\n return Peer.q(ssn_query, tx.get(DB_AFTER), entity).iterator().next().get(0).toString();\n }\n\n private String queryForAttrName(Object db, Object attr) {\n return Peer.q(attr_query, db, attr).iterator().next().get(0).toString();\n }\n}", "public class DatomicPersonApi implements PersonApi {\n\n private final Connection conn;\n\n public DatomicPersonApi(Connection conn) {\n this.conn = conn;\n }\n\n @Override\n public List<Object> findAllPersons() {\n final Database db = conn.db();\n return Peer\n .q(\"[:find ?p :where [?p :person/ssn]]\", db)\n .stream()\n .map(list -> resultListToEntityMap(db, list))\n .collect(Collectors.toList());\n }\n\n @Override\n public void changeNameAndStatus(String ssn, String newName, String newStatus) throws Exception {\n updatePerson(map(\n \":person/ssn\", ssn,\n \":person/sivilstatus\", read(newStatus),\n \":person/name\", newName\n ));\n }\n\n @Override\n public void moveToNewAddress(String ssn, String street, String number, String postnumber) throws Exception {\n Object newTmpAddressId = tempid(\"db.part/user\");\n conn.transact(list(\n map(\n \":db/id\", newTmpAddressId,\n \":address/street\", street,\n \":address/streetnumber\", number,\n \":address/postnumber\", postnumber\n ),\n map(\n \":db/id\", list(\":person/ssn\", ssn),\n \":person/address\", newTmpAddressId\n )\n )).get();\n }\n\n @Override\n public List<Map> changesForPerson(String ssn) throws Exception {\n return findPersonBySSN(ssn)\n .map(id -> Changes.changeOverTimeForEntity(conn.db(), id))\n .orElse(Collections.<Map>emptyList());\n }\n\n @Override\n public Map getPerson(String ssn) throws Exception {\n return findPersonBySSN(ssn)\n .map(id -> conn.db().entity(id))\n .map(IO::entityToMap)\n .orElse(Collections.emptyMap());\n }\n\n @Override\n public void updatePerson(Map person) throws Exception {\n final HashMap<Object, Object> txMap = new HashMap<>();\n\n txMap.put(\":db/id\", tempid(\"db.part/user\"));\n txMap.putAll(person);\n\n conn.transact(list(txMap)).get();\n }\n\n private Optional<Object> findPersonBySSN(String ssn) {\n return Optional.ofNullable(conn.db().entid(lookupRef(ssn)));\n }\n\n private List lookupRef(String ssn) {\n return list(\":person/ssn\", ssn);\n }\n\n private Map resultListToEntityMap(Database db, List results) {\n final Entity entity = db.entity(results.get(0));\n return IO.entityToMap(entity);\n }\n}", "public interface PersonApi {\n List<Object> findAllPersons();\n\n void changeNameAndStatus(String ssn, String newName, String newStatus) throws Exception;\n\n void moveToNewAddress(String ssn, String street, String number, String postnumber) throws Exception;\n\n List<Map> changesForPerson(String ssn) throws Exception;\n\n Map getPerson(String ssn) throws Exception;\n\n void updatePerson(Map person) throws Exception;\n}", "@SuppressWarnings(\"unchecked\")\npublic class IO {\n\n public static void transactAllFromFile(Connection conn, String filename) throws InterruptedException, ExecutionException {\n for (List tx : readData(filename)) {\n conn.transact(tx).get();\n }\n }\n\n public static Connection newMemConnection() {\n String uri = \"datomic:mem://\" + UUID.randomUUID();\n Peer.createDatabase(uri);\n return Peer.connect(uri);\n }\n\n public static Map<String, Object> entityToMap(Entity entity) {\n return entity\n .keySet()\n .stream()\n .collect(Collectors.toMap(\n key -> key.substring(key.lastIndexOf(\"/\") + 1),\n key -> attrToValue(entity, key)\n ));\n }\n\n public static Object attrToValue(Entity entity, Object key) {\n Object value = entity.get(key);\n if (value instanceof Entity) {\n value = entityToMap((Entity) value);\n } else if (value instanceof Keyword) {\n value = ((Keyword) value).getName();\n }\n return value;\n }\n\n private static List<List> readData(String filename) {\n return Util.readAll(new InputStreamReader(\n Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));\n }\n}", "@Path(\"persons\")\n@Produces(MediaType.APPLICATION_JSON)\npublic class PersonResource {\n\n private final PersonApi personApi;\n\n public PersonResource(PersonApi personApi) {\n this.personApi = personApi;\n }\n\n @GET\n public Object findAll() {\n return personApi.findAllPersons();\n }\n\n @GET\n @Path(\"{ssn}/changes\")\n public Object changes(@PathParam(\"ssn\") String ssn) throws Exception {\n return personApi.changesForPerson(ssn);\n }\n\n @GET\n @Path(\"{ssn}\")\n public Object get(@PathParam(\"ssn\") String ssn) throws Exception {\n return personApi.getPerson(ssn);\n }\n\n @POST\n public void update(Map person) throws Exception {\n personApi.updatePerson(person);\n }\n}", "public class ServerConfig extends Configuration {\n\n @NotNull\n @JsonProperty\n private String feedServerUrl;\n\n @Valid\n @NotNull\n @JsonProperty\n private JerseyClientConfiguration jerseyClient = new JerseyClientConfiguration();\n\n public String getFeedServerUrl() {\n return feedServerUrl;\n }\n\n public JerseyClientConfiguration getJerseyClientConfig() {\n return jerseyClient;\n }\n}", "public class DatomicConnectionManager implements Managed {\n\n private final Connection conn;\n\n public DatomicConnectionManager(Connection conn) {\n this.conn = conn;\n }\n\n @Override\n public void start() throws Exception {\n }\n\n @Override\n public void stop() throws Exception {\n conn.release();\n Peer.shutdown(true);\n }\n}", "public class ThreadManager implements Managed {\n\n private final Runnable[] runnables;\n\n private ExecutorService executorService;\n\n public ThreadManager(Runnable... runnables) {\n this.runnables = runnables;\n }\n\n @Override\n public void start() throws Exception {\n executorService = Executors.newFixedThreadPool(runnables.length);\n Stream.of(runnables).forEach(executorService::execute);\n }\n\n @Override\n public void stop() throws Exception {\n executorService.shutdown();\n }\n}" ]
import com.bazaarvoice.dropwizard.webjars.WebJarBundle; import com.sun.jersey.api.client.Client; import datomic.Connection; import io.dropwizard.Application; import io.dropwizard.assets.AssetsBundle; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import ske.folkeregister.datomic.feed.FeedGenerator; import ske.folkeregister.datomic.person.DatomicPersonApi; import ske.folkeregister.datomic.person.PersonApi; import ske.folkeregister.datomic.util.IO; import ske.folkeregister.dw.api.PersonResource; import ske.folkeregister.dw.conf.ServerConfig; import ske.folkeregister.dw.managed.DatomicConnectionManager; import ske.folkeregister.dw.managed.ThreadManager;
package ske.folkeregister.dw; public class Server extends Application<ServerConfig> { public static void main(String[] args) throws Exception { new Server().run(new String[]{"server", "src/main/conf/config.yml"}); } @Override public void initialize(Bootstrap<ServerConfig> bootstrap) { bootstrap.addBundle(new WebJarBundle()); bootstrap.addBundle(new AssetsBundle("/web/", "/web", "index.html")); } @Override public void run(ServerConfig conf, Environment env) throws Exception {
final Connection conn = IO.newMemConnection();
3
BoD/irondad
src/main/java/org/jraf/irondad/handler/commitstrip/CommitstripHandler.java
[ "public class Config {\n\n public static final boolean LOGD = true;\n\n}", "public class Constants {\n public static final String TAG = \"irondad/\";\n\n public static final String PROJECT_FULL_NAME = \"BoD irondad\";\n public static final String PROJECT_URL = \"https://github.com/BoD/irondad\";\n public static final String VERSION_NAME = \"v1.11.1\"; // xxx When updating this, don't forget to update the version in pom.xml as well\n}", "public abstract class CommandHandler extends BaseHandler {\n protected abstract String getCommand();\n\n @Override\n public boolean isMessageHandled(String channel, String fromNickname, String text, List<String> textAsList, Message message, HandlerContext handlerContext) {\n String command = getCommand();\n return text.trim().toLowerCase(Locale.getDefault()).startsWith(command.toLowerCase(Locale.getDefault()));\n }\n}", "public class HandlerContext extends HashMap<String, Object> {\n private final HandlerConfig mHandlerConfig;\n private final String mChannelName;\n private Connection mConnection;\n\n public HandlerContext(HandlerConfig handlerConfig, String channelName) {\n mHandlerConfig = handlerConfig;\n mChannelName = channelName;\n }\n\n public HandlerConfig getHandlerConfig() {\n return mHandlerConfig;\n }\n\n public void setConnection(Connection connection) {\n mConnection = connection;\n }\n\n public Connection getConnection() {\n return mConnection;\n }\n\n /**\n * @return {@code null} if this is a privmsg context.\n */\n public String getChannelName() {\n return mChannelName;\n }\n}", "public enum Command {\n //@formatter:off\n \n /*\n * Messages.\n */\n \n PING,\n PONG,\n NICK,\n USER,\n JOIN,\n PART,\n PRIVMSG,\n NAMES,\n QUIT,\n \n UNKNOWN, \n \n \n /*\n * Replies.\n */\n \n RPL_WELCOME(1),\n \n RPL_NAMREPLY(353),\n \n ERR_ERRONEUSNICKNAME(432),\n ERR_NICKNAMEINUSE(433),\n ERR_NICKCOLLISION(436),\n \n ;\n\n //@formatter:on\n\n private static final HashMap<String, Command> sCommandByName = new HashMap<String, Command>(40);\n private static final HashMap<Integer, Command> sCommandByCode = new HashMap<Integer, Command>(40);\n\n static {\n for (Command command : values()) {\n sCommandByName.put(command.name(), command);\n if (command.mCode != -1) sCommandByCode.put(command.mCode, command);\n }\n }\n\n private int mCode;\n\n private Command() {\n mCode = -1;\n }\n\n private Command(int code) {\n mCode = code;\n }\n\n public static Command from(String commandStr) {\n if (StringUtils.isNumeric(commandStr)) {\n // Reply (numeric command)\n return from(Integer.valueOf(commandStr));\n }\n // Message (string command)\n Command res = sCommandByName.get(commandStr);\n if (res == null) return UNKNOWN;\n return res;\n }\n\n public static Command from(int code) {\n Command res = sCommandByCode.get(code);\n if (res == null) return UNKNOWN;\n return res;\n }\n}", "public class Connection {\n private static final String TAG = Constants.TAG + Connection.class.getSimpleName();\n private static final String CR_LF = \"\\r\\n\";\n\n private Client mClient;\n private final BufferedReader mBufferedReader;\n private final OutputStream mOutputStream;\n\n public Connection(Client client, Socket socket) throws IOException {\n mClient = client;\n mBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), \"utf-8\"));\n mOutputStream = socket.getOutputStream();\n }\n\n public void send(String line) throws IOException {\n Log.d(TAG, \"SND \" + line);\n mOutputStream.write((line + CR_LF).getBytes(\"utf-8\"));\n }\n\n public void send(Command command, String... params) throws IOException {\n String[] paramsCopy = params.clone();\n if (paramsCopy.length > 0) {\n // Add a colon to the last param if it contains spaces\n if (paramsCopy[paramsCopy.length - 1].contains(\" \")) {\n paramsCopy[paramsCopy.length - 1] = \":\" + paramsCopy[paramsCopy.length - 1];\n }\n send(command.name() + \" \" + StringUtils.join(paramsCopy, \" \"));\n } else {\n send(command.name());\n }\n }\n\n public void send(Command command, List<String> params) throws IOException {\n String[] paramArray = params.toArray(new String[params.size()]);\n send(command, paramArray);\n }\n\n public String receiveLine() throws IOException {\n String line = mBufferedReader.readLine();\n Log.i(TAG, \"RCV \" + line);\n return line;\n }\n\n public Message receive() throws IOException {\n String line = receiveLine();\n if (line == null) return null;\n Message res = Message.parse(line);\n // if (Config.LOGD) Log.d(TAG, \"receive res=\" + res);\n return res;\n }\n\n public Client getClient() {\n return mClient;\n }\n}", "public class Message {\n /**\n * Origin of the message (can be {@code null}).\n */\n public final Origin origin;\n public final Command command;\n public final ArrayList<String> parameters;\n\n public Message(Origin origin, Command command, ArrayList<String> parameters) {\n this.origin = origin;\n this.command = command;\n this.parameters = parameters;\n }\n\n public static Message parse(String line) {\n ArrayList<String> split = split(line);\n Origin origin = null;\n if (split.get(0).startsWith(\":\")) {\n // Prefix is an optional origin\n String originStr = split.remove(0);\n // Remove colon\n originStr = originStr.substring(1);\n origin = new Origin(originStr);\n }\n String commandStr = split.remove(0);\n Command command = Command.from(commandStr);\n return new Message(origin, command, split);\n }\n\n\n\n private static ArrayList<String> split(String line) {\n ArrayList<String> split = new ArrayList<String>(10);\n int len = line.length();\n StringBuilder currentToken = new StringBuilder(10);\n boolean previousCharIsSpace = false;\n boolean lastParam = false;\n for (int i = 0; i < len; i++) {\n char c = line.charAt(i);\n if (c == ' ' && !lastParam) {\n // Space\n split.add(currentToken.toString());\n currentToken = new StringBuilder(10);\n previousCharIsSpace = true;\n } else if (c == ':' && i != 0 && previousCharIsSpace) {\n // Colon: if at start of token, the remainder is the last param (can have spaces)\n lastParam = true;\n // currentToken.append(c);\n } else {\n // Other characters\n currentToken.append(c);\n previousCharIsSpace = false;\n }\n }\n split.add(currentToken.toString());\n return split;\n }\n\n @Override\n public String toString() {\n return \"Message [origin=\" + origin + \", command=\" + command + \", parameters=\" + parameters + \"]\";\n }\n}", "public class Log {\n public static void w(String tag, String msg, Throwable t) {\n System.out.print(getDate() + \" W \" + tag + \" \" + msg + \"\\n\" + getStackTraceString(t));\n }\n\n public static void w(String tag, String msg) {\n System.out.print(getDate() + \" W \" + tag + \" \" + msg + \"\\n\");\n }\n\n public static void e(String tag, String msg, Throwable t) {\n System.out.print(getDate() + \" E \" + tag + \" \" + msg + \"\\n\" + getStackTraceString(t));\n }\n\n public static void e(String tag, String msg) {\n System.out.print(getDate() + \" E \" + tag + \" \" + msg + \"\\n\");\n }\n\n public static void d(String tag, String msg, Throwable t) {\n System.out.print(getDate() + \" D \" + tag + \" \" + msg + \"\\n\" + getStackTraceString(t));\n }\n\n public static void d(String tag, String msg) {\n System.out.print(getDate() + \" D \" + tag + \" \" + msg + \"\\n\");\n }\n\n public static void i(String tag, String msg, Throwable t) {\n System.out.print(getDate() + \" I \" + tag + \" \" + msg + \"\\n\" + getStackTraceString(t));\n }\n\n public static void i(String tag, String msg) {\n System.out.print(getDate() + \" I \" + tag + \" \" + msg + \"\\n\");\n }\n\n private static String getDate() {\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd/HH:mm:ss\");\n return sdf.format(new Date());\n }\n\n private static String getStackTraceString(Throwable tr) {\n if (tr == null) {\n return \"\";\n }\n\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n tr.printStackTrace(pw);\n return sw.toString();\n }\n}" ]
import org.jraf.irondad.Config; import org.jraf.irondad.Constants; import org.jraf.irondad.handler.CommandHandler; import org.jraf.irondad.handler.HandlerContext; import org.jraf.irondad.protocol.Command; import org.jraf.irondad.protocol.Connection; import org.jraf.irondad.protocol.Message; import org.jraf.irondad.util.Log; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.github.kevinsawicki.http.HttpRequest; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2016 Nicolas Pomepuy * Copyright (C) 2013 Benoit 'BoD' Lubek ([email protected]) * * This library 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. * * This library 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 this library; if not, see * <http://www.gnu.org/licenses/>. */ package org.jraf.irondad.handler.commitstrip; public class CommitstripHandler extends CommandHandler { private static final String TAG = Constants.TAG + CommitstripHandler.class.getSimpleName(); private static final String URL_HTML = "http://www.commitstrip.com/en/"; private final ExecutorService mThreadPool = Executors.newCachedThreadPool(); @Override protected String getCommand() { return "!commitstrip"; } @Override protected void handleChannelMessage(final Connection connection, final String channel, String fromNickname, String text, List<String> textAsList, Message message, HandlerContext handlerContext) throws Exception {
if (Config.LOGD) Log.d(TAG, "handleChannelMessage");
0
BottleRocketStudios/Android-GroundControl
GroundControl/groundcontrol/src/main/java/com/bottlerocketstudios/groundcontrol/convenience/StandardExecutionBuilder.java
[ "public class AgentExecutor implements InactivityCleanupListener {\n\n private static final String TAG = AgentExecutor.class.getSimpleName();\n\n public static final String DEFAULT_AGENT_EXECUTOR_ID = \"<def>\";\n\n private static final ConcurrentHashMap<String, AgentExecutor> sAgentExecutorMap = new ConcurrentHashMap<>();\n\n private final String mId;\n private final AgentResultCache mAgentResultCache;\n private final AgentTetherBuilder mAgentTetherBuilder;\n private final AgentPolicy mDefaultAgentPolicy;\n private final PriorityQueueingPoolExecutorService mCacheExecutorService;\n private final PriorityQueueingPoolExecutorService mAgentExecutorService;\n private final AgentRequestController mAgentRequestController;\n private final Map<String, StartedAgent> mStartedAgentMap;\n private final InactivityCleanupRunnable mInactivityCleanupRunnable;\n private final AbandonedCacheController mAbandonedCacheController;\n private final HandlerCache mHandlerCache;\n private final String mBackgroundLooperId;\n\n //Object is used for a synchronize lock to prevent other Threads from scheduling the same agent twice.\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final String mExecutionLock = \"executionLock\";\n\n /**\n * Obtain the default instance of the AgentExecutor. This is typically all you need.\n */\n public static AgentExecutor getDefault() {\n AgentExecutor agentExecutor = sAgentExecutorMap.get(DEFAULT_AGENT_EXECUTOR_ID);\n if (agentExecutor == null) {\n agentExecutor = createDefaultInstance();\n }\n return agentExecutor;\n }\n\n /**\n * Guarantee that only one instance of the AgentExecutor is built.\n */\n private static AgentExecutor createDefaultInstance() {\n synchronized (sAgentExecutorMap) {\n AgentExecutor agentExecutor = sAgentExecutorMap.get(DEFAULT_AGENT_EXECUTOR_ID);\n if (agentExecutor == null) {\n agentExecutor = builder(DEFAULT_AGENT_EXECUTOR_ID).build();\n Log.d(TAG, \"Built Default \" + String.valueOf(agentExecutor));\n sAgentExecutorMap.put(DEFAULT_AGENT_EXECUTOR_ID, agentExecutor);\n }\n return agentExecutor;\n }\n }\n\n /**\n * Obtain a different instance of the AgentExecutor created with the Builder.\n *\n * <strong>NOTE: This will have a separate instance of cache and a separate thread pool. Use multiple AgentExecutors with caution.</strong>\n *\n * @param identifier Globally unique identifier for the AgentExecutor\n */\n public static AgentExecutor getInstance(String identifier) {\n if (DEFAULT_AGENT_EXECUTOR_ID.equals(identifier)) {\n return getDefault();\n }\n return sAgentExecutorMap.get(identifier);\n }\n\n /**\n * Store a reference to a new AgentExecutor in the static map.\n */\n protected static void setInstance(String identifier, AgentExecutor agentExecutor) {\n sAgentExecutorMap.put(identifier, agentExecutor);\n }\n\n /**\n * The only constructor requires a builder instance to be created.\n */\n protected AgentExecutor(AgentExecutorBuilder builder) {\n mId = builder.getId();\n mAgentResultCache = builder.getAgentResultCache();\n mAgentTetherBuilder = builder.getAgentTetherBuilder();\n mDefaultAgentPolicy = builder.getDefaultAgentPolicy();\n mCacheExecutorService = builder.getCacheExecutorService();\n mAgentExecutorService = builder.getAgentExecutorService();\n mAgentRequestController = builder.getAgentRequestController();\n mInactivityCleanupRunnable = builder.getInactivityCleanupRunnable();\n mHandlerCache = builder.getHandlerCache();\n\n mStartedAgentMap = Collections.synchronizedMap(new HashMap<String, StartedAgent>());\n mAbandonedCacheController = new AbandonedCacheController(mAgentResultCache, builder.getAbandonedCacheTimeoutMs());\n mBackgroundLooperId = UUID.randomUUID().toString();\n }\n\n /**\n * Create a builder instance with the supplied ID. This ID must be globally unique for the\n * application, but does not need to be the same across future application instances.\n */\n public static AgentExecutorBuilder builder(String agentExecutorId) {\n return new AgentExecutorBuilder(agentExecutorId);\n }\n\n /**\n * Globally unique identifier for this AgentExecutor.\n */\n public String getId() {\n return mId;\n }\n\n /**\n * Globally unique background looper associated with background delivery via Handler. Use this\n * in your AgentPolicy if you desire notification on a background thread serially.\n */\n public String getBackgroundLooperId() {\n return mBackgroundLooperId;\n }\n\n /**\n * Enqueue a new Agent for execution with the default policy\n */\n public <ResultType, ProgressType> AgentTether runAgent(Agent<ResultType, ProgressType> agent, AgentListener<ResultType, ProgressType> agentListener) {\n return runAgent(agent, mDefaultAgentPolicy, agentListener);\n }\n\n /**\n * Enqueue a new Agent for execution.\n */\n public <ResultType, ProgressType> AgentTether runAgent(Agent<ResultType, ProgressType> agent, AgentPolicy agentPolicy, AgentListener<ResultType, ProgressType> agentListener) {\n mInactivityCleanupRunnable.restartTimer();\n\n String agentIdentifier = agent.getUniqueIdentifier();\n if (TextUtils.isEmpty(agentIdentifier)) {\n throw new IllegalArgumentException(\"Agent \" + agent.getClass().getCanonicalName() + \" returned '\" + String.valueOf(agentIdentifier) + \"' from getUniqueIdentifier(). The identifier must be a non-empty String.\");\n }\n\n AgentTether agentTether = createAgentTether(agentListener, agentIdentifier);\n\n AgentRequest<ResultType, ProgressType> agentRequest = new AgentRequest<>(agent, agentListener, agentPolicy);\n\n if (agentRequest.shouldClearCache()) {\n mAgentResultCache.removeCache(agentIdentifier);\n }\n\n if (agentRequest.shouldBypassCache() || agentRequest.shouldClearCache()) {\n startAgentRequest(agentRequest);\n } else {\n startCacheRequest(agentRequest, false);\n }\n\n return agentTether;\n }\n\n private <ResultType, ProgressType> AgentTether createAgentTether(AgentListener<ResultType, ProgressType> agentListener, String agentIdentifier) {\n AgentTether agentTether;\n synchronized (mAgentTetherBuilder) {\n agentTether = mAgentTetherBuilder\n .clear()\n .setAgentExecutor(this)\n .setAgentIdentifier(agentIdentifier)\n .setAgentListener(agentListener)\n .build();\n mAgentTetherBuilder.clear();\n }\n mAbandonedCacheController.addWeakTether(agentIdentifier, agentTether);\n return agentTether;\n }\n\n /**\n * Attach for delivery of an already running agent or hit cache only, do not re-run the agent with the default policy.\n */\n public <ResultType, ProgressType> AgentTether reattachToOneTimeAgent(String agentIdentifier, AgentListener<ResultType, ProgressType> agentListener) {\n return reattachToOneTimeAgent(agentIdentifier, mDefaultAgentPolicy, agentListener);\n }\n\n /**\n * Attach for delivery of an already running agent or hit cache only, do not re-run the agent.\n */\n public <ResultType, ProgressType> AgentTether reattachToOneTimeAgent(String agentIdentifier, AgentPolicy agentPolicy, AgentListener<ResultType, ProgressType> agentListener) {\n AgentTether agentTether = createAgentTether(agentListener, agentIdentifier);\n\n HollowAgent<ResultType, ProgressType> hollowAgent = new HollowAgent<>(agentIdentifier);\n\n AgentRequest<ResultType, ProgressType> agentRequest = new AgentRequest<>(hollowAgent, agentListener, agentPolicy);\n\n StartedAgent startedAgent = getStartedAgent(agentIdentifier);\n if (startedAgent != null) {\n mAgentRequestController.addAgentRequest(agentRequest);\n updatePendingAgentExecution(startedAgent, agentRequest);\n } else {\n if (agentPolicy.shouldBypassCache()) {\n Log.i(TAG, \"Policy bypassCache directive ignored when reattaching to one-time agents.\");\n }\n startCacheRequest(agentRequest, true);\n }\n\n return agentTether;\n }\n\n /**\n * Begin an asynchronous cache check. This will be off of the UI thread, but cache implementations should be very few clock cycles.\n * It is primarily taken off of the UI thread to ensure that delivery is asynchronous.\n */\n private <ResultType, ProgressType> void startCacheRequest(AgentRequest<ResultType, ProgressType> agentRequest, final boolean failOnCacheMiss) {\n CacheCheckRunnable<ResultType, ProgressType> cacheCheckRunnable = new CacheCheckRunnable<>(\n mAgentResultCache,\n agentRequest,\n new CacheCheckRunnableListener<ResultType, ProgressType>() {\n @Override\n public void onCacheResult(AgentRequest<ResultType, ProgressType> agentRequest, ResultType result) {\n try {\n if (result != null) {\n mAgentRequestController.deliverCompletion(agentRequest, result);\n } else if (failOnCacheMiss) {\n mAgentRequestController.deliverCompletion(agentRequest, null);\n } else {\n startAgentRequest(agentRequest);\n }\n } catch (ClassCastException e) {\n Log.e(TAG, \"Cache result was of an unexpected type\");\n }\n }\n });\n\n Job cacheCheckJob = new Job(mCacheExecutorService.getNextJobId(), cacheCheckRunnable, agentRequest.getPolicyTimeoutMs(), agentRequest.getJobPriority());\n mCacheExecutorService.enqueue(cacheCheckJob);\n }\n\n /**\n * Begin an agent request or add a redundant request to the list of waiting requests.\n */\n private <ResultType, ProgressType> void startAgentRequest(AgentRequest<ResultType, ProgressType> agentRequest) {\n synchronized (mExecutionLock) {\n mAgentRequestController.addAgentRequest(agentRequest);\n\n StartedAgent startedAgent = getStartedAgent(agentRequest.getAgentIdentifier());\n if (startedAgent == null) {\n addNewPendingAgentExecution(agentRequest);\n } else {\n updatePendingAgentExecution(startedAgent, agentRequest);\n }\n }\n }\n\n /**\n * Request is not already in progress. Enqueue it.\n */\n private <ResultType, ProgressType> void addNewPendingAgentExecution(AgentRequest<ResultType, ProgressType> agentRequest) {\n //Store the StartedAgent data.\n Agent<ResultType, ProgressType> agent = agentRequest.getAgent();\n Job agentJob = new Job(mAgentExecutorService.getNextJobId(), agent, agent.getRunTimeoutMs(), agentRequest.getJobPriority());\n StartedAgent startedAgent = StartedAgent.newStartedAgent(agentRequest, agent, agentJob);\n agentJob.setJobExecutionListener(startedAgent);\n addStartedAgent(agentRequest.getAgentIdentifier(), startedAgent);\n\n //Set the agent executor to this instance.\n agent.setAgentExecutor(this);\n\n //Set the listener to an anonymous instance.\n agent.setAgentListener(new AgentListener<ResultType, ProgressType>() {\n @Override\n public void onCompletion(String agentIdentifier, ResultType result) {\n StartedAgent startedAgent = removeStartedAgent(agentIdentifier);\n mAgentRequestController.notifyAgentCompletion(agentIdentifier, result);\n //The startedAgent may be null if an agent is cancelled then expunged by exceeding time limits and sends completion later anyway.\n if (startedAgent != null) {\n mAgentResultCache.put(agentIdentifier, result, startedAgent.getInitialCacheAgeMs());\n }\n }\n\n @Override\n public void onProgress(String agentIdentifier, ProgressType progress) {\n mAgentRequestController.notifyAgentProgress(agentIdentifier, progress);\n }\n });\n\n mAgentExecutorService.enqueue(agentJob);\n }\n\n /**\n * Request is already in progress. Update any escalations, add this request to the delivery list and request a progress update.\n */\n private <ResultType, ProgressType> void updatePendingAgentExecution(StartedAgent startedAgent, AgentRequest<ResultType, ProgressType> agentRequest) {\n //Check job priority against queued/running job to promote if necessary.\n Job agentJob = startedAgent.getJob();\n if (agentJob != null && agentJob.getPriority().compareTo(agentRequest.getJobPriority()) < 0) {\n mAgentExecutorService.updateJobPriority(agentJob.getId(), agentRequest.getJobPriority());\n }\n\n //Adjust max cache age for coalesced requests before completion.\n startedAgent.setInitialCacheAgeMs(Math.max(startedAgent.getInitialCacheAgeMs(), agentRequest.getMaxCacheAgeMs()));\n\n //Request progress update\n startedAgent.requestProgressUpdate();\n }\n\n /**\n * Release this tether then cancel a running agent associated with the tether if no more listeners exist.\n */\n public void tetherCancel(AgentTether tether, String agentIdentifier, AgentListener agentListener) {\n tetherRelease(tether, agentIdentifier, agentListener);\n\n //There aren't any other AgentRequests associated with this agentIdentifier, cancel the associated agent.\n if (!mAgentRequestController.hasActiveRequests(agentIdentifier)) {\n cancelAgent(agentIdentifier);\n }\n }\n\n /**\n * Release this tether and allow the agent to continue execution.\n */\n public void tetherRelease(AgentTether tether, String agentIdentifier, AgentListener agentListener) {\n //Remove this listener\n mAgentRequestController.removeRequestForAgent(agentIdentifier, agentListener);\n mAbandonedCacheController.removeWeakTether(agentIdentifier, tether);\n }\n\n /**\n * Notify an agent that it should cancel.\n */\n private void cancelAgent(String agentIdentifier) {\n StartedAgent startedAgent = getStartedAgent(agentIdentifier);\n if (startedAgent != null) {\n startedAgent.cancel();\n }\n }\n\n @Override\n public boolean isBusy() {\n return mStartedAgentMap.size() > 0;\n }\n\n @Override\n public void enterIdleState() {\n mHandlerCache.stopHandler(getBackgroundLooperId());\n }\n\n @Override\n public void performCleanup() {\n mAgentRequestController.notifyPastDeadline();\n cancelExpiredAgents();\n cleanCache();\n }\n\n /**\n * Clean up any untethered cache entries.\n */\n private void cleanCache() {\n mAbandonedCacheController.cleanupUntetheredCache();\n }\n\n /**\n * Clean up and cancel agents that are not running or tell overdue agents to cancel.\n */\n @SuppressWarnings(\"ForLoopReplaceableByForEach\")\n private void cancelExpiredAgents() {\n synchronized (mStartedAgentMap) {\n /*\n * Take a snapshot of the key Set. If the Agent notifies of failure immediately upon\n * cancellation, Agent will be removed from mStartedAgentMap in a re-entrant way on the\n * current thread which modifies the key Set without being blocked by synchronization.\n *\n * We perform a null check on the value referenced by the key to avoid a potential\n * mismatch between the snapshot key set and the mStartedAgentMap.\n */\n Set<String> snapshotKeySet = new HashSet<>(mStartedAgentMap.keySet());\n for (Iterator<String> startedAgentMapKeyIterator = snapshotKeySet.iterator(); startedAgentMapKeyIterator.hasNext(); ) {\n String agentIdentifier = startedAgentMapKeyIterator.next();\n StartedAgent startedAgent = getStartedAgent(agentIdentifier);\n if (startedAgent != null) {\n if (startedAgent.isPastMaximumDeadline()) {\n Log.w(TAG, \"Giving up on overdue agent \" + startedAgent);\n removeStartedAgent(agentIdentifier);\n } else if (!startedAgent.isCancelled() && startedAgent.isPastCancellationDeadline()) {\n Log.w(TAG, \"Cancelling overdue agent \" + startedAgent);\n cancelAgent(agentIdentifier);\n }\n }\n }\n }\n }\n\n private StartedAgent removeStartedAgent(String agentIdentifier) {\n return mStartedAgentMap.remove(agentIdentifier);\n }\n\n private void addStartedAgent(String agentIdentifier, StartedAgent startedAgent) {\n synchronized (mStartedAgentMap) {\n if (mStartedAgentMap.containsKey(agentIdentifier)) {\n throw new RuntimeException(\"More than one agent started for agentIdentifier: \" + agentIdentifier);\n }\n mStartedAgentMap.put(agentIdentifier, startedAgent);\n }\n }\n\n private StartedAgent getStartedAgent(String agentIdentifier) {\n return mStartedAgentMap.get(agentIdentifier);\n }\n\n public boolean hasStartedAgent(String agentIdentifier) {\n return getStartedAgent(agentIdentifier) != null;\n }\n\n}", "public interface Agent<ResultType, ProgressType> extends Runnable {\n /**\n * Provide a globally unique string to identify this agent. All identical agents will\n * be executed one at a time. If available, cached values for Agents with the same unique\n * identifier will be delivered.\n */\n String getUniqueIdentifier();\n\n /**\n * Stop executing ASAP, your result is no longer needed. If this is a meta-Agent cancel any\n * associated AgentTethers you have created. This will also be called after cancelTimeoutMs\n * has elapsed.\n */\n void cancel();\n\n /**\n * Maximum amount of time in milliseconds to allow an Agent's run operation to run before being interrupted.\n * Using a very large number with a repeated task that fails to complete may result in exhausted Thread\n * pool. Must be greater than getCancelTimeoutMs(). <strong>This value will be read before execution.</strong>\n */\n long getRunTimeoutMs();\n\n /**\n * Maximum amount of time in milliseconds starting at run() before cancel() is called if incomplete.\n * <strong>This value will be read before execution.</strong>\n */\n long getCancelTimeoutMs();\n\n /**\n * Maximum amount of time in milliseconds starting at run() to being discarded even if incomplete. Must be\n * greater than getCancelTimeoutMs() and getRunTimeoutMs(). <strong>This value will be read before execution.</strong>\n */\n long getMaximumTimeoutMs();\n\n /**\n * Set the listener for the agent. This listener must be called when the agent has completed or has\n * progress to deliver.\n */\n void setAgentListener(AgentListener<ResultType, ProgressType> agentListener);\n\n /**\n * Set the agentExecutor that will be running this agent. This is guaranteed to be populated before run().\n * This should be used to spawn further Agent executions and ensures that an Agent could be used with\n * multiple executors and not be tightly coupled to any specific instance.\n *\n * <p><strong>You must not perform work in this operation other than storing the reference.</strong></p>\n */\n void setAgentExecutor(AgentExecutor agentExecutor);\n\n /**\n * At the Agent's next convenience, deliver a progress update if applicable. This will be called when\n * an already running Agent has a new AgentRequest queued.\n */\n void onProgressUpdateRequested();\n}", "public enum JobPriority {\n IMMEDIATE,\n HIGH,\n NORMAL,\n LOW\n}", "public interface AgentListener<ResultType, ProgressType> {\n /**\n * Request has been completed with the associated result value.\n */\n void onCompletion(String agentIdentifier, ResultType result);\n\n /**\n * Request is still in progress and provided an update.\n */\n void onProgress(String agentIdentifier, ProgressType progress);\n}", "public class LooperController {\n private static final String TAG = LooperController.class.getSimpleName();\n\n public static final String UI_LOOPER_ID = \"uiLooperId\";\n\n private static final long MAX_CREATION_TIME_MS = TimeUnit.SECONDS.toMillis(2);\n\n private static final Map<String, Looper> sLooperMap = Collections.synchronizedMap(new HashMap<String, Looper>());\n\n /**\n * Return the main Looper associated with the UI\n */\n private static Looper getUiLooper() {\n return Looper.getMainLooper();\n }\n\n /**\n * Return the looper associated with the provided ID. Use Process.THREAD_PRIORITY_BACKGROUND for non UI Looper.\n * @see com.bottlerocketstudios.groundcontrol.looper.LooperController#UI_LOOPER_ID\n */\n public static Looper getLooper(String looperId) {\n return getLooper(looperId, Process.THREAD_PRIORITY_BACKGROUND);\n }\n\n /**\n * Return the looper associated with the provided ID and if not present, create one with the provided priority.\n * If UI_LOOPER_ID is provided, no change in priority will occur.\n * @see com.bottlerocketstudios.groundcontrol.looper.LooperController#UI_LOOPER_ID\n */\n public static Looper getLooper(String looperId, int osThreadPriority) {\n if (UI_LOOPER_ID.equals(looperId)) {\n return getUiLooper();\n } else {\n synchronized (sLooperMap) {\n Looper looper = sLooperMap.get(looperId);\n if (looper == null) {\n looper = createLooper(osThreadPriority);\n sLooperMap.put(looperId, looper);\n }\n return looper;\n }\n }\n }\n\n /**\n * Stop the looper associated with the provided ID. If UI_LOOPER_ID is provided, nothing will happen.\n */\n public static void stopLooper(String looperId) {\n Looper looper = sLooperMap.remove(looperId);\n if (looper != null) {\n quitLooper(looper);\n }\n }\n\n\n @SuppressLint(\"NewApi\")\n private static void quitLooper(Looper looper) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {\n looper.quitSafely();\n } else {\n looper.quit();\n }\n }\n\n private static class Container<T> {\n T mValue;\n\n public void setValue(T value) {\n mValue = value;\n }\n\n public T getValue() {\n return mValue;\n }\n }\n\n private static Looper createLooper(final int osThreadPriority) {\n final Container<Looper> looperContainer = new Container<>();\n\n if (osThreadPriority < Process.THREAD_PRIORITY_URGENT_AUDIO || osThreadPriority > Process.THREAD_PRIORITY_LOWEST) {\n throw new IllegalArgumentException(\"Cannot set thread priority to \" + osThreadPriority);\n }\n\n Thread thread = new Thread() {\n @Override\n public void run() {\n super.run();\n android.os.Looper.prepare();\n Process.setThreadPriority(osThreadPriority);\n looperContainer.setValue(Looper.myLooper());\n Looper.loop();\n }\n };\n thread.start();\n\n //Wait until looper is ready.\n long creationStart = SystemClock.uptimeMillis();\n while (looperContainer.getValue() == null && SystemClock.uptimeMillis() - creationStart < MAX_CREATION_TIME_MS) {\n try {\n Thread.sleep(5);\n } catch (InterruptedException e) {\n Log.e(TAG, \"Caught java.lang.InterruptedException\", e);\n }\n }\n\n return looperContainer.getValue();\n }\n}", "public class AgentPolicy {\n private final String mCallbackLooperId;\n private final long mPolicyTimeoutMs;\n private final long mParallelCallbackTimeoutMs;\n private final long mMaxCacheAgeMs;\n private final JobPriority mJobPriority;\n private final boolean mParallelBackgroundCallback;\n private final boolean mBypassCache;\n private final boolean mClearCache;\n\n public AgentPolicy(AgentPolicyBuilder builder) {\n mCallbackLooperId = builder.getCallbackLooperId();\n mPolicyTimeoutMs = builder.getPolicyTimeoutMs();\n mMaxCacheAgeMs = builder.getMaxCacheAgeMs();\n mJobPriority = builder.getJobPriority();\n mParallelBackgroundCallback = builder.isParallelBackgroundCallback();\n mBypassCache = builder.shouldBypassCache();\n mParallelCallbackTimeoutMs = builder.getParallelCallbackTimeoutMs();\n mClearCache = builder.shouldClearCache();\n }\n\n public String getCallbackLooperId() {\n return mCallbackLooperId;\n }\n\n public long getPolicyTimeoutMs() {\n return mPolicyTimeoutMs;\n }\n\n public long getMaxCacheAgeMs() {\n return mMaxCacheAgeMs;\n }\n\n public JobPriority getJobPriority() {\n return mJobPriority;\n }\n\n public boolean isParallelBackgroundCallback() {\n return mParallelBackgroundCallback;\n }\n\n public boolean shouldBypassCache() {\n return mBypassCache;\n }\n\n public long getParallelCallbackTimeoutMs() {\n return mParallelCallbackTimeoutMs;\n }\n\n public boolean shouldClearCache() {\n return mClearCache;\n }\n}", "public interface AgentPolicyBuilder {\n\n /**\n * <p>\n * Set the LooperId to use for callback operations. This should be one of two standard looperIds\n * {@link com.bottlerocketstudios.groundcontrol.looper.LooperController#UI_LOOPER_ID} or\n * {@link com.bottlerocketstudios.groundcontrol.AgentExecutor#getBackgroundLooperId()}.\n * Managing lifecycle on your own Looper is highly discouraged as it will only die when the OS cleans up the app.\n * The AgentExecutor's Looper is managed and corresponds to a lack of work for the AgentExecutor.\n * </p><p>\n * Using the {@link com.bottlerocketstudios.groundcontrol.AgentExecutor#getBackgroundLooperId()} is recommended when\n * the listener will perform database operations using the resulting data. This prevents multiple threads from\n * accessing the database simultaneously which may result in inconsistent data.\n * </p><p>\n * Messages posted to a Handler will be executed FIFO serially. If you require parallel background thread callbacks use\n * {@link com.bottlerocketstudios.groundcontrol.policy.AgentPolicyBuilder#setParallelBackgroundCallback(boolean)}\n * </p>\n * <strong>\n * You cannot both set a callback Looper ID and call setParallelBackgroundCallback on the same policy.\n * </strong>\n */\n AgentPolicyBuilder setCallbackLooperId(String callbackLooperId);\n\n String getCallbackLooperId();\n\n /**\n * <p>\n * Callback operations will occur in parallel within the limitations of the Thread pool on multiple\n * background threads.\n * </p><p>\n * If you require serial callbacks on a background thread use setCallbackLooperId with\n * {@link com.bottlerocketstudios.groundcontrol.AgentExecutor#getBackgroundLooperId()}.\n * </p>\n * <strong>\n * You cannot both set a callback Looper ID and call setParallelBackgroundCallback on the same policy.\n * </strong>\n */\n AgentPolicyBuilder setParallelBackgroundCallback(boolean parallelBackgroundCallback);\n\n boolean isParallelBackgroundCallback();\n\n /**\n * Timeout in milliseconds before the listener will be notified with a null completion. This timeout\n * will start running as soon as a Policy is submitted.\n */\n AgentPolicyBuilder setPolicyTimeoutMs(long policyTimeoutMs);\n\n long getPolicyTimeoutMs();\n\n /**\n * Maximum age in milliseconds for a cached response to be considered valid by this Policy.\n * <ul>\n * <li>The highest number submitted will become the cached item's new maximum age. That\n * does not affect cached item creation time, however it will increase its cached lifetime.</li>\n * <li>Other Policies may specify a shorter time and cause a cache miss which will fire the Agent. The\n * Policies with shorter valid ages will receive a cache hit.</li>\n * <li>A CacheAge of 0 will not be stored unless another Policy specifies a higher value. </li>\n * </ul>\n *\n * <strong>SUPER IMPORTANT</strong>Cached items are only retained while a Tether is held for the\n * associated agentIdentifier. It is designed for use with UI components to keep results in\n * memory across destroy/create actions in the UI. If you need to have in-memory long-term caching,\n * implement those outside of this tool.\n *\n * @see com.bottlerocketstudios.groundcontrol.policy.AgentPolicyBuilder#setBypassCache(boolean)\n */\n AgentPolicyBuilder setMaxCacheAgeMs(long maxCacheAgeMs);\n\n long getMaxCacheAgeMs();\n\n /**\n * This parameter determines the execution priority of the Agent as well as cache and listener callbacks. However,\n * listeners which are fired on a Handler are serially executed without attention to priority. If a Policy is\n * submitted for an Agent with a higher priority, that priority becomes the new priority. Agents with IMMEDIATE\n * priority skip the queue and are executed immediately. Use IMMEDIATE priority with caution hoss.\n */\n AgentPolicyBuilder setJobPriority(JobPriority jobPriority);\n\n JobPriority getJobPriority();\n\n /**\n * Do not attempt to read from cache despite cache age.\n */\n AgentPolicyBuilder setBypassCache(boolean bypassCache);\n\n boolean shouldBypassCache();\n\n /**\n * Set the amount of time in milliseconds for a parallelBackgroundCallback operation to last before\n * being interrupted.\n */\n AgentPolicyBuilder setParallelCallbackTimeoutMs(long timeoutMs);\n\n long getParallelCallbackTimeoutMs();\n\n /**\n * Set whether the invocation of this agent should clear the cache so that future requests cannot\n * hit a cached value until this invocation completes. i.e. The old data is no longer valid.\n * <strong>Clearing cache includes bypassing cache.</strong>\n */\n AgentPolicyBuilder setClearCache(boolean clearCache);\n\n boolean shouldClearCache();\n\n /**\n * Clear this builder to build a new instance.\n */\n AgentPolicyBuilder clear();\n\n /**\n * Clear then start with the provided policy as baseline values for this build.\n */\n AgentPolicyBuilder buildUpon(AgentPolicy agentPolicy);\n\n /**\n * Set both cache lifetime to 0 and bypass cache to true.\n */\n AgentPolicyBuilder disableCache();\n\n /**\n * Perform validation, set defaults, and deliver built instance of AgentPolicy.\n */\n AgentPolicy build();\n\n}", "public class StandardAgentPolicyBuilder implements AgentPolicyBuilder {\n\n private static final String DEFAULT_CALLBACK_LOOPER_ID = LooperController.UI_LOOPER_ID;\n private static final long DEFAULT_POLICY_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(5);\n private static final long DEFAULT_CACHE_AGE_MS = TimeUnit.MINUTES.toMillis(2);\n private static final long DEFAULT_PARALLEL_CALLBACK_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(6);\n private static final JobPriority DEFAULT_JOB_PRIORITY = JobPriority.NORMAL;\n private static final boolean DEFAULT_PARALLEL_BACKGROUND_CALLBACK = false;\n\n private String mDefaultCallbackLooperId;\n private long mDefaultPolicyTimeoutMs;\n private long mDefaultCacheAgeMs;\n private long mDefaultParallelCallbackTimeoutMs;\n private JobPriority mDefaultJobPriority;\n private boolean mDefaultParallelBackgroundCallback;\n\n private String mCallbackLooperId;\n private long mPolicyTimeoutMs;\n private long mMaxCacheAgeMs;\n private long mParallelCallbackTimeoutMs;\n private JobPriority mJobPriority;\n private Boolean mParallelBackgroundCallback;\n private boolean mBypassCache;\n private boolean mClearCache;\n\n private boolean mCallbackSet;\n\n public StandardAgentPolicyBuilder() {\n mDefaultCallbackLooperId = DEFAULT_CALLBACK_LOOPER_ID;\n mDefaultPolicyTimeoutMs = DEFAULT_POLICY_TIMEOUT_MS;\n mDefaultCacheAgeMs = DEFAULT_CACHE_AGE_MS;\n mDefaultParallelCallbackTimeoutMs = DEFAULT_PARALLEL_CALLBACK_TIMEOUT_MS;\n mDefaultJobPriority = DEFAULT_JOB_PRIORITY;\n mDefaultParallelBackgroundCallback = DEFAULT_PARALLEL_BACKGROUND_CALLBACK;\n clear();\n }\n\n public void setDefaultCallbackLooperId(String defaultCallbackLooperId) {\n if (mDefaultParallelBackgroundCallback && defaultCallbackLooperId != null) {\n throw new IllegalArgumentException(\"You must setDefaultParallelBackgroundCallback(false) first\");\n }\n mDefaultCallbackLooperId = defaultCallbackLooperId;\n }\n\n public void setDefaultPolicyTimeoutMs(long defaultPolicyTimeoutMs) {\n mDefaultPolicyTimeoutMs = defaultPolicyTimeoutMs;\n }\n\n public void setDefaultCacheAgeMs(long defaultCacheAgeMs) {\n mDefaultCacheAgeMs = defaultCacheAgeMs;\n }\n\n public void setDefaultParallelCallbackTimeoutMs(long defaultParallelCallbackTimeoutMs) {\n mDefaultParallelCallbackTimeoutMs = defaultParallelCallbackTimeoutMs;\n }\n\n public void setDefaultJobPriority(JobPriority defaultJobPriority) {\n mDefaultJobPriority = defaultJobPriority;\n }\n\n public void setDefaultParallelBackgroundCallback(boolean defaultParallelBackgroundCallback) {\n if (mDefaultCallbackLooperId != null && defaultParallelBackgroundCallback) {\n throw new IllegalArgumentException(\"You must setDefaultCallbackLooperId(null) first\");\n }\n mDefaultParallelBackgroundCallback = defaultParallelBackgroundCallback;\n }\n\n @Override\n public AgentPolicyBuilder setCallbackLooperId(String callbackLooperId) {\n if (mCallbackSet) {\n throw new IllegalArgumentException(\"Cannot call either setParallelBackgroundCallback or setCallbackLooperId again without clearing\");\n } else if (TextUtils.isEmpty(callbackLooperId)) {\n throw new IllegalArgumentException(\"callbackLooperId cannot be empty or null. Maybe you were trying to setParallelBackgroundCallback(true)?\");\n }\n mCallbackLooperId = callbackLooperId;\n mCallbackSet = true;\n if (isBackgroundLooper(callbackLooperId)) {\n disableCache();\n }\n return this;\n }\n\n @Override\n public String getCallbackLooperId() {\n return mCallbackLooperId;\n }\n\n @Override\n public AgentPolicyBuilder setParallelBackgroundCallback(boolean parallelBackgroundCallback) {\n if (mCallbackSet) {\n throw new IllegalArgumentException(\"Cannot call either setParallelBackgroundCallback or setCallbackLooperId again without clearing\");\n } else if (!parallelBackgroundCallback) {\n throw new IllegalArgumentException(\"Do not setParallelBackgroundCallback(false) instead call setCallbackLooperId\");\n }\n mParallelBackgroundCallback = true;\n mCallbackSet = true;\n disableCache();\n return this;\n }\n\n @Override\n public boolean isParallelBackgroundCallback() {\n return mParallelBackgroundCallback;\n }\n\n @Override\n public AgentPolicyBuilder setPolicyTimeoutMs(long policyTimeoutMs) {\n mPolicyTimeoutMs = policyTimeoutMs;\n return this;\n }\n\n @Override\n public long getPolicyTimeoutMs() {\n return mPolicyTimeoutMs;\n }\n\n @Override\n public AgentPolicyBuilder setMaxCacheAgeMs(long maxCacheAgeMs) {\n mMaxCacheAgeMs = maxCacheAgeMs;\n return this;\n }\n\n @Override\n public long getMaxCacheAgeMs() {\n return mMaxCacheAgeMs;\n }\n\n @Override\n public long getParallelCallbackTimeoutMs() {\n return mParallelCallbackTimeoutMs;\n }\n\n @Override\n public AgentPolicyBuilder setClearCache(boolean clearCache) {\n mClearCache = clearCache;\n return this;\n }\n\n @Override\n public boolean shouldClearCache() {\n return mClearCache;\n }\n\n @Override\n public AgentPolicyBuilder setParallelCallbackTimeoutMs(long parallelCallbackTimeoutMs) {\n mParallelCallbackTimeoutMs = parallelCallbackTimeoutMs;\n return this;\n }\n\n @Override\n public AgentPolicyBuilder setJobPriority(JobPriority jobPriority) {\n mJobPriority = jobPriority;\n return this;\n }\n\n @Override\n public JobPriority getJobPriority() {\n return mJobPriority;\n }\n\n @Override\n public AgentPolicyBuilder setBypassCache(boolean bypassCache) {\n mBypassCache = bypassCache;\n return this;\n }\n\n @Override\n public boolean shouldBypassCache() {\n return mBypassCache;\n }\n\n @Override\n public AgentPolicyBuilder clear() {\n mCallbackLooperId = null;\n mParallelBackgroundCallback = false;\n mCallbackSet = false;\n setPolicyTimeoutMs(0);\n setMaxCacheAgeMs(-1);\n setParallelCallbackTimeoutMs(0);\n setJobPriority(null);\n setBypassCache(false);\n setClearCache(false);\n return this;\n }\n\n @Override\n public AgentPolicyBuilder buildUpon(AgentPolicy agentPolicy) {\n clear();\n\n if (agentPolicy == null) {\n //When given a null policy to build upon, just clear to defaults.\n return this;\n }\n\n if (agentPolicy.isParallelBackgroundCallback()) {\n setParallelBackgroundCallback(true);\n } else {\n setCallbackLooperId(agentPolicy.getCallbackLooperId());\n }\n setPolicyTimeoutMs(agentPolicy.getPolicyTimeoutMs());\n setMaxCacheAgeMs(agentPolicy.getMaxCacheAgeMs());\n setParallelCallbackTimeoutMs(agentPolicy.getParallelCallbackTimeoutMs());\n setJobPriority(agentPolicy.getJobPriority());\n setBypassCache(agentPolicy.shouldBypassCache());\n setClearCache(agentPolicy.shouldClearCache());\n return this;\n }\n\n @Override\n public AgentPolicy build() {\n if (!mCallbackSet) {\n if (mDefaultParallelBackgroundCallback) {\n setParallelBackgroundCallback(true);\n } else {\n setCallbackLooperId(mDefaultCallbackLooperId);\n }\n }\n\n if (getPolicyTimeoutMs() <= 0) {\n setPolicyTimeoutMs(mDefaultPolicyTimeoutMs);\n }\n\n if (getMaxCacheAgeMs() < 0) {\n setMaxCacheAgeMs(mDefaultCacheAgeMs);\n }\n\n if (getParallelCallbackTimeoutMs() <= 0) {\n setParallelCallbackTimeoutMs(mDefaultParallelCallbackTimeoutMs);\n }\n\n if (getJobPriority() == null) {\n setJobPriority(mDefaultJobPriority);\n }\n\n validatePolicy();\n\n return new AgentPolicy(this);\n }\n\n @Override\n public AgentPolicyBuilder disableCache() {\n setBypassCache(true);\n setMaxCacheAgeMs(0);\n return this;\n }\n\n private void validatePolicy() {\n if (isUsingCacheOnBackgroundRequest()) {\n throw new IllegalStateException(\"Cannot build a policy that will use cache for a background delivery. Cache should only be used for UI Looper delivery. Call setBypassCache(true).\");\n }\n\n if (shouldClearCache()) {\n //Cannot clear cache without also bypassing it.\n setBypassCache(true);\n }\n\n }\n\n private boolean isBackgroundLooper(String callbackLooperId) {\n return !TextUtils.equals(LooperController.UI_LOOPER_ID, callbackLooperId);\n }\n\n private boolean isUsingCacheOnBackgroundRequest() {\n return !shouldBypassCache() && (isParallelBackgroundCallback() || isBackgroundLooper(getCallbackLooperId()));\n }\n}", "public interface AgentTether {\n /**\n * Stop the Agent now, interrupting it if it is running and no other AgentListeners are registered for\n * identical Agents.\n */\n void cancel();\n\n /**\n * Unregister interest in the result of the Agent, but let it complete. This should be used in\n * most cases of short-running requests that wouldn't hurt to complete or in the event of\n * device rotation.\n */\n void release();\n\n /**\n * Return the agent identifier associated with this agent tether\n */\n String getAgentIdentifier();\n}" ]
import android.text.TextUtils; import android.util.Log; import com.bottlerocketstudios.groundcontrol.AgentExecutor; import com.bottlerocketstudios.groundcontrol.agent.Agent; import com.bottlerocketstudios.groundcontrol.executor.JobPriority; import com.bottlerocketstudios.groundcontrol.listener.AgentListener; import com.bottlerocketstudios.groundcontrol.looper.LooperController; import com.bottlerocketstudios.groundcontrol.policy.AgentPolicy; import com.bottlerocketstudios.groundcontrol.policy.AgentPolicyBuilder; import com.bottlerocketstudios.groundcontrol.policy.StandardAgentPolicyBuilder; import com.bottlerocketstudios.groundcontrol.tether.AgentTether; import java.util.concurrent.TimeUnit;
/* * Copyright (c) 2016. Bottle Rocket LLC * 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.bottlerocketstudios.groundcontrol.convenience; /** * Standard implementation of ExecutionBuilder. New instances should be created by the StandardExecutionBuilderFactory. */ public class StandardExecutionBuilder<ResultType, ProgressType> implements ExecutionBuilder<ResultType, ProgressType> { private static final long DEFAULT_ONE_TIME_CACHE_AGE_MS = TimeUnit.MINUTES.toMillis(2); private static final String TAG = StandardExecutionBuilder.class.getSimpleName(); private final Agent<ResultType, ProgressType> mAgent; private final String mAgentExecutorId;
private final Class<? extends AgentPolicyBuilder> mAgentPolicyBuilderClass;
6
DDoS/JICI
src/main/java/ca/sapon/jici/lexer/literal/number/LongLiteral.java
[ "public class Environment {\n // TODO make me thread safe\n private static final Map<String, Class<?>> DEFAULT_CLASSES = new HashMap<>();\n private final Map<String, Class<?>> classes = new LinkedHashMap<>(DEFAULT_CLASSES);\n private final Map<String, Variable> variables = new LinkedHashMap<>();\n\n static {\n for (String name : ReflectionUtil.JAVA_LANG_CLASSES) {\n try {\n DEFAULT_CLASSES.put(name, Class.forName(\"java.lang.\" + name));\n } catch (ClassNotFoundException e) {\n throw new IllegalStateException(\"class java.lang.\" + name + \" not found\");\n }\n }\n }\n\n public void importClass(Class<?> _class) {\n final String name = _class.getCanonicalName();\n // Validate the type of class\n if (_class.isPrimitive()) {\n throw new UnsupportedOperationException(\"Can't import a primitive type: \" + name);\n }\n if (_class.isArray()) {\n throw new UnsupportedOperationException(\"Can't import an array class: \" + name);\n }\n if (_class.isAnonymousClass()) {\n throw new UnsupportedOperationException(\"Can't import an anonymous class: \" + name);\n }\n // Check for existing import under the same simple name\n final String simpleName = _class.getSimpleName();\n final Class<?> existing = classes.get(simpleName);\n // ignore cases where the classes are the same as redundant imports are allowed\n if (existing != null && _class != existing) {\n throw new UnsupportedOperationException(\"Class \" + name + \" clashes with existing import \" + existing.getCanonicalName());\n }\n // Add the class to the imports\n classes.put(simpleName, _class);\n }\n\n public Class<?> findClass(Identifier name) {\n return classes.get(name.getSource());\n }\n\n public Class<?> getClass(Identifier name) {\n final Class<?> _class = findClass(name);\n if (_class == null) {\n throw new UnsupportedOperationException(\"Class \" + name.getSource() + \" does not exist\");\n }\n return _class;\n }\n\n public Collection<Class<?>> getClasses() {\n return classes.values();\n }\n\n public boolean hasClass(Identifier name) {\n return classes.containsKey(name.getSource());\n }\n\n public boolean hasClass(Class<?> _class) {\n return classes.containsValue(_class);\n }\n\n public void declareVariable(Identifier name, LiteralType type, Value value) {\n if (hasVariable(name)) {\n throw new UnsupportedOperationException(\"Variable \" + name.getSource() + \" is already declared\");\n }\n variables.put(name.getSource(), new Variable(name, type, value));\n }\n\n public LiteralType getVariableType(Identifier name) {\n return findVariable(name).getType();\n }\n\n public Value getVariable(Identifier name) {\n return findVariable(name).getValue();\n }\n\n public Collection<Variable> getVariables() {\n return variables.values();\n }\n\n public void setVariable(Identifier name, Value value) {\n findVariable(name).setValue(value);\n }\n\n public boolean hasVariable(Identifier name) {\n return variables.containsKey(name.getSource());\n }\n\n private Variable findVariable(Identifier name) {\n final String nameString = name.getSource();\n final Variable variable = variables.get(nameString);\n if (variable == null) {\n throw new UnsupportedOperationException(\"Variable \" + nameString + \" does not exist\");\n }\n return variable;\n }\n\n public static class Variable {\n private final Identifier name;\n private final LiteralType type;\n private Value value;\n\n private Variable(Identifier name, LiteralType type, Value value) {\n this.name = name;\n this.type = type;\n this.value = value;\n }\n\n public Identifier getName() {\n return name;\n }\n\n public LiteralType getType() {\n return type;\n }\n\n public boolean initialized() {\n return value != null;\n }\n\n public Value getValue() {\n if (!initialized()) {\n throw new UnsupportedOperationException(\"Variable \" + name.getSource() + \" has not been initialized\");\n }\n return value;\n }\n\n private void setValue(Value value) {\n this.value = value;\n }\n }\n}", "public class EvaluatorException extends SourceException {\n private static final long serialVersionUID = 1;\n\n public EvaluatorException(Throwable cause, SourceIndexed indexed) {\n this(\"EvaluatorException\", cause, indexed);\n }\n\n public EvaluatorException(String error, Throwable cause, SourceIndexed indexed) {\n super(getMessage(error, cause), cause, null, indexed.getStart(), indexed.getEnd());\n }\n\n public EvaluatorException(String error, SourceIndexed indexed) {\n this(error, indexed.getStart(), indexed.getEnd());\n }\n\n public EvaluatorException(String error, int start, int end) {\n super(error, null, start, end);\n }\n\n private static String getMessage(String error, Throwable cause) {\n if (cause == null) {\n return error;\n }\n String causeMessage = cause.getMessage();\n if (causeMessage != null) {\n causeMessage = causeMessage.trim();\n if (causeMessage.isEmpty()) {\n causeMessage = null;\n }\n }\n error += \" (\" + cause.getClass().getSimpleName();\n if (causeMessage != null) {\n error += \": \" + causeMessage;\n }\n return getMessage(error, cause.getCause()) + \")\";\n }\n}", "public class PrimitiveType implements LiteralType {\n public static final PrimitiveType THE_BOOLEAN;\n public static final PrimitiveType THE_BYTE;\n public static final PrimitiveType THE_SHORT;\n public static final PrimitiveType THE_CHAR;\n public static final PrimitiveType THE_INT;\n public static final PrimitiveType THE_LONG;\n public static final PrimitiveType THE_FLOAT;\n public static final PrimitiveType THE_DOUBLE;\n private static final Map<Class<?>, PrimitiveType> ALL_TYPES = new HashMap<>();\n private static final Map<Class<?>, Set<Class<?>>> PRIMITIVE_CONVERSIONS = new HashMap<>();\n private static final Map<Class<?>, LiteralReferenceType> BOXING_CONVERSIONS = new HashMap<>();\n private static final Map<Class<?>, RangeChecker> NARROW_CHECKERS = new HashMap<>();\n private static final Set<Class<?>> UNARY_WIDENS_INT = new HashSet<>();\n private static final Map<Class<?>, Widener> BINARY_WIDENERS = new HashMap<>();\n private final Class<?> type;\n private final ValueKind kind;\n\n static {\n THE_BOOLEAN = new PrimitiveType(boolean.class, ValueKind.BOOLEAN);\n THE_BYTE = new PrimitiveType(byte.class, ValueKind.BYTE);\n THE_SHORT = new PrimitiveType(short.class, ValueKind.SHORT);\n THE_CHAR = new PrimitiveType(char.class, ValueKind.CHAR);\n THE_INT = new PrimitiveType(int.class, ValueKind.INT);\n THE_LONG = new PrimitiveType(long.class, ValueKind.LONG);\n THE_FLOAT = new PrimitiveType(float.class, ValueKind.FLOAT);\n THE_DOUBLE = new PrimitiveType(double.class, ValueKind.DOUBLE);\n\n ALL_TYPES.put(boolean.class, THE_BOOLEAN);\n ALL_TYPES.put(byte.class, THE_BYTE);\n ALL_TYPES.put(short.class, THE_SHORT);\n ALL_TYPES.put(char.class, THE_CHAR);\n ALL_TYPES.put(int.class, THE_INT);\n ALL_TYPES.put(long.class, THE_LONG);\n ALL_TYPES.put(float.class, THE_FLOAT);\n ALL_TYPES.put(double.class, THE_DOUBLE);\n\n PRIMITIVE_CONVERSIONS.put(boolean.class, new HashSet<Class<?>>(Collections.singletonList(boolean.class)));\n PRIMITIVE_CONVERSIONS.put(byte.class, new HashSet<Class<?>>(Arrays.asList(byte.class, short.class, int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(short.class, new HashSet<Class<?>>(Arrays.asList(short.class, int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(char.class, new HashSet<Class<?>>(Arrays.asList(char.class, int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(int.class, new HashSet<Class<?>>(Arrays.asList(int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(long.class, new HashSet<Class<?>>(Arrays.asList(long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(float.class, new HashSet<Class<?>>(Arrays.asList(float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(double.class, new HashSet<Class<?>>(Collections.singletonList(double.class)));\n\n BOXING_CONVERSIONS.put(boolean.class, LiteralReferenceType.of(Boolean.class));\n BOXING_CONVERSIONS.put(byte.class, LiteralReferenceType.of(Byte.class));\n BOXING_CONVERSIONS.put(short.class, LiteralReferenceType.of(Short.class));\n BOXING_CONVERSIONS.put(char.class, LiteralReferenceType.of(Character.class));\n BOXING_CONVERSIONS.put(int.class, LiteralReferenceType.of(Integer.class));\n BOXING_CONVERSIONS.put(long.class, LiteralReferenceType.of(Long.class));\n BOXING_CONVERSIONS.put(float.class, LiteralReferenceType.of(Float.class));\n BOXING_CONVERSIONS.put(double.class, LiteralReferenceType.of(Double.class));\n\n NARROW_CHECKERS.put(byte.class, new RangeChecker(-128, 0xFF));\n NARROW_CHECKERS.put(short.class, new RangeChecker(-32768, 0xFFFF));\n NARROW_CHECKERS.put(char.class, new RangeChecker(0, 0xFFFF));\n\n Collections.addAll(UNARY_WIDENS_INT, byte.class, short.class, char.class);\n\n final Widener intWidener = new Widener(int.class, byte.class, short.class, char.class);\n BINARY_WIDENERS.put(byte.class, intWidener);\n BINARY_WIDENERS.put(short.class, intWidener);\n BINARY_WIDENERS.put(char.class, intWidener);\n BINARY_WIDENERS.put(int.class, intWidener);\n BINARY_WIDENERS.put(long.class, new Widener(long.class, byte.class, short.class, char.class, int.class));\n BINARY_WIDENERS.put(float.class, new Widener(float.class, byte.class, short.class, char.class, int.class, long.class));\n BINARY_WIDENERS.put(double.class, new Widener(double.class, byte.class, short.class, char.class, int.class, long.class, float.class));\n }\n\n private PrimitiveType(Class<?> type, ValueKind kind) {\n this.type = type;\n this.kind = kind;\n }\n\n @Override\n public Class<?> getTypeClass() {\n return type;\n }\n\n @Override\n public String getName() {\n return type.getCanonicalName();\n }\n\n @Override\n public ValueKind getKind() {\n return kind;\n }\n\n @Override\n public boolean isVoid() {\n return false;\n }\n\n @Override\n public boolean isNull() {\n return false;\n }\n\n @Override\n public boolean isPrimitive() {\n return true;\n }\n\n @Override\n public boolean isNumeric() {\n return isIntegral() || type == float.class || type == double.class;\n }\n\n @Override\n public boolean isIntegral() {\n return type == byte.class || type == short.class || type == char.class || type == int.class || type == long.class;\n }\n\n @Override\n public boolean isBoolean() {\n return type == boolean.class;\n }\n\n @Override\n public boolean isArray() {\n return false;\n }\n\n @Override\n public boolean isReference() {\n return false;\n }\n\n @Override\n public boolean isReifiable() {\n return true;\n }\n\n @Override\n public LiteralReferenceType asArray(int dimensions) {\n return LiteralReferenceType.of(ReflectionUtil.asArrayType(type, dimensions));\n }\n\n @Override\n public Object newArray(int length) {\n return Array.newInstance(type, length);\n }\n\n @Override\n public Object newArray(int[] lengths) {\n return Array.newInstance(type, lengths);\n }\n\n public SingleReferenceType box() {\n return BOXING_CONVERSIONS.get(type);\n }\n\n public boolean canNarrowFrom(int value) {\n final RangeChecker checker = NARROW_CHECKERS.get(type);\n return checker != null && checker.contains(value);\n }\n\n public PrimitiveType unaryWiden() {\n return of(UNARY_WIDENS_INT.contains(type) ? int.class : type);\n }\n\n public PrimitiveType binaryWiden(PrimitiveType with) {\n return of(BINARY_WIDENERS.get(type).widen(with.getTypeClass()));\n }\n\n @Override\n public boolean convertibleTo(Type to) {\n // Primitive types can be converted to certain primitive types\n // If the target type isn't primitive, box the source and try again\n if (to.isPrimitive()) {\n final PrimitiveType target = (PrimitiveType) to;\n return PRIMITIVE_CONVERSIONS.get(type).contains(target.getTypeClass());\n }\n return box().convertibleTo(to);\n }\n\n @Override\n public PrimitiveType capture() {\n return this;\n }\n\n @Override\n public String toString() {\n return getName();\n }\n\n @Override\n public boolean equals(Object other) {\n return this == other || other instanceof PrimitiveType && this.type == ((PrimitiveType) other).getTypeClass();\n }\n\n @Override\n public int hashCode() {\n return type.getName().hashCode();\n }\n\n public static PrimitiveType of(Class<?> type) {\n return ALL_TYPES.get(type);\n }\n\n private static class RangeChecker {\n private final int minValue;\n private final int invertedMask;\n\n private RangeChecker(int minValue, int mask) {\n this.minValue = minValue;\n invertedMask = ~mask;\n }\n\n private boolean contains(int value) {\n return (value - minValue & invertedMask) == 0;\n }\n }\n\n private static class Widener {\n private final Class<?> wider;\n private final Set<Class<?>> widens = new HashSet<>();\n\n private Widener(Class<?> wider, Class<?>... widens) {\n this.wider = wider;\n Collections.addAll(this.widens, widens);\n }\n\n private Class<?> widen(Class<?> type) {\n return widens.contains(type) ? wider : type;\n }\n }\n}", "public interface Type {\n String getName();\n\n ValueKind getKind();\n\n boolean isVoid();\n\n boolean isNull();\n\n boolean isPrimitive();\n\n boolean isNumeric();\n\n boolean isIntegral();\n\n boolean isBoolean();\n\n boolean isArray();\n\n boolean isReference();\n\n boolean isReifiable();\n\n boolean convertibleTo(Type to);\n\n Type capture();\n\n @Override\n String toString();\n\n @Override\n boolean equals(Object other);\n\n @Override\n int hashCode();\n}", "public interface Value {\n boolean asBoolean();\n\n byte asByte();\n\n short asShort();\n\n char asChar();\n\n int asInt();\n\n long asLong();\n\n float asFloat();\n\n double asDouble();\n\n Object asObject();\n\n String asString();\n\n <T> T as();\n\n ValueKind getKind();\n\n boolean isPrimitive();\n\n Class<?> getTypeClass();\n\n String toString();\n}", "public enum ValueKind {\n BOOLEAN(Boolean.class) {\n @Override\n public BooleanValue defaultValue() {\n return BooleanValue.defaultValue();\n }\n\n @Override\n public BooleanValue wrap(Object object) {\n if (object instanceof Boolean) {\n return BooleanValue.of((Boolean) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a boolean\");\n }\n\n @Override\n public BooleanValue convert(Value value) {\n return BooleanValue.of(value.asBoolean());\n }\n },\n BYTE(Byte.class) {\n @Override\n public ByteValue defaultValue() {\n return ByteValue.defaultValue();\n }\n\n @Override\n public ByteValue wrap(Object object) {\n if (object instanceof Byte) {\n return ByteValue.of((Byte) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a byte\");\n }\n\n @Override\n public ByteValue convert(Value value) {\n return ByteValue.of(value.asByte());\n }\n },\n SHORT(Short.class) {\n @Override\n public ShortValue defaultValue() {\n return ShortValue.defaultValue();\n }\n\n @Override\n public ShortValue wrap(Object object) {\n if (object instanceof Short) {\n return ShortValue.of((Short) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a short\");\n }\n\n @Override\n public ShortValue convert(Value value) {\n return ShortValue.of(value.asShort());\n }\n },\n CHAR(Character.class) {\n @Override\n public CharValue defaultValue() {\n return CharValue.defaultValue();\n }\n\n @Override\n public CharValue wrap(Object object) {\n if (object instanceof Character) {\n return CharValue.of((Character) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a char\");\n }\n\n @Override\n public CharValue convert(Value value) {\n return CharValue.of(value.asChar());\n }\n },\n INT(Integer.class) {\n @Override\n public IntValue defaultValue() {\n return IntValue.defaultValue();\n }\n\n @Override\n public IntValue wrap(Object object) {\n if (object instanceof Integer) {\n return IntValue.of((Integer) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to an int\");\n }\n\n @Override\n public IntValue convert(Value value) {\n return IntValue.of(value.asInt());\n }\n },\n LONG(Long.class) {\n @Override\n public LongValue defaultValue() {\n return LongValue.defaultValue();\n }\n\n @Override\n public LongValue wrap(Object object) {\n if (object instanceof Long) {\n return LongValue.of((Long) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a long\");\n }\n\n @Override\n public LongValue convert(Value value) {\n return LongValue.of(value.asLong());\n }\n },\n FLOAT(Float.class) {\n @Override\n public FloatValue defaultValue() {\n return FloatValue.defaultValue();\n }\n\n @Override\n public FloatValue wrap(Object object) {\n if (object instanceof Float) {\n return FloatValue.of((Float) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a float\");\n }\n\n @Override\n public FloatValue convert(Value value) {\n return FloatValue.of(value.asFloat());\n }\n },\n DOUBLE(Double.class) {\n @Override\n public DoubleValue defaultValue() {\n return DoubleValue.defaultValue();\n }\n\n @Override\n public DoubleValue wrap(Object object) {\n if (object instanceof Double) {\n return DoubleValue.of((Double) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a double\");\n }\n\n @Override\n public DoubleValue convert(Value value) {\n return DoubleValue.of(value.asDouble());\n }\n },\n VOID(Void.class) {\n @Override\n public Value defaultValue() {\n return VoidValue.defaultValue();\n }\n\n @Override\n public Value wrap(Object object) {\n if (object instanceof Void) {\n return VoidValue.THE_VOID;\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to void\");\n }\n\n @Override\n public Value convert(Value value) {\n throw new UnsupportedOperationException(\"Cannot convert anything to void\");\n }\n },\n OBJECT(null) {\n @Override\n public ObjectValue defaultValue() {\n return ObjectValue.defaultValue();\n }\n\n @Override\n public ObjectValue wrap(Object object) {\n return ObjectValue.of(object);\n }\n\n @Override\n public ObjectValue convert(Value value) {\n return ObjectValue.of(value.asObject());\n }\n };\n private static final Map<Class<?>, ValueKind> BOX_TO_KIND = new HashMap<>();\n private final Class<?> boxingClass;\n\n static {\n for (ValueKind kind : values()) {\n BOX_TO_KIND.put(kind.getBoxingClass(), kind);\n }\n }\n\n ValueKind(Class<?> boxingClass) {\n this.boxingClass = boxingClass;\n }\n\n public abstract Value defaultValue();\n\n public abstract Value wrap(Object object);\n\n public abstract Value convert(Value value);\n\n public Class<?> getBoxingClass() {\n return boxingClass;\n }\n\n public static Value unbox(Object box) {\n final ValueKind kind = BOX_TO_KIND.get(box.getClass());\n if (kind == null) {\n return null;\n }\n if (kind == OBJECT) {\n throw new UnsupportedOperationException(\"Not a box type: \" + box.getClass().getSimpleName());\n }\n return kind.wrap(box);\n }\n}", "public class Symbol extends Token {\n private static final Map<String, Symbol> SYMBOLS = new HashMap<>();\n private static final Symbol[] CHAR_SYMBOLS = new Symbol[256];\n private final Symbol compoundAssignOperator;\n\n static {\n // punctuation\n add(TokenID.SYMBOL_PERIOD, \".\");\n add(TokenID.SYMBOL_COMMA, \",\");\n add(TokenID.SYMBOL_COLON, \":\");\n add(TokenID.SYMBOL_SEMICOLON, \";\");\n // math\n add(TokenID.SYMBOL_PLUS, \"+\");\n add(TokenID.SYMBOL_MINUS, \"-\");\n add(TokenID.SYMBOL_MULTIPLY, \"*\");\n add(TokenID.SYMBOL_DIVIDE, \"/\");\n add(TokenID.SYMBOL_MODULO, \"%\");\n add(TokenID.SYMBOL_INCREMENT, \"++\", \"+\");\n add(TokenID.SYMBOL_DECREMENT, \"--\", \"-\");\n // bitwise\n add(TokenID.SYMBOL_BITWISE_AND, \"&\");\n add(TokenID.SYMBOL_BITWISE_OR, \"|\");\n add(TokenID.SYMBOL_BITWISE_NOT, \"~\");\n add(TokenID.SYMBOL_BITWISE_XOR, \"^\");\n // shift\n add(TokenID.SYMBOL_LOGICAL_LEFT_SHIFT, \"<<\");\n add(TokenID.SYMBOL_ARITHMETIC_RIGHT_SHIFT, \">>\");\n add(TokenID.SYMBOL_LOGICAL_RIGHT_SHIFT, \">>>\");\n // boolean\n add(TokenID.SYMBOL_BOOLEAN_NOT, \"!\");\n add(TokenID.SYMBOL_BOOLEAN_AND, \"&&\");\n add(TokenID.SYMBOL_BOOLEAN_OR, \"||\");\n // comparison\n add(TokenID.SYMBOL_LESSER, \"<\");\n add(TokenID.SYMBOL_GREATER, \">\");\n add(TokenID.SYMBOL_GREATER_OR_EQUAL, \">=\");\n add(TokenID.SYMBOL_LESSER_OR_EQUAL, \"<=\");\n add(TokenID.SYMBOL_EQUAL, \"==\");\n add(TokenID.SYMBOL_NOT_EQUAL, \"!=\");\n // assignment\n add(TokenID.SYMBOL_ASSIGN, \"=\");\n add(TokenID.SYMBOL_ADD_ASSIGN, \"+=\", \"+\");\n add(TokenID.SYMBOL_SUBTRACT_ASSIGN, \"-=\", \"-\");\n add(TokenID.SYMBOL_MULTIPLY_ASSIGN, \"*=\", \"*\");\n add(TokenID.SYMBOL_DIVIDE_ASSIGN, \"/=\", \"/\");\n add(TokenID.SYMBOL_REMAINDER_ASSIGN, \"%=\", \"%\");\n add(TokenID.SYMBOL_BITWISE_AND_ASSIGN, \"&=\", \"&\");\n add(TokenID.SYMBOL_BITWISE_OR_ASSIGN, \"|=\", \"|\");\n add(TokenID.SYMBOL_BITWISE_XOR_ASSIGN, \"^=\", \"^\");\n add(TokenID.SYMBOL_LOGICAL_LEFT_SHIFT_ASSIGN, \"<<=\", \"<<\");\n add(TokenID.SYMBOL_ARITHMETIC_RIGHT_SHIFT_ASSIGN, \">>=\", \">>\");\n add(TokenID.SYMBOL_LOGICAL_RIGHT_SHIFT_ASSIGN, \">>>=\", \">>>\");\n // enclosing\n add(TokenID.SYMBOL_OPEN_PARENTHESIS, \"(\");\n add(TokenID.SYMBOL_CLOSE_PARENTHESIS, \")\");\n add(TokenID.SYMBOL_OPEN_BRACKET, \"[\");\n add(TokenID.SYMBOL_CLOSE_BRACKET, \"]\");\n add(TokenID.SYMBOL_OPEN_BRACE, \"{\");\n add(TokenID.SYMBOL_CLOSE_BRACE, \"}\");\n // comment\n add(TokenID.SYMBOL_DOUBLE_SLASH, \"//\");\n add(TokenID.SYMBOL_SLASH_STAR, \"/*\");\n add(TokenID.SYMBOL_STAR_SLASH, \"*/\");\n // other\n add(TokenID.SYMBOL_QUESTION_MARK, \"?\");\n add(TokenID.SYMBOL_DOUBLE_PERIOD, \"..\");\n add(TokenID.SYMBOL_TRIPLE_PERIOD, \"...\");\n add(TokenID.SYMBOL_DOUBLE_COLON, \"::\");\n add(TokenID.SYMBOL_ARROW, \"->\");\n add(TokenID.SYMBOL_AT, \"@\");\n }\n\n private Symbol(Symbol token, int index) {\n this(token.getID(), token.getSource(), index, token.getCompoundAssignOperator());\n }\n\n private Symbol(TokenID id, String source, int index, Symbol compoundAssignOperator) {\n super(id, source, index);\n this.compoundAssignOperator = compoundAssignOperator;\n }\n\n public Symbol getCompoundAssignOperator() {\n return compoundAssignOperator;\n }\n\n public static boolean is(char source) {\n return CHAR_SYMBOLS[source] != null;\n }\n\n public static boolean is(String source) {\n if (source.length() == 1) {\n return is(source.charAt(0));\n }\n return SYMBOLS.containsKey(source);\n }\n\n public static Symbol from(char source, int index) {\n final Symbol symbol = CHAR_SYMBOLS[source];\n return symbol == null ? null : new Symbol(symbol, index);\n }\n\n public static Symbol from(String source, int index) {\n if (source.length() == 1) {\n return from(source.charAt(0), index);\n }\n final Symbol symbol = SYMBOLS.get(source);\n return symbol == null ? null : new Symbol(symbol, index);\n }\n\n public static Collection<Symbol> all() {\n return Collections.unmodifiableCollection(SYMBOLS.values());\n }\n\n private static void add(TokenID id, String source) {\n add(id, source, null);\n }\n\n private static void add(TokenID id, String source, String compoundAssignOperator) {\n final Symbol symbol = new Symbol(id, source, 0, SYMBOLS.get(compoundAssignOperator));\n SYMBOLS.put(source, symbol);\n if (source.length() == 1) {\n CHAR_SYMBOLS[source.charAt(0)] = symbol;\n }\n }\n}", "public enum TokenID {\n IDENTIFIER(TokenGroup.IDENTIFIER),\n KEYWORD_ASSERT(TokenGroup.UNSPECIFIED),\n KEYWORD_IF(TokenGroup.UNSPECIFIED),\n KEYWORD_ELSE(TokenGroup.UNSPECIFIED),\n KEYWORD_WHILE(TokenGroup.UNSPECIFIED),\n KEYWORD_DO(TokenGroup.UNSPECIFIED),\n KEYWORD_FOR(TokenGroup.UNSPECIFIED),\n KEYWORD_BREAK(TokenGroup.UNSPECIFIED),\n KEYWORD_CONTINUE(TokenGroup.UNSPECIFIED),\n KEYWORD_SWITCH(TokenGroup.UNSPECIFIED),\n KEYWORD_CASE(TokenGroup.UNSPECIFIED),\n KEYWORD_DEFAULT(TokenGroup.UNSPECIFIED),\n KEYWORD_RETURN(TokenGroup.UNSPECIFIED),\n KEYWORD_THROW(TokenGroup.UNSPECIFIED),\n KEYWORD_TRY(TokenGroup.UNSPECIFIED),\n KEYWORD_CATCH(TokenGroup.UNSPECIFIED),\n KEYWORD_FINALLY(TokenGroup.UNSPECIFIED),\n KEYWORD_VOID(TokenGroup.UNSPECIFIED),\n KEYWORD_BOOLEAN(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_BYTE(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_SHORT(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_CHAR(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_INT(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_LONG(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_FLOAT(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_DOUBLE(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_CLASS(TokenGroup.CLASS_TYPE),\n KEYWORD_INTERFACE(TokenGroup.CLASS_TYPE),\n KEYWORD_ENUM(TokenGroup.CLASS_TYPE),\n KEYWORD_EXTENDS(TokenGroup.UNSPECIFIED),\n KEYWORD_IMPLEMENTS(TokenGroup.UNSPECIFIED),\n KEYWORD_SUPER(TokenGroup.SELF_REFERENCE),\n KEYWORD_THIS(TokenGroup.SELF_REFERENCE),\n KEYWORD_PACKAGE(TokenGroup.UNSPECIFIED),\n KEYWORD_IMPORT(TokenGroup.UNSPECIFIED),\n KEYWORD_PUBLIC(TokenGroup.ACCESS_MODIFIER),\n KEYWORD_PROTECTED(TokenGroup.ACCESS_MODIFIER),\n KEYWORD_PRIVATE(TokenGroup.ACCESS_MODIFIER),\n KEYWORD_THROWS(TokenGroup.UNSPECIFIED),\n KEYWORD_ABSTRACT(TokenGroup.OTHER_MODIFIER),\n KEYWORD_STRICTFP(TokenGroup.OTHER_MODIFIER),\n KEYWORD_TRANSIENT(TokenGroup.OTHER_MODIFIER),\n KEYWORD_VOLATILE(TokenGroup.OTHER_MODIFIER),\n KEYWORD_FINAL(TokenGroup.OTHER_MODIFIER),\n KEYWORD_STATIC(TokenGroup.OTHER_MODIFIER),\n KEYWORD_SYNCHRONIZED(TokenGroup.OTHER_MODIFIER),\n KEYWORD_NATIVE(TokenGroup.OTHER_MODIFIER),\n KEYWORD_NEW(TokenGroup.UNSPECIFIED),\n KEYWORD_INSTANCEOF(TokenGroup.BINARY_OPERATOR),\n KEYWORD_GOTO(TokenGroup.UNUSED),\n KEYWORD_CONST(TokenGroup.UNUSED),\n SYMBOL_PERIOD(TokenGroup.CALL_OPERATOR),\n SYMBOL_COMMA(TokenGroup.UNSPECIFIED),\n SYMBOL_COLON(TokenGroup.UNSPECIFIED),\n SYMBOL_SEMICOLON(TokenGroup.UNSPECIFIED),\n SYMBOL_PLUS(TokenGroup.ADD_OPERATOR),\n SYMBOL_MINUS(TokenGroup.ADD_OPERATOR),\n SYMBOL_MULTIPLY(TokenGroup.MULTIPLY_OPERATOR),\n SYMBOL_DIVIDE(TokenGroup.MULTIPLY_OPERATOR),\n SYMBOL_MODULO(TokenGroup.MULTIPLY_OPERATOR),\n SYMBOL_INCREMENT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_DECREMENT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_BITWISE_AND(TokenGroup.BINARY_OPERATOR),\n SYMBOL_BITWISE_OR(TokenGroup.BINARY_OPERATOR),\n SYMBOL_BITWISE_NOT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_BITWISE_XOR(TokenGroup.BINARY_OPERATOR),\n SYMBOL_LOGICAL_LEFT_SHIFT(TokenGroup.SHIFT_OPERATOR),\n SYMBOL_ARITHMETIC_RIGHT_SHIFT(TokenGroup.SHIFT_OPERATOR),\n SYMBOL_LOGICAL_RIGHT_SHIFT(TokenGroup.SHIFT_OPERATOR),\n SYMBOL_BOOLEAN_NOT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_BOOLEAN_AND(TokenGroup.BINARY_OPERATOR),\n SYMBOL_BOOLEAN_OR(TokenGroup.BINARY_OPERATOR),\n SYMBOL_LESSER(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_GREATER(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_GREATER_OR_EQUAL(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_LESSER_OR_EQUAL(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_EQUAL(TokenGroup.EQUAL_OPERATOR),\n SYMBOL_NOT_EQUAL(TokenGroup.EQUAL_OPERATOR),\n SYMBOL_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_ADD_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_SUBTRACT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_MULTIPLY_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_DIVIDE_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_REMAINDER_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_BITWISE_AND_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_BITWISE_OR_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_BITWISE_XOR_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_LOGICAL_LEFT_SHIFT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_ARITHMETIC_RIGHT_SHIFT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_LOGICAL_RIGHT_SHIFT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_OPEN_PARENTHESIS(TokenGroup.UNSPECIFIED),\n SYMBOL_CLOSE_PARENTHESIS(TokenGroup.UNSPECIFIED),\n SYMBOL_OPEN_BRACKET(TokenGroup.UNSPECIFIED),\n SYMBOL_CLOSE_BRACKET(TokenGroup.UNSPECIFIED),\n SYMBOL_OPEN_BRACE(TokenGroup.UNSPECIFIED),\n SYMBOL_CLOSE_BRACE(TokenGroup.UNSPECIFIED),\n SYMBOL_DOUBLE_SLASH(TokenGroup.COMMENT_DELIMITER),\n SYMBOL_SLASH_STAR(TokenGroup.COMMENT_DELIMITER),\n SYMBOL_STAR_SLASH(TokenGroup.COMMENT_DELIMITER),\n SYMBOL_QUESTION_MARK(TokenGroup.UNSPECIFIED),\n SYMBOL_DOUBLE_PERIOD(TokenGroup.UNUSED),\n SYMBOL_TRIPLE_PERIOD(TokenGroup.UNSPECIFIED),\n SYMBOL_DOUBLE_COLON(TokenGroup.UNSPECIFIED),\n SYMBOL_ARROW(TokenGroup.UNSPECIFIED),\n SYMBOL_AT(TokenGroup.UNSPECIFIED),\n LITERAL_TRUE(TokenGroup.LITERAL),\n LITERAL_FALSE(TokenGroup.LITERAL),\n LITERAL_CHARACTER(TokenGroup.LITERAL),\n LITERAL_NULL(TokenGroup.LITERAL),\n LITERAL_STRING(TokenGroup.LITERAL),\n LITERAL_DOUBLE(TokenGroup.LITERAL),\n LITERAL_FLOAT(TokenGroup.LITERAL),\n LITERAL_INT(TokenGroup.LITERAL),\n LITERAL_LONG(TokenGroup.LITERAL);\n private final TokenGroup group;\n\n TokenID(TokenGroup group) {\n this.group = group;\n }\n\n public TokenGroup getGroup() {\n return group;\n }\n}", "public final class StringUtil {\n private static final int[] DIGIT_VALUES = new int[256];\n\n static {\n for (int i = 0; i < DIGIT_VALUES.length; i++) {\n DIGIT_VALUES[i] = -1;\n }\n for (int c = '0', i = 0; c <= '9'; c++, i++) {\n DIGIT_VALUES[c] = i;\n }\n for (int c = 'a', i = 10; c <= 'z'; c++, i++) {\n DIGIT_VALUES[c] = i;\n }\n for (int c = 'A', i = 10; c <= 'Z'; c++, i++) {\n DIGIT_VALUES[c] = i;\n }\n }\n\n private StringUtil() {\n }\n\n public static boolean isWhitespace(char c) {\n return c == ' ' || c == '\\t' || c == '\\f' || isLineTerminator(c);\n }\n\n public static boolean isLineTerminator(char c) {\n return c == '\\n' || c == '\\r';\n }\n\n public static String toString(Object[] elements, String separator) {\n return toString(Arrays.asList(elements), separator);\n }\n\n public static String toString(Collection<?> elements, String separator) {\n final int size = elements.size() - 1;\n if (size >= 0) {\n final StringBuilder builder = new StringBuilder();\n final Iterator<?> iterator = elements.iterator();\n for (int i = 0; i < size; i++) {\n builder.append(iterator.next());\n builder.append(separator);\n }\n return builder.append(iterator.next()).toString();\n }\n return \"\";\n }\n\n public static String repeat(String string, int number) {\n final StringBuilder builder = new StringBuilder();\n repeat(string, number, builder);\n return builder.toString();\n }\n\n public static void repeat(String string, int number, StringBuilder to) {\n for (int i = 0; i < number; i++) {\n to.append(string);\n }\n }\n\n public static String removeAll(String string, char remove) {\n final int length = string.length();\n final char[] chars = new char[length];\n int count = 0;\n for (int i = 0; i < length; i++) {\n final char c = string.charAt(i);\n if (c != remove) {\n chars[count++] = c;\n }\n }\n return String.valueOf(chars, 0, count);\n }\n\n public static int findRadix(String source) {\n if (source.length() < 2) {\n return 10;\n }\n if (source.charAt(0) == '0') {\n switch (source.charAt(1)) {\n case 'b':\n case 'B':\n return 2;\n case 'x':\n case 'X':\n return 16;\n default:\n return 8;\n }\n }\n return 10;\n }\n\n public static String removeRadixIdentifier(String source, int radix) {\n switch (radix) {\n case 2:\n case 16:\n return source.substring(2);\n case 8:\n return source.substring(1);\n case 10:\n return source;\n default:\n throw new IllegalArgumentException(\"No known radix identifier for \" + radix);\n }\n }\n\n public static String reduceSign(String source) {\n boolean sign = false;\n int i = 0;\n for (; i < source.length(); i++) {\n final char c = source.charAt(i);\n if (c == '+') {\n continue;\n }\n if (c == '-') {\n sign ^= true;\n continue;\n }\n if (!isWhitespace(c)) {\n break;\n }\n }\n return (sign ? '-' : \"\") + source.substring(i);\n }\n\n public static int getDigitValue(char digit, int radix) {\n if (digit >= 256) {\n return -1;\n }\n final int value = DIGIT_VALUES[digit];\n return value >= radix ? -1 : value;\n }\n\n public static boolean equalsNoCaseASCII(char a, char b) {\n return (a & ~32) == (b & ~32);\n }\n\n public static char decodeJavaEscape(char escape) {\n switch (escape) {\n case 'b':\n return '\\b';\n case 't':\n return '\\t';\n case 'n':\n return '\\n';\n case 'f':\n return '\\f';\n case 'r':\n return '\\r';\n case '\"':\n return '\\\"';\n case '\\'':\n return '\\'';\n case '\\\\':\n return '\\\\';\n case '0':\n return '\\0';\n case '1':\n return '\\1';\n case '2':\n return '\\2';\n case '3':\n return '\\3';\n case '4':\n return '\\4';\n case '5':\n return '\\6';\n case '6':\n return '\\6';\n case '7':\n return '\\7';\n default:\n throw new IllegalArgumentException(\"'\" + escape + \"' is neither b, t, n, f, r, \\\", ', \\\\, 0, 1, 2, 3, 4, 5, 6 or 7\");\n }\n }\n\n public static char decodeUnicodeEscape(String escape) {\n // format: XXXX where X is a hexadecimal digit\n if (escape.length() == 4) {\n int digit = getDigitValue(escape.charAt(3), 16);\n if (digit >= 0) {\n int value = digit;\n digit = getDigitValue(escape.charAt(2), 16);\n if (digit >= 0) {\n value += digit << 4;\n digit = getDigitValue(escape.charAt(1), 16);\n if (digit >= 0) {\n value += digit << 8;\n digit = getDigitValue(escape.charAt(0), 16);\n if (digit >= 0) {\n value += digit << 12;\n return (char) value;\n }\n }\n }\n }\n }\n throw new IllegalArgumentException(\"Expected 4 hexadecimal digits, got: \" + escape);\n }\n\n public static String escapeCharacter(char offender) {\n final String string;\n if (Character.isWhitespace(offender)) {\n string = Character.getName(offender);\n } else {\n string = String.valueOf(offender);\n }\n return '\\'' + string + '\\'';\n }\n}" ]
import ca.sapon.jici.lexer.TokenID; import ca.sapon.jici.util.StringUtil; import ca.sapon.jici.evaluator.Environment; import ca.sapon.jici.evaluator.EvaluatorException; import ca.sapon.jici.evaluator.type.PrimitiveType; import ca.sapon.jici.evaluator.type.Type; import ca.sapon.jici.evaluator.value.Value; import ca.sapon.jici.evaluator.value.ValueKind; import ca.sapon.jici.lexer.Symbol;
/* * This file is part of JICI, licensed under the MIT License (MIT). * * Copyright (c) 2015-2016 Aleksi Sapon <http://sapon.ca/jici/> * * 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 ca.sapon.jici.lexer.literal.number; public class LongLiteral extends NumberLiteral { private long value = 0; private boolean evaluated = false; public LongLiteral(String source, int index) { super(TokenID.LITERAL_LONG, source, index); } private LongLiteral(String source, int start, int end) { super(TokenID.LITERAL_LONG, source, start, end); } private void evaluate() { if (!evaluated) { String source = StringUtil.reduceSign(getSource()); final int lastIndex = source.length() - 1; if (StringUtil.equalsNoCaseASCII(source.charAt(lastIndex), 'l')) { source = source.substring(0, lastIndex); } final int radix = StringUtil.findRadix(source); try { source = StringUtil.removeRadixIdentifier(source, radix); value = Long.parseLong(source, radix); } catch (Exception exception) {
throw new EvaluatorException(exception.getMessage(), this);
1
lumag/JBookReader
src/org/jbookreader/book/parser/FB2Parser.java
[ "public interface IBinaryData {\n\n\t/**\n\t * Returns the content-type of the blob.\n\t * @return the content-type.\n\t */\n\tString getContentType();\n\n\t/**\n\t * Sets the content-type of the blob.\n\t * @param contentType new content-type\n\t */\n\tvoid setContentType(String contentType);\n\t\n\t/**\n\t * Returns a character sequence iterating over base64-encoded\n\t * representation of the binary data.\n\t * @return a character sequence iterating over base64-encoded\n\t * representation of the binary data.\n\t */\n\tCharSequence getBase64Encoded();\n\n\t/**\n\t * Sets the contents of the blob by providing base64-encoding\n\t * representation of data.\n\t * @param base64Encoded the base64-encoded representation of data\n\t */\n\tvoid setBase64Encoded(char[] base64Encoded);\n\n\t/**\n\t * Sets the contents by providing a byte array and a length.\n\t * @param contents the new contents array.\n\t * @param length the length of contents.\n\t */\n\tvoid setContents(byte[] contents, int length);\n\n\t/**\n\t * Returns the contents array of the data.\n\t * Note, that data can fill not the whole array, but the part of it.\n\t * @return the contents array.\n\t * @see #getContentsLength()\n\t */\n\tbyte[] getContentsArray();\n\n\t/**\n\t * Returns the contents length\n\t * @return the length of the contents in the contents array.\n\t */\n\tint getContentsLength();\n\n}", "public interface IBook {\n\n\t/**\n\t * Creates new body node with give tag and node names.\n\t * @param tagName the tag name\n\t * @param name the name of new body or null if it's main node.\n\t * @return new body node.\n\t */\n\tIContainerNode newBody(String tagName, String name);\n\n\t/**\n\t * Returns the main (the first) body of the book.\n\t * @return the main body of the book\n\t */\n\tIContainerNode getMainBody();\n\n\t/**\n\t * Returns a collection of book bodies.\n\t * @return a collection of book bodies.\n\t */\n\tCollection<IContainerNode> getBodies();\n\n\t/**\n\t * Allocates new binary data.\n\t * @param id the id of given data\n\t * @param contentType the content type of the data.\n\t * @return new binary blob object.\n\t */\n\tIBinaryData newBinaryData(String id, String contentType);\n\n\t/**\n\t * Returns the binary blob associated with specified <code>id</code>.\n\t * If no corresponding blob is found, returns <code>null</code>.\n\t * @param id the id of the blob\n\t * @return the binary blob associated with specified id.\n\t */\n\tIBinaryData getBinaryData(String id);\n\n\t/**\n\t * Returns an id-&gt;binary data mapping.\n\t * @return an id-&gt;binary data mapping.\n\t */\n\tMap<String, ? extends IBinaryData> getBinaryMap();\n\n\t/**\n\t * Returns the system stylesheet for specified book.\n\t * @return the system stylesheet for specified book.\n\t */\n\tIStyleSheet getSystemStyleSheet();\n\t\n\t/**\n\t * Don't use this for now.\n\t * @param stylesheet\n\t */\n\tvoid setSystemStyleSheet(IStyleSheet stylesheet);\n\t\n\t/**\n\t * Returns the node with specified ID.\n\t * @param id the id of node\n\t * @return the node with specified ID.\n\t */\n\tINode getNodeByID(String id);\n\t\n\t/**\n\t * Returns the node corresponding to the string reference.\n\t * @see INode#getNodeReference()\n\t * @param reference the strign reference of the node\n\t * @return the node corresponding to the <code>reference</code>.\n\t */\n\tINode getNodeByReference(String reference);\n}", "public interface IContainerNode extends INode {\n\n\t/**\n\t * Returns a collection of child (contained in this one) nodes.\n\t * @return a collection of child nodes.\n\t */\n\tList<INode> getChildNodes();\n\n\t/**\n\t * This creates new child text node with specified text.\n\t * @param text the text of created node\n\t * @return new text node.\n\t */\n\tINode newTextNode(String text);\n\t/**\n\t * Creates new child container node.\n\t * @param tagName the tag name of new node\n\t * @return new container node.\n\t */\n\tIContainerNode newContainerNode(String tagName);\n\n\t/**\n\t * Returns the title of the section.\n\t * @return the title of the section.\n\t */\n\tIContainerNode getTitle();\n\t/**\n\t * Allocates the title of the section.\n\t * @param tagName the tag name of the title node\n\t * @return newly created container node.\n\t */\n\tIContainerNode newTitle(String tagName);\n\t\n\t/**\n\t * Allocates new Image node.\n\t * @param tagName the tag name of the image node\n\t * @param href the url of the image \n\t * @return newly created image node.\n\t */\n\tIImageNode newImage(String tagName, String href);\n\n}", "public interface IImageNode extends INode {\n\n\t/**\n\t * Returns the location of the image. Probably you should only use internal locations ('#id') for now.\n\t * @return the location of the image.\n\t */\n\tString getHyperRef();\n\n\t/**\n\t * Sets the alternative text for the image.\n\t * @param text new alternative text\n\t */\n\tvoid setText(String text);\n\n\t/**\n\t * Returns the title of the image or null if there is no title.\n\t * @return the title of the image\n\t */\n\tString getTitle();\n\n\t/**\n\t * Sets the title of the image.\n\t * @param title new title\n\t */\n\tvoid setTitle(String title);\n\n}", "public interface INode {\n\n\t/**\n\t * Returns the text contained in the node.\n\t * @return the text contained in the node.\n\t */\n\tString getText();\n\n\t/**\n\t * Returns the tag-name of the node.\n\t * @return the tag-name of the node.\n\t */\n\tString getTagName();\n\t\n\t/**\n\t * Returns the class of the node.\n\t * @return the class of the node.\n\t */\n\tString getNodeClass();\n\t\n\t/**\n\t * Sets the class of the node.\n\t * @param nodeClass the class of the node\n\t */\n\tvoid setNodeClass(String nodeClass);\n\t\n\t/**\n\t * Returns the parent node (the node, containing this one).\n\t * @return the parent node.\n\t */\n\tIContainerNode getParentNode();\n\t\n\t/**\n\t * Returns the ID of this node or null if this node has no ID.\n\t * @return the ID of this node.\n\t */\n\tString getID();\n\t\n\t/**\n\t * Sets the ID of this node\n\t * @param id new ID\n\t */\n\tvoid setID(String id);\n\t\n\t/**\n\t * Returns a book containing this node.\n\t * @return a book containing this node.\n\t */\n\tIBook getBook();\n\t\n\tString getNodeReference();\n}", "public class Book implements IBook {\n\t/**\n\t * The system stylesheet of the book.\n\t */\n\tprivate IStyleSheet mySystemStyleSheet;\n\t/**\n\t * The list with book bodies.\n\t */\n\tprivate Map<String, IContainerNode> myBodies = new LinkedHashMap<String, IContainerNode>();\n\t/**\n\t * Maps id -> node.\n\t */\n\tprivate Map<String, INode> myIDmap = new LinkedHashMap<String, INode>();\n\t/**\n\t * The list with binary blobs, encapsulated in the book.\n\t */\n\tprivate Map<String, BinaryData> myBinaries = new LinkedHashMap<String, BinaryData>();\n\t\n\tpublic IContainerNode newBody(String tagName, String name) {\n\t\tContainerNode body = new ContainerNode();\n\t\tbody.setTagName(tagName);\n\t\tbody.setBook(this);\n\t\tthis.myBodies.put(name, body);\n\t\treturn body;\n\t}\n\n\tpublic IContainerNode getMainBody() {\n\t\tIContainerNode node = this.myBodies.get(null);\n\t\tif (node == null) {\n\t\t\tthrow new IllegalStateException(\"No main body provided\");\n\t\t}\n\t\treturn node;\n\t}\n\t\n\tpublic Collection<IContainerNode> getBodies() {\n\t\treturn Collections.unmodifiableCollection(this.myBodies.values());\n\t}\n\t\n\tpublic IBinaryData newBinaryData(String id, String contentType) {\n\t\tBinaryData bdata = new BinaryData();\n\t\tbdata.setContentType(contentType);\n\t\tthis.myBinaries.put(id, bdata);\n\t\treturn bdata;\n\t}\n\t\n\tpublic IBinaryData getBinaryData(String id) {\n\t\treturn this.myBinaries.get(id);\n\t}\n\t\n\tpublic Map<String, ? extends IBinaryData> getBinaryMap() {\n\t\treturn Collections.unmodifiableMap(this.myBinaries);\n\t}\n\n\tpublic IStyleSheet getSystemStyleSheet() {\n\t\treturn this.mySystemStyleSheet;\n\t}\n\n\tpublic void setSystemStyleSheet(IStyleSheet systemStyleSheet) {\n\t\tthis.mySystemStyleSheet = systemStyleSheet;\n\t}\n\n\tpublic INode getNodeByID(String id) {\n\t\treturn this.myIDmap.get(id);\n\t}\n\t\n\t/**\n\t * Adds a node to ID mapping. The node should already have correct ID.\n\t * @param node the node to put into the mapping.\n\t */\n\tvoid mapIdNode(INode node) {\n\t\tString id = node.getID();\n\t\tif (id != null) {\n\t\t\tthis.myIDmap.put(id, node);\n\t\t}\n\t}\n\n\tpublic INode getNodeByReference(String reference) {\n\t\tString[] tokens = reference.split(\";\");\n\t\tINode node = null;\n\t\tfor (String token: tokens) {\n\t\t\t// TODO: id handling\n\t\t\tint index = Integer.parseInt(token);\n\t\t\t// FIXME: find correct body!\n\t\t\tif (node == null) {\n\t\t\t\tnode = getMainBody();\n\t\t\t} else if (node instanceof IContainerNode){\n\t\t\t\tList<INode> children = ((IContainerNode)node).getChildNodes();\n\t\t\t\tif (index < 0 || index >= children.size()) {\n\t\t\t\t\tSystem.err.println(\"Bad node reference: \" + reference);\n\t\t\t\t\treturn node;\n\t\t\t\t}\n\t\t\t\tnode = children.get(index);\n\t\t\t} else {\n\t\t\t\tSystem.err.println(\"Bad node reference: \" + reference);\n\t\t\t\treturn node;\n\t\t\t}\n\t\t}\n\t\treturn node;\n\t}\n\n}", "public interface IStyleSheet {\n\t/**\n\t * Returns new style stack.\n\t * @return new style stack.\n\t */\n\tIStyleStack newStyleStateStack();\n}", "public class FB2StyleSheet implements IStyleSheet {\n\t\n\t/**\n\t * This mapping holds tagName -&gt; display type information.\n\t */\n\tprivate static Map<String, EDisplayType> ourDisplayTypes = new HashMap<String,EDisplayType>();\n\t\n\t/**\n\t * These are <code>{display: block;}</code> tags.\n\t */\n\tprivate static final String[] FB2_BLOCK_TAGS = {\n\t\t\"body\",\n\t\t\"section\",\n\t\t\"title\",\n\t\t\"p\", \"v\",\n\t\t\"empty-line\",\n\t\t\"abstract\",\n\t\t\"stanza\",\n\t\t\"epigraph\"\n\t\t};\n\t\n\t/**\n\t * These are <code>{display: inline;}</code> tags.\n\t */\n\tprivate static final String[] FB2_INLINE_TAGS = {\n\t\t\"strong\",\n\t\t\"emphasis\",\n\t\t\"strikethrough\",\n\t\t\"sub\",\n\t\t\"sup\",\n\t\t\"code\",\n\t\t\"a\",\n\t\t\"#text\"\n\t\t};\n\t\n\tstatic {\n\t\tfor (String s: FB2_INLINE_TAGS) {\n\t\t\tourDisplayTypes.put(s, EDisplayType.INLINE);\n\t\t}\n\n\t\tfor (String s: FB2_BLOCK_TAGS) {\n\t\t\tourDisplayTypes.put(s, EDisplayType.BLOCK);\n\t\t}\n\t}\n\n\tstatic EDisplayType getDisplay(String name) {\n\t\treturn ourDisplayTypes.get(name);\n\t}\n\n\tpublic IStyleStack newStyleStateStack() {\n\t\treturn new FB2StyleStack();\n\t}\n\n}" ]
import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.jbookreader.book.bom.IBinaryData; import org.jbookreader.book.bom.IBook; import org.jbookreader.book.bom.IContainerNode; import org.jbookreader.book.bom.IImageNode; import org.jbookreader.book.bom.INode; import org.jbookreader.book.bom.impl.Book; import org.jbookreader.book.stylesheet.IStyleSheet; import org.jbookreader.book.stylesheet.fb2.FB2StyleSheet; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory;
/* * JBookReader - Java FictionBook Reader * Copyright (C) 2006 Dmitry Baryshkov * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jbookreader.book.parser; /** * This class represents a parser for the FB2 books format. * * @author Dmitry Baryshkov ([email protected]) * */ public class FB2Parser { /** * The namespace of FB2 tags */ public static final String FB2_XMLNS_URI = "http://www.gribuser.ru/xml/fictionbook/2.0"; /** * This parses the book located at the <code>uri</code>. * @param uri the location of book to parse * @return the parsed book representation * @throws IOException in case of I/O problem * @throws SAXException in case of XML parsing problem */
public static IBook parse(String uri) throws IOException, SAXException {
1
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/storylist/StoryListFragment.java
[ "public class HackerNewsApplication extends SugarApp {\n private static boolean mDebug = BuildConfig.DEBUG;\n private static HackerNewsApplication sInstance;\n private Context mContext;\n private static AppComponent sAppComponent;\n\n private static AppModule sAppModule;\n\n @Override\n public void onCreate() {\n super.onCreate();\n if (sInstance == null) {\n sInstance = this;\n }\n\n if(\"release\".equals(BuildConfig.BUILD_TYPE)){\n Bugsnag.init(this);\n }\n\n mContext = getApplicationContext();\n Stetho.initialize(\n Stetho.newInitializerBuilder(this)\n .enableDumpapp(\n Stetho.defaultDumperPluginsProvider(this))\n .enableWebKitInspector(\n Stetho.defaultInspectorModulesProvider(this))\n .build());\n\n sAppModule = new AppModule(this);\n sAppComponent = DaggerAppComponent.builder()\n .appModule(sAppModule)\n .build();\n sAppComponent.inject(this);\n\n LocalDataManager.initialize(mContext);\n }\n\n public static boolean isDebug() {\n return mDebug;\n }\n\n public static HackerNewsApplication getInstance() {\n return sInstance;\n }\n\n public Context getContext() {\n return mContext;\n }\n\n public static AppComponent getAppComponent() {\n return sAppComponent;\n }\n\n public static AppModule getAppModule(){\n return sAppModule;\n }\n}", "public abstract class BaseViewModelFragment<T extends BaseViewModel> extends BaseFragment {\n protected abstract T getViewModel();\n\n @Override\n public void onResume() {\n super.onResume();\n getViewModel().onAttachToView();\n }\n\n public void onPause(){\n super.onPause();\n getViewModel().onDetachFromView();\n }\n}", "public class Story extends SugarRecord<Story> implements Parcelable {\n private Long mStoryId;\n private String mTitle;\n private String mUrl;\n private String mDomain;\n private int mPoints;\n private String mSubmitter;\n private String mPublishedTime;\n private int mNumComments;\n private String mType;\n private boolean isSaved;\n private boolean mIsRead;\n\n public Story() {\n }\n\n private Story(Long storyId, String title, String url, String domain, int points, String submitter, String publishedTime, int numComments, String type) {\n mStoryId = storyId;\n mTitle = title;\n mUrl = url;\n mDomain = domain;\n mPoints = points;\n mSubmitter = submitter;\n mPublishedTime = publishedTime;\n mNumComments = numComments;\n mType = type;\n }\n\n public static Story fromNodeHNAPIStory(NodeHNAPIStory nodeHNAPIStory) {\n return new Story(nodeHNAPIStory.id,\n nodeHNAPIStory.title,\n nodeHNAPIStory.url,\n nodeHNAPIStory.domain,\n nodeHNAPIStory.points,\n nodeHNAPIStory.user,\n nodeHNAPIStory.timeAgo,\n nodeHNAPIStory.commentsCount,\n nodeHNAPIStory.type);\n }\n\n public Long getStoryId() {\n return mStoryId;\n }\n\n public String getTitle() {\n return mTitle;\n }\n\n public String getUrl() {\n return mUrl;\n }\n\n public String getDomain() {\n return mDomain;\n }\n\n public int getPoints() {\n return mPoints;\n }\n\n public String getSubmitter() {\n return mSubmitter;\n }\n\n public String getPublishedTime() {\n return mPublishedTime;\n }\n\n public int getNumComments() {\n return mNumComments;\n }\n\n public String getType() {\n return mType;\n }\n\n public void setStoryId(Long storyId) {\n mStoryId = storyId;\n }\n\n public void setTitle(String title) {\n mTitle = title;\n }\n\n public void setUrl(String url) {\n mUrl = url;\n }\n\n public void setDomain(String domain) {\n mDomain = domain;\n }\n\n public void setPoints(int points) {\n mPoints = points;\n }\n\n public void setSubmitter(String submitter) {\n mSubmitter = submitter;\n }\n\n public void setPublishedTime(String publishedTime) {\n mPublishedTime = publishedTime;\n }\n\n public void setNumComments(int numComments) {\n mNumComments = numComments;\n }\n\n public void setType(String type) {\n mType = type;\n }\n\n public boolean isSaved() {\n return isSaved;\n }\n\n public void setIsSaved(boolean isSaved) {\n this.isSaved = isSaved;\n }\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 Story story = (Story) o;\n\n if (mStoryId != null ? !mStoryId.equals(story.mStoryId) : story.mStoryId != null)\n return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return mStoryId != null ? mStoryId.hashCode() : 0;\n }\n\n public boolean isRead() {\n return mIsRead;\n }\n\n public void setIsRead(boolean isRead) {\n this.mIsRead = isRead;\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.writeValue(this.mStoryId);\n dest.writeString(this.mTitle);\n dest.writeString(this.mUrl);\n dest.writeString(this.mDomain);\n dest.writeInt(this.mPoints);\n dest.writeString(this.mSubmitter);\n dest.writeString(this.mPublishedTime);\n dest.writeInt(this.mNumComments);\n dest.writeString(this.mType);\n dest.writeByte(isSaved ? (byte) 1 : (byte) 0);\n dest.writeByte(mIsRead ? (byte) 1 : (byte) 0);\n }\n\n protected Story(Parcel in) {\n this.mStoryId = (Long) in.readValue(Long.class.getClassLoader());\n this.mTitle = in.readString();\n this.mUrl = in.readString();\n this.mDomain = in.readString();\n this.mPoints = in.readInt();\n this.mSubmitter = in.readString();\n this.mPublishedTime = in.readString();\n this.mNumComments = in.readInt();\n this.mType = in.readString();\n this.isSaved = in.readByte() != 0;\n this.mIsRead = in.readByte() != 0;\n }\n\n public static final Creator<Story> CREATOR = new Creator<Story>() {\n public Story createFromParcel(Parcel source) {\n return new Story(source);\n }\n\n public Story[] newArray(int size) {\n return new Story[size];\n }\n };\n}", "public class HNLog {\n private static final Pattern ANONYMOUS_CLASS = Pattern.compile(\"(\\\\$\\\\d+)+$\");\n\n public static void d(@NonNull String message){\n if(HackerNewsApplication.isDebug()){\n Log.d(getTag(), message);\n }\n }\n\n public static void d(@NonNull String tag, @NonNull String message){\n if(HackerNewsApplication.isDebug()){\n Log.d(tag, message);\n }\n }\n\n public static void e(@NonNull String tag, @NonNull String message){\n if(HackerNewsApplication.isDebug()){\n Log.e(tag, message);\n }\n }\n\n public static void i(@NonNull String tag, @NonNull String message){\n if(HackerNewsApplication.isDebug()){\n Log.i(tag, message);\n }\n }\n\n public static void w(@NonNull String tag, @NonNull String message){\n if(HackerNewsApplication.isDebug()){\n Log.w(tag, message);\n }\n }\n\n public static void v(@NonNull String tag, @NonNull String message){\n if(HackerNewsApplication.isDebug()){\n Log.v(tag, message);\n }\n }\n\n private static String getTag(){\n StackTraceElement[] stackTrace = new Throwable().getStackTrace();\n if (stackTrace.length <= 2) {\n throw new IllegalStateException(\n \"Synthetic stacktrace didn't have enough elements: are you using proguard?\");\n }\n return createStackElementTag(stackTrace[2]);\n }\n\n protected static String createStackElementTag(StackTraceElement element) {\n String tag = element.getClassName();\n Matcher m = ANONYMOUS_CLASS.matcher(tag);\n if (m.find()) {\n tag = m.replaceAll(\"\");\n }\n return tag.substring(tag.lastIndexOf('.') + 1);\n }\n}", "public class UIUtils {\n public static int dpAsPixels(Context context, int densityPixels){\n float scale = context.getResources().getDisplayMetrics().density;\n return (int) (densityPixels * scale + 0.5f);\n }\n\n public static void showToast(Context context, String message){\n Toast.makeText(context, message, Toast.LENGTH_SHORT).show();\n }\n\n}" ]
import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import com.bluelinelabs.logansquare.LoganSquare; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.base.BaseViewModelFragment; import io.dwak.holohackernews.app.dagger.component.DaggerViewModelComponent; import io.dwak.holohackernews.app.models.Story; import io.dwak.holohackernews.app.util.HNLog; import io.dwak.holohackernews.app.util.UIUtils; import retrofit.RetrofitError; import rx.Observable; import rx.Observer; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers;
package io.dwak.holohackernews.app.ui.storylist; public class StoryListFragment extends BaseViewModelFragment<StoryListViewModel> { public static final String FEED_TO_LOAD = "feed_to_load"; private static final String TAG = StoryListFragment.class.getSimpleName(); public static final String TOP_OF_LIST = "TOP_OF_LIST"; public static final String STORY_LIST = "STORY_LIST"; @InjectView(R.id.story_list) RecyclerView mRecyclerView; @InjectView(R.id.swipe_container) SwipeRefreshLayout mSwipeRefreshLayout; private OnStoryListFragmentInteractionListener mListener; private StoryListAdapter mRecyclerAdapter; private LinearLayoutManager mLayoutManager; @Inject StoryListViewModel mViewModel; public static StoryListFragment newInstance(@StoryListViewModel.FeedType int feedType) { StoryListFragment fragment = new StoryListFragment(); Bundle args = new Bundle(); args.putInt(FEED_TO_LOAD, feedType); fragment.setArguments(args); return fragment; } private void refresh() { mRecyclerAdapter.clear(); getViewModel().setIsRestoring(false); getViewModel().setStoryList(null); react(getViewModel().getStories(), false); } private void react(Observable<Story> stories, boolean pageTwo) { stories.subscribe(new Subscriber<Story>() { @Override public void onCompleted() { showProgress(false); mSwipeRefreshLayout.setRefreshing(false); getViewModel().setPageTwoLoaded(pageTwo); } @Override public void onError(Throwable e) { if (e instanceof RetrofitError) { Toast.makeText(getActivity(), R.string.story_list_error_toast_message, Toast.LENGTH_SHORT).show(); } else { throw new RuntimeException(e); } } @Override public void onNext(Story story) { if (story.getStoryId() != null && mRecyclerAdapter.getPositionOfItem(story) == -1) { mRecyclerAdapter.addStory(story); } } }); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnStoryListFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnStoryListFragmentInteractionListener"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); DaggerViewModelComponent.builder()
.appComponent(HackerNewsApplication.getAppComponent())
0
52North/SensorPlanningService
52n-sps-testplugin/src/test/java/org/n52/sps/sensor/cite/CiteTaskResultAccessTest.java
[ "public class ResultAccessDataServiceReference {\r\n \r\n private Long id; // database id\r\n \r\n private String reference;\r\n \r\n private String role;\r\n \r\n private String title;\r\n \r\n private String identifier;\r\n \r\n private String referenceAbstract;\r\n \r\n private String format;\r\n\r\n /**\r\n * Content of SPSMetadata types\r\n */\r\n private List<String> dataAccessTypes;\r\n\r\n public ResultAccessDataServiceReference() {\r\n // database serialization\r\n }\r\n \r\n Long getId() {\r\n return id;\r\n }\r\n\r\n void setId(Long id) {\r\n this.id = id;\r\n }\r\n\r\n public String getReference() {\r\n return reference;\r\n }\r\n\r\n public void setReference(String reference) {\r\n this.reference = reference;\r\n }\r\n\r\n public String getRole() {\r\n return role;\r\n }\r\n\r\n public void setRole(String role) {\r\n this.role = role;\r\n }\r\n\r\n public String getTitle() {\r\n return title;\r\n }\r\n\r\n public void setTitle(String title) {\r\n this.title = title;\r\n }\r\n\r\n public String getIdentifier() {\r\n return identifier;\r\n }\r\n\r\n public void setIdentifier(String identifier) {\r\n this.identifier = identifier;\r\n }\r\n\r\n public String getReferenceAbstract() {\r\n return referenceAbstract;\r\n }\r\n\r\n public void setReferenceAbstract(String referenceAbstract) {\r\n this.referenceAbstract = referenceAbstract;\r\n }\r\n\r\n public String getFormat() {\r\n return format;\r\n }\r\n\r\n public void setFormat(String format) {\r\n this.format = format;\r\n }\r\n\r\n public List<String> getDataAccessTypes() {\r\n return dataAccessTypes;\r\n }\r\n\r\n public void setDataAccessTypes(List<String> dataAccessTypes) {\r\n this.dataAccessTypes = dataAccessTypes;\r\n }\r\n \r\n \r\n}\r", "public class SensorTask {\r\n \r\n private static final Logger LOGGER = LoggerFactory.getLogger(SensorTask.class);\r\n \r\n private static final DateTimeFormatter ISO8601_FORMATTER = ISODateTimeFormat.dateTime();\r\n\r\n private Long id; // database id\r\n \r\n private String taskId;\r\n \r\n private String procedure;\r\n\r\n private Calendar estimatedToC;\r\n \r\n private SensorTaskStatus taskStatus;\r\n\r\n private double percentCompletion = 0d;\r\n\r\n private TaskingRequestStatus requestStatus = TaskingRequestStatus.PENDING;\r\n\r\n private Calendar updateTime = new GregorianCalendar(); // default;\r\n\r\n private List<String> statusMessages = new ArrayList<String>();\r\n\r\n private ParameterDataType parameterData;\r\n\r\n private String event;\r\n\r\n SensorTask() {\r\n // database serialization\r\n }\r\n \r\n public SensorTask(String taskId, String procedure) {\r\n checkNonEmptyParameter(taskId, procedure);\r\n this.taskId = taskId;\r\n this.procedure = procedure;\r\n }\r\n\r\n private void checkNonEmptyParameter(String taskId, String procedure) {\r\n if (taskId == null || taskId.isEmpty()) {\r\n LOGGER.error(\"Illegal parameter => taskId: {}\", taskId);\r\n throw new IllegalArgumentException(\"taskId must not be null!\");\r\n }\r\n if (procedure == null || procedure.isEmpty()) {\r\n LOGGER.error(\"Illegal parameter => procedure: {}\", procedure);\r\n throw new IllegalArgumentException(\"procedure must not be null!\");\r\n }\r\n }\r\n \r\n Long getId() {\r\n return id;\r\n }\r\n\r\n void setId(Long id) {\r\n // keep package private for database\r\n this.id = id;\r\n }\r\n\r\n public String getTaskId() {\r\n return taskId;\r\n }\r\n \r\n void setTaskId(String taskId) {\r\n // keep package private for database\r\n this.taskId = taskId;\r\n }\r\n \r\n public Calendar getCalendarInstance() {\r\n return updateTime;\r\n }\r\n\r\n public void setUpdateTime(Calendar calendar) {\r\n this.updateTime = calendar;\r\n }\r\n \r\n public Calendar getUpdateTime() {\r\n return updateTime;\r\n }\r\n\r\n public String getFormattedUpdateTime(DateFormat formatter) {\r\n return formatter.format(updateTime.getTime());\r\n }\r\n \r\n public String getUpdateTimeFormattedAsIso8601() {\r\n return ISO8601_FORMATTER.print(updateTime.getTimeInMillis());\r\n }\r\n\r\n /**\r\n * @param requestStatus\r\n * according to REQ 14: <a\r\n * href=\"http://www.opengis.net/spec/SPS/2.0/req/TaskingResponse/content\">http\r\n * ://www.opengis.net/spec/SPS/2.0/req/TaskingResponse/content</a>\r\n */\r\n public void setRequestStatus(TaskingRequestStatus requestStatus) {\r\n this.updateTime.setTimeInMillis(System.currentTimeMillis());\r\n this.requestStatus = requestStatus;\r\n if (!isAccepted()) {\r\n updateStatusTransitionEvent(RESET_TRANSITION_EVENT);\r\n } else {\r\n updateStatusTransitionEvent(TASK_SUBMITTED);\r\n } \r\n }\r\n\r\n public void setRequestStatusAsString(String requestStatus) {\r\n if (requestStatus != null) {\r\n this.requestStatus = TaskingRequestStatus.getTaskingRequestStatus(requestStatus);\r\n }\r\n }\r\n\r\n private void updateStatusTransitionEvent(TaskStatusTransitionEvent transition) {\r\n event = transition.getEvent();\r\n }\r\n\r\n public TaskingRequestStatus getRequestStatus() {\r\n return requestStatus;\r\n }\r\n \r\n public String getRequestStatusAsString() {\r\n return requestStatus.toString();\r\n }\r\n\r\n /**\r\n * @return the estimated time when task will finish.\r\n */\r\n public Calendar getEstimatedToC() {\r\n return estimatedToC;\r\n }\r\n\r\n public void setEstimatedToC(Calendar estimatedToC) {\r\n this.estimatedToC = estimatedToC;\r\n }\r\n\r\n public double getPercentCompletion() {\r\n return percentCompletion;\r\n }\r\n\r\n public void setPercentCompletion(double percentCompletion) {\r\n this.percentCompletion = percentCompletion;\r\n }\r\n\r\n public String getProcedure() {\r\n return procedure;\r\n }\r\n \r\n void setProcedure(String procedure) {\r\n // keep package private for database\r\n this.procedure = procedure;\r\n }\r\n\r\n public void clearStatusMessages() {\r\n statusMessages.clear();\r\n }\r\n\r\n public void addStatusMessage(String message) {\r\n statusMessages.add(message);\r\n }\r\n \r\n public void setStatusMessages(List<String> statusMessages) {\r\n this.statusMessages = statusMessages;\r\n }\r\n\r\n public List<String> getStatusMessages() {\r\n return statusMessages;\r\n }\r\n\r\n /**\r\n * @param taskStatus\r\n * according to REQ 15: <a\r\n * href=\"http://www.opengis.net/spec/SPS/2.0/req/TaskingResponse/statusCodes\"\r\n * >http://www.opengis.net/spec/SPS/2.0/req/TaskingResponse/statusCodes</a>\r\n */\r\n public void setTaskStatus(SensorTaskStatus taskStatus) {\r\n this.taskStatus = taskStatus;\r\n if (isExecuting()) {\r\n updateStatusTransitionEvent(TASK_SUBMITTED);\r\n } else if (isFinished()) {\r\n updateStatusTransitionEvent(TASK_COMPLETED);\r\n setPercentCompletion(100.0);\r\n } else if (isExpired()) {\r\n updateStatusTransitionEvent(TASKING_REQUEST_EXPIRED);\r\n } else {\r\n updateStatusTransitionEvent(RESET_TRANSITION_EVENT);\r\n }\r\n }\r\n \r\n public void setTaskStatusAsString(String taskStatus) {\r\n if (taskStatus != null) {\r\n this.taskStatus = SensorTaskStatus.getSensorTaskStatus(taskStatus);\r\n }\r\n }\r\n\r\n public String getFormattedEstimatedToC(DateFormat formatter) {\r\n return formatter.format(estimatedToC.getTime());\r\n }\r\n \r\n public String getEstimatedToCFormattedAsIso8601() {\r\n return ISO8601_FORMATTER.print(estimatedToC.getTimeInMillis());\r\n }\r\n \r\n public SensorTaskStatus getTaskStatus() {\r\n return taskStatus;\r\n }\r\n\r\n public String getTaskStatusAsString() {\r\n return taskStatus != null ? taskStatus.toString() : null;\r\n }\r\n \r\n public ParameterDataType getParameterData() {\r\n return parameterData;\r\n }\r\n\r\n public String getParameterDataAsString() {\r\n return parameterData != null ? parameterData.xmlText() : null;\r\n }\r\n\r\n public void setParameterData(ParameterDataType parameterData) {\r\n this.parameterData = parameterData;\r\n }\r\n \r\n public void setParameterDataAsString(String parameterData) throws XmlException {\r\n if (parameterData != null) {\r\n this.parameterData = ParameterDataType.Factory.parse(parameterData);\r\n }\r\n }\r\n \r\n public String getEvent() {\r\n return event;\r\n }\r\n \r\n void setEvent(String event) {\r\n this.event = event;\r\n }\r\n \r\n public TaskType getTask() throws StatusInformationExpiredException {\r\n StatusReportGenerator statusReporter = StatusReportGenerator.createFor(this);\r\n TaskType taskType = TaskType.Factory.newInstance();\r\n taskType.setIdentifier(getTaskId());\r\n StatusReportPropertyType status = taskType.addNewStatus();\r\n status.setStatusReport(statusReporter.generateWithoutTaskingParameters());\r\n return taskType;\r\n }\r\n\r\n /**\r\n * @deprecated use {@link StatusReportGenerator} instead.\r\n * @return\r\n * @throws StatusInformationExpiredException\r\n */\r\n @Deprecated\r\n public StatusReportType generateStatusReport() throws StatusInformationExpiredException {\r\n if (taskStatus == SensorTaskStatus.EXPIRED) {\r\n throw new StatusInformationExpiredException();\r\n }\r\n StatusReportType statusReport = StatusReportType.Factory.newInstance();\r\n statusReport.setTask(getTaskId());\r\n statusReport.setProcedure(getProcedure());\r\n statusReport.setRequestStatus(getRequestStatusAsString());\r\n statusReport.setUpdateTime(updateTime);\r\n if (estimatedToC != null) {\r\n statusReport.setEstimatedToC(estimatedToC);\r\n }\r\n\r\n // TODO implement event\r\n\r\n if (percentCompletion >= 0d) {\r\n statusReport.setPercentCompletion(percentCompletion);\r\n }\r\n if ( !statusMessages.isEmpty()) {\r\n for (String message : statusMessages) {\r\n LanguageStringType statusMessage = statusReport.addNewStatusMessage();\r\n statusMessage.setStringValue(message);\r\n }\r\n }\r\n if (taskStatus != null) {\r\n statusReport.setTaskStatus(getTaskStatusAsString());\r\n }\r\n\r\n // TODO implement alternative\r\n\r\n if (parameterData != null) {\r\n statusReport.addNewTaskingParameters().setParameterData(parameterData);\r\n }\r\n return statusReport;\r\n }\r\n \r\n public boolean isExpired() {\r\n return taskStatus == SensorTaskStatus.EXPIRED;\r\n }\r\n \r\n public boolean isFinished() {\r\n return taskStatus == SensorTaskStatus.COMPLETED;\r\n }\r\n \r\n public boolean isAccepted() {\r\n return requestStatus == TaskingRequestStatus.ACCEPTED;\r\n }\r\n\r\n public boolean isExecuting() {\r\n return taskStatus == SensorTaskStatus.INEXECUTION;\r\n }\r\n \r\n @Override\r\n public int hashCode() {\r\n final int prime = 31;\r\n int result = 1;\r\n result = prime * result + ( (procedure == null) ? 0 : procedure.hashCode());\r\n result = prime * result + ( (taskId == null) ? 0 : taskId.hashCode());\r\n return result;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj)\r\n return true;\r\n if (obj == null)\r\n return false;\r\n if (getClass() != obj.getClass())\r\n return false;\r\n SensorTask other = (SensorTask) obj;\r\n if (procedure == null) {\r\n if (other.procedure != null)\r\n return false;\r\n }\r\n else if ( !procedure.equals(other.procedure))\r\n return false;\r\n if (taskId == null) {\r\n if (other.taskId != null)\r\n return false;\r\n }\r\n else if ( !taskId.equals(other.taskId))\r\n return false;\r\n return true;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"TaskId: \").append(getTaskId()).append(\", \");\r\n sb.append(\"Procedure: \").append(getProcedure()).append(\", \");\r\n sb.append(\"RequestStatus: \").append(requestStatus).append(\", \");\r\n sb.append(\"UpdateTime: \").append(getUpdateTimeFormattedAsIso8601());\r\n return sb.toString();\r\n }\r\n\r\n}\r", "public class MissingSensorInformationException extends InternalServiceException {\r\n\r\n private static final long serialVersionUID = -7661454857813095434L;\r\n\r\n public MissingSensorInformationException(String locator) {\r\n super(InternalServiceExceptionCode.MISSING_SENSOR_INFORMATION.toString(), locator);\r\n }\r\n\r\n @Override\r\n public int getHttpStatusCode() {\r\n return InternalServiceException.BAD_REQUEST;\r\n }\r\n\r\n}\r", "public class SensorInstanceProvider implements InsertSensorOfferingListener {\r\n\r\n private static final Logger LOGGER = LoggerFactory.getLogger(SensorInstanceProvider.class);\r\n\r\n protected SensorConfigurationRepository sensorConfigurationRepository;\r\n\r\n protected SensorTaskRepository sensorTaskRepository;\r\n\r\n private ServiceLoader<SensorInstanceFactory> sensorPluginLoader;\r\n\r\n private List<SensorPlugin> sensorInstances = new ArrayList<SensorPlugin>();\r\n\r\n public void init() throws InternalServiceException {\r\n sensorPluginLoader = ServiceLoader.load(SensorInstanceFactory.class);\r\n if (isMissingRepository()) {\r\n throw new IllegalStateException(\"SensorInstanceProvider misses a repository.\");\r\n }\r\n Iterable<SensorConfiguration> configs = sensorConfigurationRepository.getSensorConfigurations();\r\n for (SensorConfiguration sensorConfiguration : configs) {\r\n sensorInstances.add(initSensorInstance(sensorConfiguration));\r\n }\r\n LOGGER.info(\"Initialised {} with #{} sensor configuration(s).\", getClass().getSimpleName(), sensorInstances.size());\r\n }\r\n\r\n private boolean isMissingRepository() {\r\n return sensorConfigurationRepository == null || sensorTaskRepository == null;\r\n }\r\n \r\n protected void addSensor(SensorPlugin sensorInstance) {\r\n // protected access to provide a seam for testing only\r\n sensorInstances.add(sensorInstance);\r\n }\r\n\r\n public Iterable<SensorPlugin> getSensors() {\r\n return sensorInstances;\r\n }\r\n \r\n public boolean containsTaskWith(String taskId) {\r\n return getTaskForTaskId(taskId) != null;\r\n }\r\n\r\n public SensorTask getTaskForTaskId(String taskId) {\r\n return getSensorTaskRepository().getTask(taskId);\r\n }\r\n \r\n public boolean containsSensorWith(String procedure) {\r\n return getSensorForProcedure(procedure) != null;\r\n }\r\n\r\n public SensorPlugin getSensorForProcedure(String procedure) {\r\n for (SensorPlugin sensorInstance : sensorInstances) {\r\n if (sensorInstance.getProcedure().equals(procedure)) {\r\n return sensorInstance;\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n public SensorPlugin getSensorForTaskId(String taskId) {\r\n SensorTask sensorTask = sensorTaskRepository.getTask(taskId);\r\n return getSensorForProcedure(sensorTask.getProcedure());\r\n }\r\n\r\n public SensorConfigurationRepository getSensorConfigurationRepository() {\r\n return sensorConfigurationRepository;\r\n }\r\n\r\n public void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository) throws InternalServiceException {\r\n this.sensorConfigurationRepository = sensorConfigurationRepository;\r\n }\r\n \r\n public SensorTaskRepository getSensorTaskRepository() {\r\n return sensorTaskRepository;\r\n }\r\n\r\n public void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository) {\r\n this.sensorTaskRepository = sensorTaskRepository;\r\n }\r\n\r\n public void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent) throws InternalServiceException {\r\n InsertSensorOfferingDocument insertSensorOfferingDocument = insertSensorOfferingEvent.getInsertSensorOffering();\r\n InsertSensorOffering insertSensorOffering = insertSensorOfferingDocument.getInsertSensorOffering();\r\n SensorOfferingType sensorOffering = createFromInsertSensorOffering(insertSensorOffering);\r\n SensorConfiguration sensorConfiguration = createSensorConfiguration(insertSensorOffering, sensorOffering);\r\n if (isSensorExisting(insertSensorOffering.getSensorInstanceData())) {\r\n SensorPlugin sensorPlugin = getSensorForProcedure(sensorOffering.getProcedure());\r\n sensorPlugin.mergeSensorConfigurations(sensorConfiguration);\r\n sensorConfigurationRepository.saveOrUpdateSensorConfiguration(sensorConfiguration);\r\n }\r\n else {\r\n checkMandatoryContentForNewSensorOffering(insertSensorOffering);\r\n sensorInstances.add(initSensorInstance(sensorConfiguration));\r\n sensorConfigurationRepository.storeNewSensorConfiguration(sensorConfiguration);\r\n }\r\n }\r\n\r\n private SensorPlugin initSensorInstance(SensorConfiguration sensorConfiguration) throws InternalServiceException {\r\n String pluginType = sensorConfiguration.getSensorPluginType();\r\n SensorInstanceFactory factory = getSensorFactory(pluginType);\r\n SensorTaskService sensorTaskService = new SensorTaskService(sensorTaskRepository);\r\n return factory.createSensorPlugin(sensorTaskService, sensorConfiguration);\r\n }\r\n\r\n private void checkMandatoryContentForNewSensorOffering(InsertSensorOffering insertSensorOffering) throws MissingSensorInformationException {\r\n // XXX validating InsertSensorOffering may make this check unneccessary\r\n SensorDescriptionData[] sensorDescriptions = insertSensorOffering.getSensorDescriptionDataArray();\r\n if (sensorDescriptions == null || sensorDescriptions.length == 0) {\r\n LOGGER.warn(\"No sensor description found.\");\r\n throw new MissingSensorInformationException(\"sensorDescription\");\r\n }\r\n if (insertSensorOffering.getSensorTaskingParametersSet() == null) {\r\n LOGGER.warn(\"No sensor tasking parameters found.\");\r\n throw new MissingSensorInformationException(\"sensorTaskingParameters\");\r\n }\r\n }\r\n\r\n protected SensorInstanceFactory getSensorFactory(String pluginType) throws PluginTypeConfigurationException {\r\n Iterator<SensorInstanceFactory> iterator = sensorPluginLoader.iterator();\r\n while (iterator.hasNext()) {\r\n SensorInstanceFactory factory = iterator.next();\r\n if (factory.getPluginType().equals(pluginType)) {\r\n return factory;\r\n }\r\n }\r\n LOGGER.error(\"Unknown sensor plugin type or no factory has been configured for '{}'.\", pluginType);\r\n throw new PluginTypeConfigurationException(pluginType);\r\n }\r\n\r\n private SensorOfferingType createFromInsertSensorOffering(InsertSensorOffering insertSensorOffering) {\r\n InsertSensorOfferingConverter converter = new InsertSensorOfferingConverter();\r\n return converter.convertToSensorOfferingType(insertSensorOffering);\r\n }\r\n\r\n private SensorConfiguration createSensorConfiguration(InsertSensorOffering insertSensorOffering, SensorOfferingType sensorOffering) throws InternalServiceException {\r\n SensorConfiguration sensorConfiguration = new SensorConfiguration();\r\n SensorInstanceData sensorInstanceData = insertSensorOffering.getSensorInstanceData();\r\n sensorConfiguration.setSensorPluginType(sensorInstanceData.getSensorPluginType());\r\n sensorConfiguration.setProcedure(sensorInstanceData.getProcedure().getStringValue());\r\n sensorConfiguration.setSensorDescriptions(createSensorDescriptions(insertSensorOffering.getSensorDescriptionDataArray()));\r\n sensorConfiguration.addSensorOffering(sensorOffering);\r\n sensorConfiguration.setTaskingParametersTemplate(createTaskingParameterTemplate(insertSensorOffering.getSensorTaskingParametersSet()));\r\n sensorConfiguration.setResultAccessDataService(createResultAccessReference(sensorInstanceData));\r\n if (insertSensorOffering.isSetSensorSetup()) {\r\n sensorConfiguration.setSensorSetup(insertSensorOffering.getSensorSetup());\r\n }\r\n return sensorConfiguration;\r\n }\r\n\r\n\r\n /**\r\n * Checks if the sensor instance data passed can be associated with an existing sensor instance. This is\r\n * done by checking the procedure and the corresponding plugin type. If the plugin type was omitted, the\r\n * plugin type of the sensor instance found (if so) will be assumed. An exception will be thrown if there\r\n * seems to be a request for an existing sensor instance with a procedure not matching its plugin type.\r\n * \r\n * @param sensorInstanceData\r\n * the sensor instance data of the sensor to check.\r\n * @return <code>true</code> if a sensor instance with matching procedure and plugin type does already\r\n * exist, and <code>false</code> if procedure is unknown.\r\n * @throws IllegalPluginTypeRelationException\r\n * if a sensor instance with matching procedure but different plugin type does exit already.\r\n */\r\n private boolean isSensorExisting(SensorInstanceData sensorInstanceData) throws IllegalPluginTypeRelationException {\r\n String procedure = sensorInstanceData.getProcedure().getStringValue();\r\n String sensorPluginType = sensorInstanceData.getSensorPluginType();\r\n if (sensorConfigurationRepository.containsSensorConfiguration(procedure)) {\r\n SensorPlugin sensorInstance = getSensorForProcedure(procedure);\r\n String existingType = sensorInstance.getSensorPluginType();\r\n if (sensorPluginType == null || existingType.equals(sensorPluginType)) {\r\n return true;\r\n }\r\n else {\r\n LOGGER.error(\"Procedure '{}' already exists (for type '{}')\", procedure, existingType);\r\n throw new IllegalPluginTypeRelationException(\"Procedure already in use.\");\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n private List<SensorDescription> createSensorDescriptions(SensorDescriptionData[] sensorDescriptionDataArray) {\r\n List<SensorDescription> sensorDescriptions = new ArrayList<SensorDescription>();\r\n for (SensorDescriptionData sensorDescriptionData : sensorDescriptionDataArray) {\r\n String procedureDescriptionFormat = sensorDescriptionData.getProcedureDescriptionFormat();\r\n String downloadLink = sensorDescriptionData.getDownloadLink();\r\n sensorDescriptions.add(new SensorDescription(procedureDescriptionFormat, downloadLink));\r\n }\r\n return sensorDescriptions;\r\n }\r\n \r\n\r\n private AbstractDataComponentType createTaskingParameterTemplate(SensorTaskingParametersSet sensorTaskingParametersSet) throws InvalidSensorInformationException {\r\n AbstractDataComponentType parameterTemplate = null;\r\n if (sensorTaskingParametersSet.isSetSingleParameterSet()) {\r\n SingleParameterSet singleParameterSet = sensorTaskingParametersSet.getSingleParameterSet();\r\n AbstractDataComponentType parameterSet = singleParameterSet.getAbstractDataComponent();\r\n if (isValidTaskingName(parameterSet.getIdentifier())) {\r\n parameterTemplate = parameterSet;\r\n } else {\r\n throwInvalidSensorInformation(parameterSet.getIdentifier());\r\n }\r\n } else {\r\n MultipleParameterSets parameterSets = sensorTaskingParametersSet.getMultipleParameterSets();\r\n List<String> validIdentifiers = new ArrayList<String>();\r\n for (Item parameterSet : parameterSets.getDataChoice().getItemArray()) {\r\n if (!isValidTaskingName(parameterSet.getName(), validIdentifiers)) {\r\n throwInvalidSensorInformation(parameterSet.getName());\r\n }\r\n }\r\n parameterTemplate = parameterSets.getDataChoice();\r\n }\r\n return parameterTemplate;\r\n }\r\n\r\n private boolean isValidTaskingName(String name, List<String> validIdentifiers) {\r\n boolean alreadyContainsIdentifier = validIdentifiers.contains(name);\r\n if (alreadyContainsIdentifier) {\r\n return false;\r\n } else {\r\n if (isValidTaskingName(name)) {\r\n return validIdentifiers.add(name);\r\n } else {\r\n return false;\r\n }\r\n }\r\n }\r\n\r\n private boolean isValidTaskingName(String name) {\r\n return name != null && !name.isEmpty();\r\n }\r\n\r\n private void throwInvalidSensorInformation(String identifier) throws InvalidSensorInformationException {\r\n InvalidSensorInformationException e = new InvalidSensorInformationException(\"taskingParameters\");\r\n String msg = String.format(\"Invalid identifier for tasking parameter: '%s'\", identifier);\r\n e.addDetailedMessage(msg);\r\n LOGGER.warn(msg);\r\n throw e;\r\n }\r\n\r\n protected ResultAccessDataServiceReference createResultAccessReference(SensorInstanceData sensorInstanceData) throws MissingSensorInformationException {\r\n ResultAccessDataServiceReference resultAccessDataServiceReference = new ResultAccessDataServiceReference();\r\n ReferenceType reference = sensorInstanceData.getReference();\r\n if (reference == null) {\r\n throw new MissingSensorInformationException(\"reference\");\r\n }\r\n resultAccessDataServiceReference.setRole(reference.getRole());\r\n resultAccessDataServiceReference.setTitle(reference.getTitle());\r\n resultAccessDataServiceReference.setFormat(reference.getFormat());\r\n resultAccessDataServiceReference.setReference(reference.getHref());\r\n resultAccessDataServiceReference.setIdentifier(reference.getIdentifier().getStringValue());\r\n resultAccessDataServiceReference.setDataAccessTypes(createDataAccessTypes(reference.getMetadataArray()));\r\n handleAbstractContent(resultAccessDataServiceReference, reference.getAbstractArray());\r\n return resultAccessDataServiceReference;\r\n }\r\n\r\n private List<String> createDataAccessTypes(MetadataType[] metadataArray) throws MissingSensorInformationException {\r\n try {\r\n List<String> metadatas = new ArrayList<String>();\r\n for (MetadataType metadataType : metadataArray) {\r\n SPSMetadataDocument spsMetadata = SPSMetadataDocument.Factory.parse(metadataType.newInputStream());\r\n metadatas.add(spsMetadata.getSPSMetadata().getDataAccessType());\r\n }\r\n return metadatas;\r\n }\r\n catch (XmlException e) {\r\n LOGGER.warn(\"Invalid metadata element detected.\", e);\r\n throw new MissingSensorInformationException(\"sps metadata\");\r\n }\r\n catch (IOException e) {\r\n LOGGER.warn(\"Invalid metadata element detected.\", e);\r\n throw new MissingSensorInformationException(\"sps metadata\");\r\n }\r\n }\r\n\r\n private void handleAbstractContent(ResultAccessDataServiceReference reference, LanguageStringType[] abstracts) {\r\n if (abstracts != null && abstracts.length > 0) {\r\n reference.setReferenceAbstract(abstracts[0].getStringValue());\r\n if (abstracts.length > 1) {\r\n LOGGER.warn(\"Ignore further abstract descriptions, as SPS spec. requires only one!\");\r\n }\r\n }\r\n }\r\n\r\n}\r", "public class FileContentLoader {\r\n\r\n /**\r\n * Loads XML files which can be found via the <code>clazz</code>'s {@link ClassLoader}. If not found the\r\n * {@link FileContentLoader}'s {@link ClassLoader} is asked to load the file. If file could not be found\r\n * an exception is thrown.\r\n * \r\n * @param filePath\r\n * the path to the file to be loaded.\r\n * @param clazz\r\n * the class which {@link ClassLoader} to be used.\r\n * @return an XmlObject of the loaded file.\r\n * @throws XmlException\r\n * if file could not be parsed into XML\r\n * @throws IOException\r\n * if file could not be read.\r\n * @throws IllegalArgumentException\r\n * if file path is <code>null</code> or empty\r\n * @throws FileNotFoundException\r\n * if the resource could not be found be the <code>clazz</code>'s {@link ClassLoader}\r\n */\r\n public static XmlObject loadXmlFileViaClassloader(String filePath, Class< ? > clazz) throws XmlException,\r\n IOException {\r\n if (filePath == null || filePath.isEmpty()) {\r\n throw new IllegalArgumentException(\"Check file path: '\" + filePath + \"'.\");\r\n }\r\n InputStream is = clazz.getResourceAsStream(filePath);\r\n if (is == null) {\r\n is = FileContentLoader.class.getResourceAsStream(filePath);\r\n if (is == null) {\r\n throw new FileNotFoundException(\"The resource at '\" + filePath + \"' cannot be found.\");\r\n }\r\n }\r\n return XmlObject.Factory.parse(is);\r\n }\r\n\r\n}\r" ]
import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.junit.Before; import org.junit.Test; import org.n52.sps.sensor.model.ResultAccessDataServiceReference; import org.n52.sps.sensor.model.SensorTask; import org.n52.sps.service.admin.MissingSensorInformationException; import org.n52.sps.service.core.SensorInstanceProvider; import org.n52.testing.utilities.FileContentLoader; import org.x52North.schemas.sps.v2.SensorInstanceDataDocument; import org.x52North.schemas.sps.v2.SensorInstanceDataDocument.SensorInstanceData; import static org.junit.Assert.*; import net.opengis.ows.x11.ServiceReferenceType;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * 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. */ package org.n52.sps.sensor.cite; public class CiteTaskResultAccessTest { private CiteTaskResultAccess citeTaskResultAccess; private String procedure; private String taskId; @Before public void setUp() throws Exception { XmlObject file = FileContentLoader.loadXmlFileViaClassloader("/files/sensorInstanceData.xml", getClass()); SensorInstanceDataDocument.Factory.newInstance(); SensorInstanceDataDocument instanceDataDoc = SensorInstanceDataDocument.Factory.parse(file.newInputStream()); SensorInstanceData sensorInstanceData = instanceDataDoc.getSensorInstanceData(); SensorInstanceProviderSeam sensorInstanceProviderSeam = new SensorInstanceProviderSeam(); ResultAccessDataServiceReference reference = sensorInstanceProviderSeam.createResultAccess(sensorInstanceData); procedure = "http://host.tld/procedure1/"; taskId = "http://host.tld/procedure1/tasks/1";
SensorTask validTask = new SensorTask(taskId, procedure);
1
VladThodo/behe-keyboard
app/src/main/java/com/vlath/keyboard/latin/settings/Settings.java
[ "public final class KeyboardTheme implements Comparable<KeyboardTheme> {\n private static final String TAG = KeyboardTheme.class.getSimpleName();\n\n static final String KLP_KEYBOARD_THEME_KEY = \"pref_keyboard_layout_20110916\";\n static final String LXX_KEYBOARD_THEME_KEY = \"pref_keyboard_theme_20140509\";\n\n // These should be aligned with Keyboard.themeId and Keyboard.Case.keyboardTheme\n // attributes' values in attrs.xml.\n public static final int THEME_ID_ICS = 0;\n public static final int THEME_ID_KLP = 2;\n public static final int THEME_ID_LXX_LIGHT = 3;\n public static final int THEME_ID_LXX_DARK = 4;\n public static final int DEFAULT_THEME_ID = THEME_ID_LXX_DARK;\n\n private static KeyboardTheme[] AVAILABLE_KEYBOARD_THEMES;\n\n /* package private for testing */\n static final KeyboardTheme[] KEYBOARD_THEMES = {\n new KeyboardTheme(THEME_ID_ICS, \"ICS\", R.style.KeyboardTheme_ICS,\n // This has never been selected because we support ICS or later.\n VERSION_CODES.BASE),\n new KeyboardTheme(THEME_ID_KLP, \"KLP\", R.style.KeyboardTheme_KLP,\n // Default theme for ICS, JB, and KLP.\n VERSION_CODES.ICE_CREAM_SANDWICH),\n new KeyboardTheme(THEME_ID_LXX_LIGHT, \"LXXLight\", R.style.KeyboardTheme_LXX_Light,\n // Default theme for LXX.\n Build.VERSION_CODES.LOLLIPOP),\n new KeyboardTheme(THEME_ID_LXX_DARK, \"LXXDark\", R.style.KeyboardTheme_LXX_Dark,\n // This has never been selected as default theme.\n VERSION_CODES.BASE),\n };\n\n static {\n // Sort {@link #KEYBOARD_THEME} by descending order of {@link #mMinApiVersion}.\n Arrays.sort(KEYBOARD_THEMES);\n }\n\n public final int mThemeId;\n public final int mStyleId;\n public final String mThemeName;\n public final int mMinApiVersion;\n\n // Note: The themeId should be aligned with \"themeId\" attribute of Keyboard style\n // in values/themes-<style>.xml.\n private KeyboardTheme(final int themeId, final String themeName, final int styleId,\n final int minApiVersion) {\n mThemeId = themeId;\n mThemeName = themeName;\n mStyleId = styleId;\n mMinApiVersion = minApiVersion;\n }\n\n @Override\n public int compareTo(final KeyboardTheme rhs) {\n if (mMinApiVersion > rhs.mMinApiVersion) return -1;\n if (mMinApiVersion < rhs.mMinApiVersion) return 1;\n return 0;\n }\n\n @Override\n public boolean equals(final Object o) {\n if (o == this) return true;\n return (o instanceof KeyboardTheme) && ((KeyboardTheme)o).mThemeId == mThemeId;\n }\n\n @Override\n public int hashCode() {\n return mThemeId;\n }\n\n /* package private for testing */\n static KeyboardTheme searchKeyboardThemeById(final int themeId,\n final KeyboardTheme[] availableThemeIds) {\n // TODO: This search algorithm isn't optimal if there are many themes.\n for (final KeyboardTheme theme : availableThemeIds) {\n if (theme.mThemeId == themeId) {\n return theme;\n }\n }\n return null;\n }\n\n /* package private for testing */\n static KeyboardTheme getDefaultKeyboardTheme(final SharedPreferences prefs,\n final int sdkVersion, final KeyboardTheme[] availableThemeArray) {\n final String klpThemeIdString = prefs.getString(KLP_KEYBOARD_THEME_KEY, null);\n if (klpThemeIdString != null) {\n if (sdkVersion <= VERSION_CODES.KITKAT) {\n try {\n final int themeId = Integer.parseInt(klpThemeIdString);\n final KeyboardTheme theme = searchKeyboardThemeById(themeId,\n availableThemeArray);\n if (theme != null) {\n return theme;\n }\n Log.w(TAG, \"Unknown keyboard theme in KLP preference: \" + klpThemeIdString);\n } catch (final NumberFormatException e) {\n Log.w(TAG, \"Illegal keyboard theme in KLP preference: \" + klpThemeIdString, e);\n }\n }\n // Remove old preference.\n Log.i(TAG, \"Remove KLP keyboard theme preference: \" + klpThemeIdString);\n prefs.edit().remove(KLP_KEYBOARD_THEME_KEY).apply();\n }\n // TODO: This search algorithm isn't optimal if there are many themes.\n for (final KeyboardTheme theme : availableThemeArray) {\n if (sdkVersion >= theme.mMinApiVersion) {\n return theme;\n }\n }\n return searchKeyboardThemeById(DEFAULT_THEME_ID, availableThemeArray);\n }\n\n public static String getKeyboardThemeName(final int themeId) {\n final KeyboardTheme theme = searchKeyboardThemeById(themeId, KEYBOARD_THEMES);\n return theme.mThemeName;\n }\n\n public static void saveKeyboardThemeId(final int themeId, final SharedPreferences prefs) {\n saveKeyboardThemeId(themeId, prefs, Build.VERSION.SDK_INT);\n }\n\n /* package private for testing */\n static String getPreferenceKey(final int sdkVersion) {\n if (sdkVersion <= VERSION_CODES.KITKAT) {\n return KLP_KEYBOARD_THEME_KEY;\n }\n return LXX_KEYBOARD_THEME_KEY;\n }\n\n /* package private for testing */\n static void saveKeyboardThemeId(final int themeId, final SharedPreferences prefs,\n final int sdkVersion) {\n final String prefKey = getPreferenceKey(sdkVersion);\n prefs.edit().putString(prefKey, Integer.toString(themeId)).apply();\n }\n\n public static KeyboardTheme getKeyboardTheme(final Context context) {\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n final KeyboardTheme[] availableThemeArray = getAvailableThemeArray(context);\n return getKeyboardTheme(prefs, Build.VERSION.SDK_INT, availableThemeArray);\n }\n\n /* package private for testing */\n static KeyboardTheme[] getAvailableThemeArray(final Context context) {\n if (AVAILABLE_KEYBOARD_THEMES == null) {\n final int[] availableThemeIdStringArray = context.getResources().getIntArray(\n R.array.keyboard_theme_ids);\n final ArrayList<KeyboardTheme> availableThemeList = new ArrayList<>();\n for (final int id : availableThemeIdStringArray) {\n final KeyboardTheme theme = searchKeyboardThemeById(id, KEYBOARD_THEMES);\n if (theme != null) {\n availableThemeList.add(theme);\n }\n }\n AVAILABLE_KEYBOARD_THEMES = availableThemeList.toArray(\n new KeyboardTheme[availableThemeList.size()]);\n Arrays.sort(AVAILABLE_KEYBOARD_THEMES);\n }\n return AVAILABLE_KEYBOARD_THEMES;\n }\n\n /* package private for testing */\n static KeyboardTheme getKeyboardTheme(final SharedPreferences prefs, final int sdkVersion,\n final KeyboardTheme[] availableThemeArray) {\n final String lxxThemeIdString = prefs.getString(LXX_KEYBOARD_THEME_KEY, null);\n if (lxxThemeIdString == null) {\n return getDefaultKeyboardTheme(prefs, sdkVersion, availableThemeArray);\n }\n try {\n final int themeId = Integer.parseInt(lxxThemeIdString);\n final KeyboardTheme theme = searchKeyboardThemeById(themeId, availableThemeArray);\n if (theme != null) {\n return theme;\n }\n Log.w(TAG, \"Unknown keyboard theme in LXX preference: \" + lxxThemeIdString);\n } catch (final NumberFormatException e) {\n Log.w(TAG, \"Illegal keyboard theme in LXX preference: \" + lxxThemeIdString, e);\n }\n // Remove preference that contains unknown or illegal theme id.\n prefs.edit().remove(LXX_KEYBOARD_THEME_KEY).apply();\n return getDefaultKeyboardTheme(prefs, sdkVersion, availableThemeArray);\n }\n}", "public final class AudioAndHapticFeedbackManager {\n private AudioManager mAudioManager;\n private Vibrator mVibrator;\n\n private SettingsValues mSettingsValues;\n private boolean mSoundOn;\n\n private static final AudioAndHapticFeedbackManager sInstance =\n new AudioAndHapticFeedbackManager();\n\n public static AudioAndHapticFeedbackManager getInstance() {\n return sInstance;\n }\n\n private AudioAndHapticFeedbackManager() {\n // Intentional empty constructor for singleton.\n }\n\n public static void init(final Context context) {\n sInstance.initInternal(context);\n }\n\n private void initInternal(final Context context) {\n mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);\n }\n\n public boolean hasVibrator() {\n return mVibrator != null && mVibrator.hasVibrator();\n }\n\n public void vibrate(final long milliseconds) {\n if (mVibrator == null) {\n return;\n }\n mVibrator.vibrate(milliseconds);\n }\n\n private boolean reevaluateIfSoundIsOn() {\n if (mSettingsValues == null || !mSettingsValues.mSoundOn || mAudioManager == null) {\n return false;\n }\n return mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;\n }\n\n public void performAudioFeedback(final int code) {\n // if mAudioManager is null, we can't play a sound anyway, so return\n if (mAudioManager == null) {\n return;\n }\n if (!mSoundOn) {\n return;\n }\n final int sound;\n switch (code) {\n case Constants.CODE_DELETE:\n sound = AudioManager.FX_KEYPRESS_DELETE;\n break;\n case Constants.CODE_ENTER:\n sound = AudioManager.FX_KEYPRESS_RETURN;\n break;\n case Constants.CODE_SPACE:\n sound = AudioManager.FX_KEYPRESS_SPACEBAR;\n break;\n default:\n sound = AudioManager.FX_KEYPRESS_STANDARD;\n break;\n }\n mAudioManager.playSoundEffect(sound, mSettingsValues.mKeypressSoundVolume);\n }\n\n public void performHapticFeedback(final View viewToPerformHapticFeedbackOn) {\n if (!mSettingsValues.mVibrateOn) {\n return;\n }\n if (mSettingsValues.mKeypressVibrationDuration >= 0) {\n vibrate(mSettingsValues.mKeypressVibrationDuration);\n return;\n }\n // Go ahead with the system default\n if (viewToPerformHapticFeedbackOn != null) {\n viewToPerformHapticFeedbackOn.performHapticFeedback(\n HapticFeedbackConstants.KEYBOARD_TAP,\n HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);\n }\n }\n\n public void onSettingsChanged(final SettingsValues settingsValues) {\n mSettingsValues = settingsValues;\n mSoundOn = reevaluateIfSoundIsOn();\n }\n\n public void onRingerModeChanged() {\n mSoundOn = reevaluateIfSoundIsOn();\n }\n}", "public final class InputAttributes {\n private final String TAG = InputAttributes.class.getSimpleName();\n\n final public String mTargetApplicationPackageName;\n final public boolean mInputTypeNoAutoCorrect;\n final public boolean mIsPasswordField;\n final public boolean mShouldShowSuggestions;\n final public boolean mApplicationSpecifiedCompletionOn;\n final public boolean mShouldInsertSpacesAutomatically;\n /**\n * Whether the floating gesture preview should be disabled. If true, this should override the\n * corresponding keyboard settings preference, always suppressing the floating preview text.\n */\n final private int mInputType;\n\n public InputAttributes(final EditorInfo editorInfo, final boolean isFullscreenMode) {\n mTargetApplicationPackageName = null != editorInfo ? editorInfo.packageName : null;\n final int inputType = null != editorInfo ? editorInfo.inputType : 0;\n final int inputClass = inputType & InputType.TYPE_MASK_CLASS;\n mInputType = inputType;\n mIsPasswordField = InputTypeUtils.isPasswordInputType(inputType)\n || InputTypeUtils.isVisiblePasswordInputType(inputType);\n if (inputClass != InputType.TYPE_CLASS_TEXT) {\n // If we are not looking at a TYPE_CLASS_TEXT field, the following strange\n // cases may arise, so we do a couple sanity checks for them. If it's a\n // TYPE_CLASS_TEXT field, these special cases cannot happen, by construction\n // of the flags.\n if (null == editorInfo) {\n Log.w(TAG, \"No editor info for this field. Bug?\");\n } else if (InputType.TYPE_NULL == inputType) {\n // TODO: We should honor TYPE_NULL specification.\n Log.i(TAG, \"InputType.TYPE_NULL is specified\");\n } else if (inputClass == 0) {\n // TODO: is this check still necessary?\n Log.w(TAG, String.format(\"Unexpected input class: inputType=0x%08x\"\n + \" imeOptions=0x%08x\", inputType, editorInfo.imeOptions));\n }\n mShouldShowSuggestions = false;\n mInputTypeNoAutoCorrect = false;\n mApplicationSpecifiedCompletionOn = false;\n mShouldInsertSpacesAutomatically = false;\n return;\n }\n // inputClass == InputType.TYPE_CLASS_TEXT\n final int variation = inputType & InputType.TYPE_MASK_VARIATION;\n final boolean flagNoSuggestions =\n 0 != (inputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);\n final boolean flagMultiLine =\n 0 != (inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE);\n final boolean flagAutoCorrect =\n 0 != (inputType & InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);\n final boolean flagAutoComplete =\n 0 != (inputType & InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);\n\n // TODO: Have a helper method in InputTypeUtils\n // Make sure that passwords are not displayed in {@link SuggestionStripView}.\n final boolean shouldSuppressSuggestions = mIsPasswordField\n || InputTypeUtils.isEmailVariation(variation)\n || InputType.TYPE_TEXT_VARIATION_URI == variation\n || InputType.TYPE_TEXT_VARIATION_FILTER == variation\n || flagNoSuggestions\n || flagAutoComplete;\n mShouldShowSuggestions = !shouldSuppressSuggestions;\n\n mShouldInsertSpacesAutomatically = InputTypeUtils.isAutoSpaceFriendlyType(inputType);\n\n // If it's a browser edit field and auto correct is not ON explicitly, then\n // disable auto correction, but keep suggestions on.\n // If NO_SUGGESTIONS is set, don't do prediction.\n // If it's not multiline and the autoCorrect flag is not set, then don't correct\n mInputTypeNoAutoCorrect =\n (variation == InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT && !flagAutoCorrect)\n || flagNoSuggestions\n || (!flagAutoCorrect && !flagMultiLine);\n\n mApplicationSpecifiedCompletionOn = flagAutoComplete && isFullscreenMode;\n }\n\n public boolean isTypeNull() {\n return InputType.TYPE_NULL == mInputType;\n }\n\n public boolean isSameInputType(final EditorInfo editorInfo) {\n return editorInfo.inputType == mInputType;\n }\n\n // Pretty print\n @Override\n public String toString() {\n return String.format(\n \"%s: inputType=0x%08x%s%s%s%s%s targetApp=%s\\n\", getClass().getSimpleName(),\n mInputType,\n (mInputTypeNoAutoCorrect ? \" noAutoCorrect\" : \"\"),\n (mIsPasswordField ? \" password\" : \"\"),\n (mShouldShowSuggestions ? \" shouldShowSuggestions\" : \"\"),\n (mApplicationSpecifiedCompletionOn ? \" appSpecified\" : \"\"),\n (mShouldInsertSpacesAutomatically ? \" insertSpaces\" : \"\"),\n mTargetApplicationPackageName);\n }\n\n public static boolean inPrivateImeOptions(final String packageName, final String key,\n final EditorInfo editorInfo) {\n if (editorInfo == null) return false;\n final String findingKey = (packageName != null) ? packageName + \".\" + key : key;\n return StringUtils.containsInCommaSplittableText(findingKey, editorInfo.privateImeOptions);\n }\n}", "public final class AdditionalSubtypeUtils {\n private static final String TAG = AdditionalSubtypeUtils.class.getSimpleName();\n\n private static final InputMethodSubtype[] EMPTY_SUBTYPE_ARRAY = new InputMethodSubtype[0];\n\n private AdditionalSubtypeUtils() {\n // This utility class is not publicly instantiable.\n }\n\n private static final String LOCALE_AND_LAYOUT_SEPARATOR = \":\";\n private static final int INDEX_OF_LOCALE = 0;\n private static final int INDEX_OF_KEYBOARD_LAYOUT = 1;\n private static final int INDEX_OF_EXTRA_VALUE = 2;\n private static final int LENGTH_WITHOUT_EXTRA_VALUE = (INDEX_OF_KEYBOARD_LAYOUT + 1);\n private static final int LENGTH_WITH_EXTRA_VALUE = (INDEX_OF_EXTRA_VALUE + 1);\n private static final String PREF_SUBTYPE_SEPARATOR = \";\";\n\n private static InputMethodSubtype createAdditionalSubtypeInternal(\n final String localeString, final String keyboardLayoutSetName,\n final boolean isAsciiCapable) {\n final int nameId = SubtypeLocaleUtils.getSubtypeNameId(localeString, keyboardLayoutSetName);\n final String platformVersionDependentExtraValues = getPlatformVersionDependentExtraValue(keyboardLayoutSetName, isAsciiCapable);\n final int platformVersionIndependentSubtypeId =\n getPlatformVersionIndependentSubtypeId(localeString, keyboardLayoutSetName);\n // NOTE: In KitKat and later, InputMethodSubtypeBuilder#setIsAsciiCapable is also available.\n // TODO: Use InputMethodSubtypeBuilder#setIsAsciiCapable when appropriate.\n return InputMethodSubtypeCompatUtils.newInputMethodSubtype(nameId,\n R.drawable.ic_ime_switcher_dark, localeString, KEYBOARD_MODE,\n platformVersionDependentExtraValues,\n false /* isAuxiliary */, false /* overrideImplicitlyEnabledSubtype */,\n platformVersionIndependentSubtypeId);\n }\n\n public static InputMethodSubtype createDummyAdditionalSubtype(\n final String localeString, final String keyboardLayoutSetName) {\n return createAdditionalSubtypeInternal(localeString, keyboardLayoutSetName,\n false /* isAsciiCapable */);\n }\n\n public static InputMethodSubtype createAsciiEmojiCapableAdditionalSubtype(\n final String localeString, final String keyboardLayoutSetName) {\n return createAdditionalSubtypeInternal(localeString, keyboardLayoutSetName,\n true /* isAsciiCapable */);\n }\n\n public static String getPrefSubtype(final InputMethodSubtype subtype) {\n final String localeString = subtype.getLocale();\n final String keyboardLayoutSetName = SubtypeLocaleUtils.getKeyboardLayoutSetName(subtype);\n final String layoutExtraValue = KEYBOARD_LAYOUT_SET + \"=\" + keyboardLayoutSetName;\n final String extraValue = StringUtils.removeFromCommaSplittableTextIfExists(\n layoutExtraValue, StringUtils.removeFromCommaSplittableTextIfExists(\n IS_ADDITIONAL_SUBTYPE, subtype.getExtraValue()));\n final String basePrefSubtype = localeString + LOCALE_AND_LAYOUT_SEPARATOR\n + keyboardLayoutSetName;\n return extraValue.isEmpty() ? basePrefSubtype\n : basePrefSubtype + LOCALE_AND_LAYOUT_SEPARATOR + extraValue;\n }\n\n public static InputMethodSubtype[] createAdditionalSubtypesArray(final String prefSubtypes) {\n if (TextUtils.isEmpty(prefSubtypes)) {\n return EMPTY_SUBTYPE_ARRAY;\n }\n final String[] prefSubtypeArray = prefSubtypes.split(PREF_SUBTYPE_SEPARATOR);\n final ArrayList<InputMethodSubtype> subtypesList = new ArrayList<>(prefSubtypeArray.length);\n for (final String prefSubtype : prefSubtypeArray) {\n final String elems[] = prefSubtype.split(LOCALE_AND_LAYOUT_SEPARATOR);\n if (elems.length != LENGTH_WITHOUT_EXTRA_VALUE\n && elems.length != LENGTH_WITH_EXTRA_VALUE) {\n Log.w(TAG, \"Unknown additional subtype specified: \" + prefSubtype + \" in \"\n + prefSubtypes);\n continue;\n }\n final String localeString = elems[INDEX_OF_LOCALE];\n final String keyboardLayoutSetName = elems[INDEX_OF_KEYBOARD_LAYOUT];\n // Here we assume that all the additional subtypes have AsciiCapable and EmojiCapable.\n // This is actually what the setting dialog for additional subtype is doing.\n final InputMethodSubtype subtype = createAsciiEmojiCapableAdditionalSubtype(\n localeString, keyboardLayoutSetName);\n if (subtype.getNameResId() == SubtypeLocaleUtils.UNKNOWN_KEYBOARD_LAYOUT) {\n // Skip unknown keyboard layout subtype. This may happen when predefined keyboard\n // layout has been removed.\n continue;\n }\n subtypesList.add(subtype);\n }\n return subtypesList.toArray(new InputMethodSubtype[subtypesList.size()]);\n }\n\n public static String createPrefSubtypes(final InputMethodSubtype[] subtypes) {\n if (subtypes == null || subtypes.length == 0) {\n return \"\";\n }\n final StringBuilder sb = new StringBuilder();\n for (final InputMethodSubtype subtype : subtypes) {\n if (sb.length() > 0) {\n sb.append(PREF_SUBTYPE_SEPARATOR);\n }\n sb.append(getPrefSubtype(subtype));\n }\n return sb.toString();\n }\n\n public static String createPrefSubtypes(final String[] prefSubtypes) {\n if (prefSubtypes == null || prefSubtypes.length == 0) {\n return \"\";\n }\n final StringBuilder sb = new StringBuilder();\n for (final String prefSubtype : prefSubtypes) {\n if (sb.length() > 0) {\n sb.append(PREF_SUBTYPE_SEPARATOR);\n }\n sb.append(prefSubtype);\n }\n return sb.toString();\n }\n\n /**\n * Returns the extra value that is optimized for the running OS.\n * <p>\n * Historically the extra value has been used as the last resort to annotate various kinds of\n * attributes. Some of these attributes are valid only on some platform versions. Thus we cannot\n * assume that the extra values stored in a persistent storage are always valid. We need to\n * regenerate the extra value on the fly instead.\n * </p>\n * @param keyboardLayoutSetName the keyboard layout set name (e.g., \"dvorak\").\n * @param isAsciiCapable true when ASCII characters are supported with this layout.\n * @return extra value that is optimized for the running OS.\n * @see #getPlatformVersionIndependentSubtypeId(String, String)\n */\n private static String getPlatformVersionDependentExtraValue(final String keyboardLayoutSetName, final boolean isAsciiCapable) {\n final ArrayList<String> extraValueItems = new ArrayList<>();\n extraValueItems.add(KEYBOARD_LAYOUT_SET + \"=\" + keyboardLayoutSetName);\n if (isAsciiCapable) {\n extraValueItems.add(ASCII_CAPABLE);\n }\n extraValueItems.add(IS_ADDITIONAL_SUBTYPE);\n return TextUtils.join(\",\", extraValueItems);\n }\n\n /**\n * Returns the subtype ID that is supposed to be compatible between different version of OSes.\n * <p>\n * From the compatibility point of view, it is important to keep subtype id predictable and\n * stable between different OSes. For this purpose, the calculation code in this method is\n * carefully chosen and then fixed. Treat the following code as no more or less than a\n * hash function. Each component to be hashed can be different from the corresponding value\n * that is used to instantiate {@link InputMethodSubtype} actually.\n * For example, you don't need to update <code>compatibilityExtraValueItems</code> in this\n * method even when we need to add some new extra values for the actual instance of\n * {@link InputMethodSubtype}.\n * </p>\n * @param localeString the locale string (e.g., \"en_US\").\n * @param keyboardLayoutSetName the keyboard layout set name (e.g., \"dvorak\").\n * @return a platform-version independent subtype ID.\n */\n private static int getPlatformVersionIndependentSubtypeId(final String localeString,\n final String keyboardLayoutSetName) {\n // For compatibility reasons, we concatenate the extra values in the following order.\n // - KeyboardLayoutSet\n // - AsciiCapable\n // - UntranslatableReplacementStringInSubtypeName\n // - EmojiCapable\n // - isAdditionalSubtype\n final ArrayList<String> compatibilityExtraValueItems = new ArrayList<>();\n compatibilityExtraValueItems.add(KEYBOARD_LAYOUT_SET + \"=\" + keyboardLayoutSetName);\n compatibilityExtraValueItems.add(ASCII_CAPABLE);\n if (SubtypeLocaleUtils.isExceptionalLocale(localeString)) {\n compatibilityExtraValueItems.add(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME + \"=\" +\n SubtypeLocaleUtils.getKeyboardLayoutSetDisplayName(keyboardLayoutSetName));\n }\n compatibilityExtraValueItems.add(IS_ADDITIONAL_SUBTYPE);\n final String compatibilityExtraValues = TextUtils.join(\",\", compatibilityExtraValueItems);\n return Arrays.hashCode(new Object[] {\n localeString,\n KEYBOARD_MODE,\n compatibilityExtraValues,\n false /* isAuxiliary */,\n false /* overrideImplicitlyEnabledSubtype */ });\n }\n}", "public final class ResourceUtils {\n private static final String TAG = ResourceUtils.class.getSimpleName();\n\n public static final float UNDEFINED_RATIO = -1.0f;\n public static final int UNDEFINED_DIMENSION = -1;\n\n private ResourceUtils() {\n // This utility class is not publicly instantiable.\n }\n\n private static final HashMap<String, String> sDeviceOverrideValueMap = new HashMap<>();\n\n private static final String[] BUILD_KEYS_AND_VALUES = {\n \"HARDWARE\", Build.HARDWARE,\n \"MODEL\", Build.MODEL,\n \"BRAND\", Build.BRAND,\n \"MANUFACTURER\", Build.MANUFACTURER\n };\n private static final HashMap<String, String> sBuildKeyValues;\n private static final String sBuildKeyValuesDebugString;\n\n static {\n sBuildKeyValues = new HashMap<>();\n final ArrayList<String> keyValuePairs = new ArrayList<>();\n final int keyCount = BUILD_KEYS_AND_VALUES.length / 2;\n for (int i = 0; i < keyCount; i++) {\n final int index = i * 2;\n final String key = BUILD_KEYS_AND_VALUES[index];\n final String value = BUILD_KEYS_AND_VALUES[index + 1];\n sBuildKeyValues.put(key, value);\n keyValuePairs.add(key + '=' + value);\n }\n sBuildKeyValuesDebugString = \"[\" + TextUtils.join(\" \", keyValuePairs) + \"]\";\n }\n\n public static String getDeviceOverrideValue(final Resources res, final int overrideResId,\n final String defaultValue) {\n final int orientation = res.getConfiguration().orientation;\n final String key = overrideResId + \"-\" + orientation;\n if (sDeviceOverrideValueMap.containsKey(key)) {\n return sDeviceOverrideValueMap.get(key);\n }\n\n final String[] overrideArray = res.getStringArray(overrideResId);\n final String overrideValue = findConstantForKeyValuePairs(sBuildKeyValues, overrideArray);\n // The overrideValue might be an empty string.\n if (overrideValue != null) {\n Log.i(TAG, \"Find override value:\"\n + \" resource=\"+ res.getResourceEntryName(overrideResId)\n + \" build=\" + sBuildKeyValuesDebugString\n + \" override=\" + overrideValue);\n sDeviceOverrideValueMap.put(key, overrideValue);\n return overrideValue;\n }\n\n sDeviceOverrideValueMap.put(key, defaultValue);\n return defaultValue;\n }\n\n @SuppressWarnings(\"serial\")\n static class DeviceOverridePatternSyntaxError extends Exception {\n public DeviceOverridePatternSyntaxError(final String message, final String expression) {\n this(message, expression, null);\n }\n\n public DeviceOverridePatternSyntaxError(final String message, final String expression,\n final Throwable throwable) {\n super(message + \": \" + expression, throwable);\n }\n }\n\n /**\n * Find the condition that fulfills specified key value pairs from an array of\n * \"condition,constant\", and return the corresponding string constant. A condition is\n * \"pattern1[:pattern2...] (or an empty string for the default). A pattern is\n * \"key=regexp_value\" string. The condition matches only if all patterns of the condition\n * are true for the specified key value pairs.\n *\n * For example, \"condition,constant\" has the following format.\n * - HARDWARE=mako,constantForNexus4\n * - MODEL=Nexus 4:MANUFACTURER=LGE,constantForNexus4\n * - ,defaultConstant\n *\n * @param keyValuePairs attributes to be used to look for a matched condition.\n * @param conditionConstantArray an array of \"condition,constant\" elements to be searched.\n * @return the constant part of the matched \"condition,constant\" element. Returns null if no\n * condition matches.\n * @see com.vlath.keyboard.latin.utils.ResourceUtilsTests#testFindConstantForKeyValuePairsRegexp()\n */\n @UsedForTesting\n static String findConstantForKeyValuePairs(final HashMap<String, String> keyValuePairs,\n final String[] conditionConstantArray) {\n if (conditionConstantArray == null || keyValuePairs == null) {\n return null;\n }\n String foundValue = null;\n for (final String conditionConstant : conditionConstantArray) {\n final int posComma = conditionConstant.indexOf(',');\n if (posComma < 0) {\n Log.w(TAG, \"Array element has no comma: \" + conditionConstant);\n continue;\n }\n final String condition = conditionConstant.substring(0, posComma);\n if (condition.isEmpty()) {\n Log.w(TAG, \"Array element has no condition: \" + conditionConstant);\n continue;\n }\n try {\n if (fulfillsCondition(keyValuePairs, condition)) {\n // Take first match\n if (foundValue == null) {\n foundValue = conditionConstant.substring(posComma + 1);\n }\n // And continue walking through all conditions.\n }\n } catch (final DeviceOverridePatternSyntaxError e) {\n Log.w(TAG, \"Syntax error, ignored\", e);\n }\n }\n return foundValue;\n }\n\n private static boolean fulfillsCondition(final HashMap<String,String> keyValuePairs,\n final String condition) throws DeviceOverridePatternSyntaxError {\n final String[] patterns = condition.split(\":\");\n // Check all patterns in a condition are true\n boolean matchedAll = true;\n for (final String pattern : patterns) {\n final int posEqual = pattern.indexOf('=');\n if (posEqual < 0) {\n throw new DeviceOverridePatternSyntaxError(\"Pattern has no '='\", condition);\n }\n final String key = pattern.substring(0, posEqual);\n final String value = keyValuePairs.get(key);\n if (value == null) {\n throw new DeviceOverridePatternSyntaxError(\"Unknown key\", condition);\n }\n final String patternRegexpValue = pattern.substring(posEqual + 1);\n try {\n if (!value.matches(patternRegexpValue)) {\n matchedAll = false;\n // And continue walking through all patterns.\n }\n } catch (final PatternSyntaxException e) {\n throw new DeviceOverridePatternSyntaxError(\"Syntax error\", condition, e);\n }\n }\n return matchedAll;\n }\n\n public static int getDefaultKeyboardWidth(final Resources res) {\n final DisplayMetrics dm = res.getDisplayMetrics();\n return dm.widthPixels;\n }\n\n public static int getKeyboardHeight(final Resources res, final SettingsValues settingsValues) {\n final int defaultKeyboardHeight = getDefaultKeyboardHeight(res);\n if (settingsValues.mHasKeyboardResize) {\n // mKeyboardHeightScale Ranges from [.5,1.2], from xml/prefs_screen_debug.xml\n return (int)(defaultKeyboardHeight * settingsValues.mKeyboardHeightScale);\n }\n return defaultKeyboardHeight;\n }\n\n public static int getDefaultKeyboardHeight(final Resources res) {\n final DisplayMetrics dm = res.getDisplayMetrics();\n final float keyboardHeight = res.getDimension(R.dimen.config_default_keyboard_height);\n final float maxKeyboardHeight = res.getFraction(\n R.fraction.config_max_keyboard_height, dm.heightPixels, dm.heightPixels);\n float minKeyboardHeight = res.getFraction(\n R.fraction.config_min_keyboard_height, dm.heightPixels, dm.heightPixels);\n if (minKeyboardHeight < 0.0f) {\n // Specified fraction was negative, so it should be calculated against display\n // width.\n minKeyboardHeight = -res.getFraction(\n R.fraction.config_min_keyboard_height, dm.widthPixels, dm.widthPixels);\n }\n // Keyboard height will not exceed maxKeyboardHeight and will not be less than\n // minKeyboardHeight.\n return (int)Math.max(Math.min(keyboardHeight, maxKeyboardHeight), minKeyboardHeight);\n }\n\n public static boolean isValidFraction(final float fraction) {\n return fraction >= 0.0f;\n }\n\n // {@link Resources#getDimensionPixelSize(int)} returns at least one pixel size.\n public static boolean isValidDimensionPixelSize(final int dimension) {\n return dimension > 0;\n }\n\n public static float getFloatFromFraction(final Resources res, final int fractionResId) {\n return res.getFraction(fractionResId, 1, 1);\n }\n\n public static float getFraction(final TypedArray a, final int index, final float defValue) {\n final TypedValue value = a.peekValue(index);\n if (value == null || !isFractionValue(value)) {\n return defValue;\n }\n return a.getFraction(index, 1, 1, defValue);\n }\n\n public static float getFraction(final TypedArray a, final int index) {\n return getFraction(a, index, UNDEFINED_RATIO);\n }\n\n public static int getDimensionPixelSize(final TypedArray a, final int index) {\n final TypedValue value = a.peekValue(index);\n if (value == null || !isDimensionValue(value)) {\n return ResourceUtils.UNDEFINED_DIMENSION;\n }\n return a.getDimensionPixelSize(index, ResourceUtils.UNDEFINED_DIMENSION);\n }\n\n public static float getDimensionOrFraction(final TypedArray a, final int index, final int base,\n final float defValue) {\n final TypedValue value = a.peekValue(index);\n if (value == null) {\n return defValue;\n }\n if (isFractionValue(value)) {\n return a.getFraction(index, base, base, defValue);\n } else if (isDimensionValue(value)) {\n return a.getDimension(index, defValue);\n }\n return defValue;\n }\n\n public static int getEnumValue(final TypedArray a, final int index, final int defValue) {\n final TypedValue value = a.peekValue(index);\n if (value == null) {\n return defValue;\n }\n if (isIntegerValue(value)) {\n return a.getInt(index, defValue);\n }\n return defValue;\n }\n\n public static boolean isFractionValue(final TypedValue v) {\n return v.type == TypedValue.TYPE_FRACTION;\n }\n\n public static boolean isDimensionValue(final TypedValue v) {\n return v.type == TypedValue.TYPE_DIMENSION;\n }\n\n public static boolean isIntegerValue(final TypedValue v) {\n return v.type >= TypedValue.TYPE_FIRST_INT && v.type <= TypedValue.TYPE_LAST_INT;\n }\n\n public static boolean isStringValue(final TypedValue v) {\n return v.type == TypedValue.TYPE_STRING;\n }\n}", "public abstract class RunInLocale<T> {\n private static final Object sLockForRunInLocale = new Object();\n\n protected abstract T job(final Resources res);\n\n /**\n * Execute {@link #job(Resources)} method in specified system locale exclusively.\n *\n * @param res the resources to use.\n * @param newLocale the locale to change to. Run in system locale if null.\n * @return the value returned from {@link #job(Resources)}.\n */\n public T runInLocale(final Resources res, final Locale newLocale) {\n synchronized (sLockForRunInLocale) {\n final Configuration conf = res.getConfiguration();\n if (newLocale == null || newLocale.equals(conf.locale)) {\n return job(res);\n }\n final Locale savedLocale = conf.locale;\n try {\n conf.locale = newLocale;\n res.updateConfiguration(conf, null);\n return job(res);\n } finally {\n conf.locale = savedLocale;\n res.updateConfiguration(conf, null);\n }\n }\n }\n}" ]
import com.vlath.keyboard.latin.AudioAndHapticFeedbackManager; import com.vlath.keyboard.latin.InputAttributes; import com.vlath.keyboard.latin.utils.AdditionalSubtypeUtils; import com.vlath.keyboard.latin.utils.ResourceUtils; import com.vlath.keyboard.latin.utils.RunInLocale; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Color; import android.preference.PreferenceManager; import androidx.annotation.NonNull; import android.util.Log; import java.util.Locale; import java.util.concurrent.locks.ReentrantLock; import com.vlath.keyboard.R; import com.vlath.keyboard.keyboard.KeyboardTheme;
private final ReentrantLock mSettingsValuesLock = new ReentrantLock(); private static final Settings sInstance = new Settings(); public static Settings getInstance() { return sInstance; } public static void init(final Context context) { sInstance.onCreate(context); } private Settings() { // Intentional empty constructor for singleton. } private void onCreate(final Context context) { mContext = context; mRes = context.getResources(); mPrefs = PreferenceManager.getDefaultSharedPreferences(context); mPrefs.registerOnSharedPreferenceChangeListener(this); } public void onDestroy() { mPrefs.unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) { mSettingsValuesLock.lock(); try { if (mSettingsValues == null) { // TODO: Introduce a static function to register this class and ensure that // loadSettings must be called before "onSharedPreferenceChanged" is called. Log.w(TAG, "onSharedPreferenceChanged called before loadSettings."); return; } loadSettings(mContext, mSettingsValues.mLocale, mSettingsValues.mInputAttributes); } finally { mSettingsValuesLock.unlock(); } } public void loadSettings(final Context context, final Locale locale, @NonNull final InputAttributes inputAttributes) { mSettingsValuesLock.lock(); mContext = context; try { final SharedPreferences prefs = mPrefs; final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() { @Override protected SettingsValues job(final Resources res) { return new SettingsValues(prefs, res, inputAttributes); } }; mSettingsValues = job.runInLocale(mRes, locale); } finally { mSettingsValuesLock.unlock(); } } // TODO: Remove this method and add proxy method to SettingsValues. public SettingsValues getCurrent() { return mSettingsValues; } // Accessed from the settings interface, hence public public static boolean readKeypressSoundEnabled(final SharedPreferences prefs, final Resources res) { return prefs.getBoolean(PREF_SOUND_ON, res.getBoolean(R.bool.config_default_sound_enabled)); } public static boolean readVibrationEnabled(final SharedPreferences prefs, final Resources res) { final boolean hasVibrator = AudioAndHapticFeedbackManager.getInstance().hasVibrator(); return hasVibrator && prefs.getBoolean(PREF_VIBRATE_ON, res.getBoolean(R.bool.config_default_vibration_enabled)); } public static boolean readFromBuildConfigIfToShowKeyPreviewPopupOption(final Resources res) { return res.getBoolean(R.bool.config_enable_show_key_preview_popup_option); } public static boolean readKeyPreviewPopupEnabled(final SharedPreferences prefs, final Resources res) { final boolean defaultKeyPreviewPopup = res.getBoolean( R.bool.config_default_key_preview_popup); if (!readFromBuildConfigIfToShowKeyPreviewPopupOption(res)) { return defaultKeyPreviewPopup; } return prefs.getBoolean(PREF_POPUP_ON, defaultKeyPreviewPopup); } public static int readKeyPreviewPopupDismissDelay(final SharedPreferences prefs, final Resources res) { return Integer.parseInt(prefs.getString(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY, Integer.toString(res.getInteger( R.integer.config_key_preview_linger_timeout)))); } public static boolean readShowsLanguageSwitchKey(final SharedPreferences prefs) { return !prefs.getBoolean(PREF_HIDE_LANGUAGE_SWITCH_KEY, false); } public static boolean readHideSpecialChars(final SharedPreferences prefs) { return prefs.getBoolean(PREF_HIDE_SPECIAL_CHARS, false); } public static boolean readShowNumberRow(final SharedPreferences prefs) { return prefs.getBoolean(PREF_SHOW_NUMBER_ROW, false); } public static boolean readSpaceSwipeEnabled(final SharedPreferences prefs) { return prefs.getBoolean(PREF_SPACE_SWIPE, true); } public static String readPrefAdditionalSubtypes(final SharedPreferences prefs, final Resources res) {
final String predefinedPrefSubtypes = AdditionalSubtypeUtils.createPrefSubtypes(
3
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/OldInputDialog.java
[ "public class CharSequenceUtil {\r\n\tprivate CharSequenceUtil() {}\r\n\t\r\n\tpublic static CharSequence shorten(final CharSequence seq, final int maxLength) {\r\n\t\tint length = seq.length();\r\n\t\tif (length < maxLength) {\r\n\t\t\treturn seq;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tint endLength = maxLength / 3;\r\n\t\t\tint startLength = maxLength - endLength - 1;\r\n\t\t\treturn seq.subSequence(0, startLength).toString() + '\\u2026' + seq.subSequence(length - endLength, length);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static CharSequence toUpperCase(final CharSequence seq) {\r\n\t\treturn new TransformingCharSequence(seq, UPPER_CASE);\r\n\t}\r\n\t\r\n\tpublic static CharSequence toLowerCase(final CharSequence seq) {\r\n\t\treturn new TransformingCharSequence(seq, LOWER_CASE);\r\n\t}\r\n\t\r\n\tpublic static CharSequence complement(final CharSequence seq) {\r\n\t\treturn new TransformingCharSequence(seq, COMPLEMENT);\r\n\t}\r\n\t\r\n\tpublic static CharSequence reverseComplement(final CharSequence seq) {\r\n\t\tfinal int maxIndex = seq.length() - 1;\r\n\t\tCharSequenceTransformer transformer = new ComplementTransformer() {\r\n\t\t\t@Override\r\n\t\t\tpublic int transformIndex(int index) {\r\n\t\t\t\treturn maxIndex - index;\r\n\t\t\t}\r\n\t\t};\r\n\t\treturn new TransformingCharSequence(seq, transformer);\r\n\t}\r\n\r\n\tprivate static final CharSequenceTransformer UPPER_CASE = new CharSequenceTransformer() {\r\n\t\tpublic char transformChar(char c) {\r\n\t\t\treturn Character.toUpperCase(c);\r\n\t\t}\r\n\t};\r\n\r\n\tprivate static final CharSequenceTransformer LOWER_CASE = new CharSequenceTransformer() {\r\n\t\tpublic char transformChar(char c) {\r\n\t\t\treturn Character.toLowerCase(c);\r\n\t\t}\r\n\t};\r\n\r\n\tprivate static final CharSequenceTransformer COMPLEMENT = new ComplementTransformer();\r\n\t\r\n\tprivate static class CharSequenceTransformer {\r\n\t\tpublic char transformChar(char c) {\r\n\t\t\treturn c;\r\n\t\t}\r\n\t\t\r\n\t\tpublic int transformIndex(int index) {\r\n\t\t\treturn index;\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate static class ComplementTransformer extends CharSequenceTransformer {\r\n\t\tpublic char transformChar(char c) {\r\n\t\t\tchar upper = Character.toUpperCase(c);\r\n\t\t\tchar complement = transformUppercase(upper);\r\n\t\t\treturn c == upper ? complement : Character.toLowerCase(complement); \r\n\t\t}\r\n\t\t\r\n\t\tprivate char transformUppercase(char c) {\t\r\n\t\t\tswitch (c) {\r\n\t\t\t\tcase 'A': return 'T';\r\n\t\t\t\tcase 'T': return 'A';\r\n\t\t\t\tcase 'U': return 'A';\r\n\t\t\t\tcase 'G': return 'C';\r\n\t\t\t\tcase 'C': return 'G';\r\n\t\t\t\tcase 'Y': return 'R';\r\n\t\t\t\tcase 'R': return 'Y';\r\n\t\t\t\tcase 'S': return 'S';\r\n\t\t\t\tcase 'W': return 'W';\r\n\t\t\t\tcase 'K': return 'M';\r\n\t\t\t\tcase 'M': return 'K';\r\n\t\t\t\tcase 'B': return 'V';\r\n\t\t\t\tcase 'D': return 'H';\r\n\t\t\t\tcase 'H': return 'D';\r\n\t\t\t\tcase 'V': return 'B';\r\n\t\t\t\tcase 'N': return 'N';\t\r\n\t\t\t\tdefault: return c;\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\t\r\n\tprivate static class TransformingCharSequence implements CharSequence {\r\n\t\tprivate final CharSequence baseSeq;\r\n\t\tprivate final CharSequenceTransformer transformer;\r\n\t\t\r\n\t\tpublic TransformingCharSequence(CharSequence baseSeq, CharSequenceTransformer transformer) {\r\n\t this.baseSeq = baseSeq;\r\n\t this.transformer = transformer;\r\n }\r\n\r\n\t\t@Override\r\n public char charAt(int index) {\r\n\t\t\tint newIndex = transformer.transformIndex(index);\r\n\t char ch = baseSeq.charAt(newIndex);\r\n\t\t\treturn transformer.transformChar(ch);\r\n }\r\n\r\n\t\t@Override\r\n public int length() {\r\n\t return baseSeq.length();\r\n }\r\n\r\n\t\t@Override\r\n public CharSequence subSequence(int start, int end) {\r\n\t\t\tint newStart = transformer.transformIndex(start);\r\n\t\t\tint newEnd = transformer.transformIndex(end);\r\n\t\t\tCharSequence newBaseSeq = baseSeq.subSequence(newStart, newEnd);\r\n\t return new TransformingCharSequence(newBaseSeq, transformer);\r\n }\r\n\r\n\t\t@Override\r\n public String toString() {\r\n\t\t\tint length = length();\r\n\t StringBuilder sb = new StringBuilder(length);\r\n\t for (int i = 0; i < length; i++) {\r\n\t \tsb.append(charAt(i));\r\n\t }\r\n\t return sb.toString();\r\n }\r\n\t\t\r\n\t}\r\n\r\n\tpublic static String toTitleCase(String input) {\r\n\t\tStringBuilder titleCase = new StringBuilder();\r\n\t\tboolean nextTitleCase = true;\r\n\t\r\n\t\tfor (int i = 0; i < input.length(); i++) {\r\n\t\t\tchar c = input.charAt(i);\r\n\t\t\tif (Character.isSpaceChar(c)) {\r\n\t\t\t\tnextTitleCase = true;\r\n\t\t\t}\r\n\t\t\telse if (nextTitleCase) {\r\n\t\t\t\tc = Character.toTitleCase(c);\r\n\t\t\t\tnextTitleCase = false;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tc = Character.toLowerCase(c);\r\n\t\t\t}\r\n\t\r\n\t\t\ttitleCase.append(c);\r\n\t\t}\r\n\t\r\n\t\treturn titleCase.toString();\r\n\t}\r\n}\r", "public class Registries implements Iterable<Registry> {\n\tprivate static Registries INSTANCE;\n\n\tpublic static Registries get() {\n\t\tif (INSTANCE == null) {\n\t\t\tINSTANCE = new Registries();\n\t\t}\n\n\t\treturn INSTANCE;\n\t}\n\n\tprivate final List<Registry> registries;\n\tprivate int partRegistryIndex;\n\tprivate int versionRegistryIndex;\n\tprivate boolean isModified = false;\n\n\tprivate Registries() {\n\t\tregistries = Lists.newArrayList();\n\t\tPreferences prefs = Preferences.userNodeForPackage(Registries.class).node(\"registries\");\n\t\t// try {\n\t\t// prefs.clear();\n\t\t// } catch (BackingStoreException e) {\n\t\t// e.printStackTrace();\n\t\t// }\n\t\tint registryCount = prefs.getInt(\"size\", 0);\n\t\tfor (int i = 0; i < registryCount; i++) {\n\t\t\tPreferences child = prefs.node(\"registry\" + i);\n\t\t\tString name = child.get(\"name\", null);\n\t\t\tString desc = child.get(\"description\", null);\n\t\t\tString location = child.get(\"location\", null);\n\t\t\tString uriPrefix = child.get(\"uriPrefix\", null);\n\t\t\ttry {\n\t\t\t\t// if (url.startsWith(\"jar:\") || url.startsWith(\"file:\")) {\n\t\t\t\t// registries.add(Registry.BUILT_IN);\n\t\t\t\t// }\n\t\t\t\t// else {\n\t\t\t\tregistries.add(new Registry(name, desc, location, uriPrefix));\n\t\t\t\t// }\n\t\t\t} catch (Exception e) {\n\t\t\t\t// e.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\tif (registries.isEmpty()) {\n\t\t\trestoreDefaults();\n\t\t} else {\n\t\t\tpartRegistryIndex = prefs.getInt(\"partRegistry\", 0);\n\t\t\tif (!isValidIndex(partRegistryIndex)) {\n\t\t\t\tpartRegistryIndex = 0;\n\t\t\t}\n\n\t\t\tversionRegistryIndex = prefs.getInt(\"versionRegistry\", 0);\n\t\t\tif (!isValidIndex(versionRegistryIndex)) {\n\t\t\t\tversionRegistryIndex = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void restoreDefaults() {\n\t\tregistries.clear();\n\t\tregistries.add(Registry.BUILT_IN);\n\t\tregistries.add(Registry.WORKING_DOCUMENT);\n\t\tpartRegistryIndex = 1;\n\t\tversionRegistryIndex = 1;\n\t\tisModified = true;\n\t\tsave();\n\t}\n\n\tpublic void save() {\n\t\tif (!isModified) {\n\t\t\treturn;\n\t\t}\n\t\tisModified = false;\n\n\t\tPreferences prefs = Preferences.userNodeForPackage(Registries.class).node(\"registries\");\n\t\ttry {\n\t\t\tprefs.removeNode();\n\t\t} catch (BackingStoreException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tprefs = Preferences.userNodeForPackage(Registries.class).node(\"registries\");\n\t\tint size = registries.size();\n\t\tprefs.putInt(\"size\", size);\n\t\tprefs.putInt(\"partRegistry\", partRegistryIndex);\n\t\tprefs.putInt(\"versionRegistry\", versionRegistryIndex);\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tRegistry registry = registries.get(i);\n\t\t\tPreferences child = prefs.node(\"registry\" + i);\n\t\t\tchild.put(\"name\", registry.getName());\n\t\t\tchild.put(\"description\", registry.getDescription());\n\t\t\tchild.put(\"location\", registry.getLocation());\n\t\t\tchild.put(\"uriPrefix\", registry.getUriPrefix());\n\t\t}\n\t}\n\n\tprivate boolean isValidIndex(int index) {\n\t\treturn index >= 0 && index < registries.size();\n\t}\n\n\tpublic Iterator<Registry> iterator() {\n\t\treturn registries.iterator();\n\t}\n\n\tpublic int size() {\n\t\treturn registries.size();\n\t}\n\n\tpublic void setPartRegistryIndex(int index) {\n\t\tPreconditions.checkArgument(isValidIndex(index));\n\t\tif (partRegistryIndex != index) {\n\t\t\tpartRegistryIndex = index;\n\t\t\tisModified = true;\n\t\t}\n\t}\n\n\tpublic int getPartRegistryIndex() {\n\t\treturn partRegistryIndex;\n\t}\n\n\tpublic void setVersionRegistryIndex(int index) {\n\t\tPreconditions.checkArgument(isValidIndex(index));\n\t\tif (versionRegistryIndex != index) {\n\t\t\tversionRegistryIndex = index;\n\t\t\tisModified = true;\n\t\t}\n\t}\n\n\tpublic int getVersionRegistryIndex() {\n\t\treturn versionRegistryIndex;\n\t}\n\n\tpublic void add(Registry registry) {\n\t\tregistries.add(registry);\n\t\tisModified = true;\n\t}\n\n\tpublic Registry get(int index) {\n\t\treturn registries.get(index);\n\t}\n\n\tpublic void remove(int index) {\n\t\tPreconditions.checkArgument(isValidIndex(index));\n\t\tregistries.remove(index);\n\t\tpartRegistryIndex = updateIndex(partRegistryIndex, index);\n\t\tversionRegistryIndex = updateIndex(versionRegistryIndex, index);\n\t\tisModified = true;\n\t}\n\n\tprivate int updateIndex(int index, int removedIndex) {\n\t\treturn (partRegistryIndex == index) ? 0 : (partRegistryIndex > index) ? index - 1 : index;\n\t}\n}", "public class Registry implements Serializable {\r\n\tprivate final String name;\r\n\tprivate final String description;\r\n\tprivate final String location;\r\n\tprivate final String uriPrefix;\r\n\r\n\tpublic static final Registry BUILT_IN = new Registry(\"Built-in parts\",\r\n\t\t\t\"Built-in parts obtained from the iGEM registry\", \"N/A\", \"N/A\");\r\n\r\n\tpublic static final Registry WORKING_DOCUMENT = new Registry(\"Working document\",\r\n\t\t\t\"The current file you are working in\", \"N/A\", \"N/A\");\r\n\r\n\tpublic Registry(String name, String description, String location, String uriPrefix) {\r\n\t\tPreconditions.checkNotNull(name, \"Name cannot be null\");\r\n\t\tPreconditions.checkNotNull(location, \"URL/Path cannot be null\");\r\n\t\tthis.name = name;\r\n\t\tthis.description = description;\r\n\t\tthis.location = location;\r\n\t\tthis.uriPrefix = uriPrefix;\r\n\t}\r\n\r\n\tpublic String getName() {\r\n\t\treturn name;\r\n\t}\r\n\r\n\tpublic String getDescription() {\r\n\t\treturn description;\r\n\t}\r\n\r\n\tpublic String getLocation() {\r\n\t\treturn location;\r\n\t}\r\n\r\n\t/**\r\n\t * @return the uriPrefix\r\n\t */\r\n\tpublic String getUriPrefix() {\r\n\t\treturn uriPrefix;\r\n\t}\r\n\r\n\tpublic boolean isPath() {\r\n\t\treturn !location.startsWith(\"http://\") && !location.startsWith(\"https://\");\r\n\t}\r\n\t\r\n\t/**\r\n\t * Checks to see if the registry we are working on is represented by\r\n\t * IdentifiedMetadata.\r\n\t */\r\n\tpublic boolean isMetadata() {\r\n\t\treturn location.startsWith(\"http://\") || location.startsWith(\"https://\");\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj)\r\n\t\t\treturn true;\r\n\t\tif (!(obj instanceof Registry))\r\n\t\t\treturn false;\r\n\t\tRegistry that = (Registry) obj;\r\n\t\treturn this.location.equals(that.location) && this.name.equals(that.name);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((location == null) ? 0 : location.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn name + \" (\" + location + \")\";\r\n\t}\r\n}\r", "public abstract class AbstractListTableModel<T> extends AbstractTableModel {\r\n\tprivate final String[] columns;\r\n\tprivate final double[] widths;\r\n\tprivate List<T> elements;\r\n\r\n\tpublic AbstractListTableModel(List<T> components, String[] columns, double[] widths) {\r\n\t\tsuper();\r\n\t\tthis.elements = components;\r\n\t\tthis.columns = columns;\r\n\t\tthis.widths = widths;\r\n\t}\r\n\r\n\tpublic double[] getWidths() {\r\n\t\treturn widths;\r\n\t}\r\n\r\n\tpublic void setElements(List<T> components) {\r\n\t\tthis.elements = components;\r\n\t\tfireTableDataChanged();\r\n\t}\r\n\r\n\tpublic int getColumnCount() {\r\n\t\treturn columns.length;\r\n\t}\r\n\r\n\tpublic int getRowCount() {\r\n\t\treturn elements.size();\r\n\t}\r\n\r\n\tpublic String getColumnName(int col) {\r\n\t\treturn columns[col];\r\n\t}\r\n\r\n\tpublic T getElement(int row) {\r\n\t\treturn elements.get(row);\r\n\t}\r\n\r\n\tpublic Class<?> getColumnClass(int col) {\r\n\t\treturn Object.class;\r\n\t}\r\n\r\n\tpublic boolean isCellEditable(int row, int col) {\r\n\t\treturn false;\r\n\t}\r\n\r\n\tpublic Object getValueAt(int row, int col) {\r\n\t\tT element = getElement(row);\r\n\t\treturn getField(element, col);\r\n\t}\r\n\r\n\tprotected abstract Object getField(T element, int field);\r\n}", "public class ComboBoxRenderer<T> extends JLabel implements ListCellRenderer {\r\n\tpublic ComboBoxRenderer() {\r\n\t\tsetOpaque(true);\r\n\t\tsetHorizontalAlignment(LEFT);\r\n\t\tsetVerticalAlignment(CENTER);\r\n\t}\r\n\r\n\tpublic Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,\r\n\t boolean cellHasFocus) {\r\n\t\tif (isSelected || (index == list.getSelectedIndex())) {\r\n\t\t\tsetBackground(list.getSelectionBackground());\r\n\t\t\tsetForeground(list.getSelectionForeground());\r\n\t\t}\r\n\t\telse {\r\n\t\t\tsetBackground(list.getBackground());\r\n\t\t\tsetForeground(list.getForeground());\r\n\t\t}\r\n\r\n\t\t@SuppressWarnings(\"unchecked\")\r\n T item = (T) value;\r\n\t\tif (item == null) {\r\n\t\t\tsetText(\"\");\r\n\t\t\tsetToolTipText(\"\");\r\n\t\t\tsetIcon(null);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tsetText(getLabel(item));\r\n\t\t\tsetToolTipText(getToolTip(item));\r\n\t\t\t\r\n\t\t\tIcon icon = getImage(item);\r\n\t\t\tboolean isExpanded = (index != -1);\r\n\t\t\tif (isExpanded || !isOnlyExpandedIcon()) {\r\n\t\t\t\tsetIcon(icon);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tsetIcon(null);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t}\r\n\t\r\n\tprotected String getLabel(T item) {\r\n\t\treturn item.toString();\r\n\t}\r\n\t\r\n\tprotected String getToolTip(T item) {\r\n\t\treturn \"\";\r\n\t}\r\n\t\r\n\tprotected Icon getImage(T item) {\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tprotected boolean isOnlyExpandedIcon() {\r\n\t\treturn true;\r\n\t}\r\n}", "public class FormBuilder {\r\n\tprivate JPanel panel = new JPanel(new SpringLayout());\t\r\n\t\r\n\tpublic JPanel build() {\t\r\n\t\tint cols = 2;\r\n\t\tint rows = panel.getComponentCount() / 2;\r\n\t\tint initX = 6, initY = 6;\r\n\t\tint padX = 6, padY = 6;\r\n\t\tmakeCompactGrid(panel, rows, cols, initX, initY, padX, padY);\r\n\t\t\r\n\t\treturn panel;\r\n\t}\r\n\t\r\n\tpublic void add(String labelText, JComponent component) {\r\n JLabel label = new JLabel(labelText, JLabel.TRAILING);\r\n label.setVerticalTextPosition(SwingConstants.TOP);\r\n label.setLabelFor(component);\r\n panel.add(label);\r\n panel.add(component);\r\n\t}\r\n\t\r\n\tpublic void add(String label, JTextComponent component, String value) {\r\n \tcomponent.setText(value);\r\n \tadd(label, component);\r\n\t}\r\n\t\r\n\tpublic JTextField addTextField(String label, String value) {\r\n\t\tJTextField field = new JTextField(); \t\r\n \tadd(label, field, value);\r\n \treturn field;\r\n\t}\r\n\t\r\n\tpublic JTextArea addTextArea(String label, String value) {\r\n\t\tJTextArea field = new JTextArea(); \r\n\t\tfield.setLineWrap(true);\r\n\t\t\r\n\t\tJScrollPane scroller = new JScrollPane(field);\r\n\t\tscroller.setPreferredSize(new Dimension(350, 75));\r\n\t\tscroller.setAlignmentX(Component.LEFT_ALIGNMENT);\t\t\r\n\t\t\r\n\t\tadd(label, scroller);\r\n \t\r\n \treturn field;\r\n\t}\r\n\r\n\t\r\n\tpublic JPasswordField addPasswordField(String label, String value) {\r\n\t\tJPasswordField field = new JPasswordField(); \t\r\n \tadd(label, field, value);\r\n \treturn field;\r\n\t}\r\n\r\n\tpublic void add(String label, JComponent... components) {\r\n\t\tJComponent component;\r\n\t\tif (components.length == 1) {\r\n\t\t\tcomponent = components[0];\r\n\t\t}\r\n\t\telse {\r\n\t\t\tBox box = Box.createHorizontalBox();\r\n\t\t\tfor (JComponent c : components) {\r\n\t\t\t\tbox.add(c);\r\n\t\t\t}\r\n\t\t\tcomponent = box;\r\n\t\t}\r\n\t\tadd(label, component);\r\n\t}\t\r\n\r\n /* Used by makeCompactGrid. */\r\n private static SpringLayout.Constraints getConstraintsForCell(\r\n int row, int col,\r\n Container parent,\r\n int cols) {\r\n SpringLayout layout = (SpringLayout) parent.getLayout();\r\n Component c = parent.getComponent(row * cols + col);\r\n return layout.getConstraints(c);\r\n }\r\n \r\n /**\r\n * Aligns the first <code>rows</code> * <code>cols</code>\r\n * components of <code>parent</code> in\r\n * a grid. Each component in a column is as wide as the maximum\r\n * preferred width of the components in that column;\r\n * height is similarly determined for each row.\r\n * The parent is made just big enough to fit them all.\r\n *\r\n * @param rows number of rows\r\n * @param cols number of columns\r\n * @param initialX x location to start the grid at\r\n * @param initialY y location to start the grid at\r\n * @param xPad x padding between cells\r\n * @param yPad y padding between cells\r\n */\r\n public static void makeCompactGrid(Container parent,\r\n int rows, int cols,\r\n int initialX, int initialY,\r\n int xPad, int yPad) {\r\n SpringLayout layout;\r\n try {\r\n layout = (SpringLayout)parent.getLayout();\r\n } catch (ClassCastException exc) {\r\n System.err.println(\"The first argument to makeCompactGrid must use SpringLayout.\");\r\n return;\r\n }\r\n \r\n //Align all cells in each column and make them the same width.\r\n Spring x = Spring.constant(initialX);\r\n for (int c = 0; c < cols; c++) {\r\n Spring width = Spring.constant(0);\r\n for (int r = 0; r < rows; r++) {\r\n width = Spring.max(width,\r\n getConstraintsForCell(r, c, parent, cols).\r\n getWidth());\r\n }\r\n for (int r = 0; r < rows; r++) {\r\n SpringLayout.Constraints constraints =\r\n getConstraintsForCell(r, c, parent, cols);\r\n constraints.setX(x);\r\n constraints.setWidth(width);\r\n }\r\n x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));\r\n }\r\n \r\n //Align all cells in each row and make them the same height.\r\n Spring y = Spring.constant(initialY);\r\n for (int r = 0; r < rows; r++) {\r\n Spring height = Spring.constant(0);\r\n for (int c = 0; c < cols; c++) {\r\n height = Spring.max(height,\r\n getConstraintsForCell(r, c, parent, cols).\r\n getHeight());\r\n }\r\n for (int c = 0; c < cols; c++) {\r\n SpringLayout.Constraints constraints =\r\n getConstraintsForCell(r, c, parent, cols);\r\n constraints.setY(y);\r\n constraints.setHeight(height);\r\n }\r\n y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));\r\n }\r\n \r\n //Set the parent's size.\r\n SpringLayout.Constraints pCons = layout.getConstraints(parent);\r\n pCons.setConstraint(SpringLayout.SOUTH, y);\r\n pCons.setConstraint(SpringLayout.EAST, x);\r\n }\r\n}\r" ]
import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import edu.utah.ece.async.sboldesigner.sbol.CharSequenceUtil; import edu.utah.ece.async.sboldesigner.sbol.editor.Registries; import edu.utah.ece.async.sboldesigner.sbol.editor.Registry; import edu.utah.ece.async.sboldesigner.swing.AbstractListTableModel; import edu.utah.ece.async.sboldesigner.swing.ComboBoxRenderer; import edu.utah.ece.async.sboldesigner.swing.FormBuilder;
/* * Copyright (c) 2012 - 2015, Clark & Parsia, LLC. <http://www.clarkparsia.com> * * 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 edu.utah.ece.async.sboldesigner.sbol.editor.dialog; /** * * @author Evren Sirin */ public abstract class OldInputDialog<T> extends JDialog { protected enum RegistryType { PART, VERSION, NONE } private final ComboBoxRenderer<Registry> registryRenderer = new ComboBoxRenderer<Registry>() { @Override protected String getLabel(Registry registry) { StringBuilder sb = new StringBuilder(); if (registry != null) { sb.append(registry.getName()); if (!registry.equals(Registry.BUILT_IN) && !registry.equals(Registry.WORKING_DOCUMENT)) { sb.append(" ("); sb.append(CharSequenceUtil.shorten(registry.getLocation(), 30)); sb.append(")"); } } return sb.toString(); } @Override protected String getToolTip(Registry registry) { return registry == null ? "" : registry.getDescription(); } }; private final ActionListener actionListener = new DialogActionListener(); private RegistryType registryType; private JComboBox registrySelection; private JButton cancelButton, selectButton, optionsButton; private FormBuilder builder = new FormBuilder(); protected boolean canceled = true; protected OldInputDialog(final Component parent, String title, RegistryType registryType) { super(JOptionPane.getFrameForComponent(parent), title, true); this.registryType = registryType; if (registryType != RegistryType.NONE) {
Registries registries = Registries.get();
1
andrewflynn/bettersettlers
app/src/main/java/com/nut/bettersettlers/logic/MapLogic.java
[ "public static final int[] PROBABILITY_MAPPING = {\n\t0, // 0\n 0, // 1\n 1, // 2\n 2, // 3\n 3, // 4\n 4, // 5\n 5, // 6\n 0, // 7\n 5, // 8\n 4, // 9\n 3, // 10\n 2, // 11\n 1 // 12\n};", "public final class CatanMap {\n\t/** The name of this map. */\n\tpublic final String name;\n\t\n\t/** The display title of this map. */\n\tpublic final String title;\n\n\t/** How many rocks/clays there are available on to distribute. */\n\tpublic final int lowResourceNumber;\n\n\t/** How many wheats/woods/sheep there are available on to distribute. */\n\tpublic final int highResourceNumber;\n\n\t/** The assigned probability for each point (if it exists). */\n\tpublic final int[] landGridProbabilities;\n\n\t/** The assigned resource for each point (if it exists). */\n\tpublic final Resource[] landGridResources;\n\n\t/** The (x,y) coordinates of the each land hexagon. */\n\tpublic final Point[] landGrid;\n\n\t/** The list of whitelists for each point (if it exists). */\n\tpublic final String[] landGridWhitelists;\n\n\t/** The whitelist of resources that can be on a certain land grid piece */\n\tpublic final Map<String, List<Resource>> landResourceWhitelists;\n\n\t/** The whitelist of probabilities that can be on a certain land grid piece */\n\tpublic final Map<String, List<Integer>> landProbabilityWhitelists;\n\n\t/** The order in which the land grid is laid out. */\n\tpublic final int[] landGridOrder;\n\n\t/** The (x,y) coordinates of each water hexagon. */\n\tpublic final Point[] waterGrid;\n\n\t/**\n\t * This list contains 2 or 3 numbers that are the possible corners that the lines can go to\n\t * (half only touch two at 2 corners and half touch at 3 corners). 0 is the TL corner, 1\n\t * is the top corner, 2 is the TR corner, and so forth clockwise around the hexagon to 5 (BL).\n\t */\n\tpublic final int[][] harborLines;\n\n\t/**\n\t * This list of lists contains the land tiles that each land tile is neighbors with.\n\t * The land tiles are numbered 0-18 starting at the TL corner and going L -> R, T -> B.\n\t */\n\tpublic final int[][] landNeighbors;\n\n\t/**\n\t * This list of lists contains the land tiles that each ocean tile is neighbors with.\n\t * The ocean tiles are (similar to everywhere else) numbered starting at the TL ocean\n\t * tile and going around clockwise 0-17. The land tiles are (similar to everywhere else)\n\t * numbered 0-18 starting at the TL land tile and going L -> R, T -> B.\n\t * Note that the numbers are not small to large but are numbered clockwise by whichever land\n\t * tile is earliest on in the clockwise rotation (starting in the TL corner).\n\t */\n\tpublic final int[][] waterNeighbors;\n\n\t/**\n\t * This list of list is like waterNeighbors except it contains the ocean tiles each ocean tile\n\t * is neighbors with (not including itself)\n\t */\n\tpublic final int[][] waterWaterNeighbors;\n\n\t/**\n\t * \"Triplets\" are defined as three terrain tiles that come together at an intersection\n\t * (ports do not count). These are ordered starting in the TL corner going L -> R, T -> B\n\t * (going straight across such that the top three terrain tiles are the \"top two\" for the\n\t * first triplets. These are defined so that we can make sure no single settlement placement\n\t * is too amazing.\n\t */\n\tpublic final int[][] landIntersections;\n\n\t/** This is a mapping between STANDARD_LAND_GRID and STANDARD_LAND_INTERSECTIONS. */\n\tpublic final int[][] landIntersectionIndexes;\n\n\t/** \n\t * This is a way to identify places in between the hexes. This is not a unique mapping, but\n\t * the X represents which hex its referring to and the Y represents which direction off of\n\t * the hex its pointing.\n\t */\n\tpublic final int[][] placementIndexes;\n\n\t/** List of how many of each resource this type of board contains. */\n\tpublic final Resource[] availableResources;\n\n\t/** List of how many of each probability this type of board contains. */\n\tpublic final int[] availableProbabilities;\n\n\t/** List of how many of each probability this type of board contains. */\n\tpublic final int[] availableOrderedProbabilities;\n\n\t/** List of how many of harbors there are (desert is 3:1). */\n\tpublic final Resource[] availableHarbors;\n\n\t/** Hardcoded directions of harbors on \"traditional\" maps. Hardcoded since they're weird. */\n\tpublic final int[] orderedHarbors;\n\n\t/** The (x,y) coordinates of the each unknown hexagon. */\n\tpublic final Point[] unknownGrid;\n\n\t/** List of how many of each resource this type of board contains for unknown only. */\n\tpublic final Resource[] availableUnknownResources;\n\n\t/** List of how many of each probability this type of board contains for unknown only. */\n\tpublic final int[] availableUnknownProbabilities;\n\n\t/** List of which placement degrees around each piece are disallowed. Null if no blacklist. */\n\tpublic final List<int[]> placementBlacklists;\n\n\t/** Order of any land converted to water so we can keep the same map for New World on a rotation. */\n\tpublic final ArrayList<Integer> theftOrder;\n\t\n\tprivate CatanMap(Builder builder) {\n\t\tthis.name = builder.name;\n\t\tthis.title = builder.title;\n\t\tthis.lowResourceNumber = builder.lowResourceNumber;\n\t\tthis.highResourceNumber = builder.highResourceNumber;\n\t\tthis.landGridProbabilities = builder.landGridProbabilities;\n\t\tthis.landGridResources = builder.landGridResources;\n\t\tthis.landGrid = builder.landGrid;\n\t\tthis.landGridWhitelists = builder.landGridWhitelists;\n\t\tthis.landResourceWhitelists = builder.landResourceWhitelists;\n\t\tthis.landProbabilityWhitelists = builder.landProbabilityWhitelists;\n\t\tthis.landGridOrder = builder.landGridOrder;\n\t\tthis.waterGrid = builder.waterGrid;\n\t\tthis.harborLines = builder.harborLines;\n\t\tthis.landNeighbors = builder.landNeighbors;\n\t\tthis.waterNeighbors = builder.waterNeighbors;\n\t\tthis.waterWaterNeighbors = builder.waterWaterNeighbors;\n\t\tthis.landIntersections = builder.landIntersections;\n\t\tthis.landIntersectionIndexes = builder.landIntersectionIndexes;\n\t\tthis.placementIndexes = builder.placementIndexes;\n\t\tthis.availableResources = builder.availableResources;\n\t\tthis.availableProbabilities = builder.availableProbabilities;\n\t\tthis.availableOrderedProbabilities = builder.availableOrderedProbabilities;\n\t\tthis.availableHarbors = builder.availableHarbors;\n\t\tthis.orderedHarbors = builder.orderedHarbors;\n\t\tthis.unknownGrid = builder.unknownGrid;\n\t\tthis.availableUnknownResources = builder.availableUnknownResources;\n\t\tthis.availableUnknownProbabilities = builder.availableUnknownProbabilities;\n\t\tthis.placementBlacklists = builder.placementBlacklists;\n\t\tthis.theftOrder = builder.theftOrder;\n\t}\n\t\n\t@Override\n\tpublic boolean equals(Object other) {\n\t\tif (this == other) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!(other instanceof CatanMap)) {\n\t\t\treturn false;\n\t\t}\n\t\tCatanMap that = (CatanMap) other;\n\t\t\n\t\treturn Util.equal(this.name, that.name)\n\t\t && Util.equal(this.title, that.title)\n\t\t && Util.equal(this.lowResourceNumber, that.lowResourceNumber)\n\t\t && Util.equal(this.highResourceNumber, that.highResourceNumber)\n\t\t && Util.equal(this.landGridProbabilities, that.landGridProbabilities)\n\t\t && Util.equal(this.landGridResources, that.landGridResources)\n\t\t && Util.equal(this.landGrid, that.landGrid)\n\t\t && Util.equal(this.landGridWhitelists, that.landGridWhitelists)\n\t\t && Util.equal(this.landResourceWhitelists, that.landResourceWhitelists)\n\t\t && Util.equal(this.landProbabilityWhitelists, that.landProbabilityWhitelists)\n\t\t && Util.equal(this.landGridOrder, that.landGridOrder)\n\t\t && Util.equal(this.waterGrid, that.waterGrid)\n\t\t && Util.equal(this.harborLines, that.harborLines)\n\t\t && Util.equal(this.landNeighbors, that.landNeighbors)\n\t\t && Util.equal(this.waterNeighbors, that.waterNeighbors)\n\t\t && Util.equal(this.waterWaterNeighbors, that.waterWaterNeighbors)\n\t\t && Util.equal(this.landIntersections, that.landIntersections)\n\t\t && Util.equal(this.landIntersectionIndexes, that.landIntersectionIndexes)\n\t\t && Util.equal(this.placementIndexes, that.placementIndexes)\n\t\t && Util.equal(this.availableResources, that.availableResources)\n\t\t && Util.equal(this.availableProbabilities, that.availableProbabilities)\n\t\t && Util.equal(this.availableOrderedProbabilities, that.availableOrderedProbabilities)\n\t\t && Util.equal(this.availableHarbors, that.availableHarbors)\n\t\t && Util.equal(this.orderedHarbors, that.orderedHarbors)\n\t\t && Util.equal(this.unknownGrid, that.unknownGrid)\n\t\t && Util.equal(this.availableUnknownResources, that.availableUnknownResources)\n\t\t && Util.equal(this.availableUnknownProbabilities, that.availableUnknownProbabilities)\n\t\t && Util.equal(this.placementBlacklists, that.placementBlacklists)\n\t\t && Util.equal(this.theftOrder, that.theftOrder);\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Util.hashCode(name, title, lowResourceNumber, highResourceNumber,\n\t\t\t\tlandGridProbabilities, landGridResources, landGrid, landGridWhitelists,\n\t\t\t\tlandResourceWhitelists, landGridOrder, waterGrid, harborLines, landNeighbors,\n\t\t\t\twaterNeighbors, waterWaterNeighbors, landIntersections, landIntersectionIndexes,\n\t\t\t\tplacementIndexes, availableResources, availableProbabilities,\n\t\t\t\tavailableOrderedProbabilities, availableHarbors, orderedHarbors,\n\t\t\t\tunknownGrid, availableUnknownResources, availableUnknownProbabilities,\n\t\t\t\tplacementBlacklists, theftOrder);\n\t}\n\t\n\tprivate String deepToString(List<int[]> array) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"[ \");\n\t\tfor (int[] arr : array) {\n\t\t\tsb.append(Arrays.toString(arr)).append(\", \");\n\t\t}\n\t\tsb.append(\" ]\");\n\t\treturn sb.toString();\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"[Settlers Map: (\" + name + \")\" + \"\\n\" +\n\t\t\t\t\" Low Resource Number: \" + lowResourceNumber + \"\\n\" +\n\t\t\t\t\" High Resource Number: \" + highResourceNumber + \"\\n\" +\n\t\t\t\t\" Land Grid: \" + Arrays.toString(landGrid) + \"\\n\" +\n\t\t\t\t\" Land Grid Whitelist: \" + Arrays.toString(landGridWhitelists) + \"\\n\" +\n\t\t\t\t\" Land Grid Probabilities: \" + Arrays.toString(landGridProbabilities) + \"\\n\" +\n\t\t\t\t\" Land Grid Resources: \" + Arrays.toString(landGridResources) + \"\\n\" +\n\t\t\t\t\" Land Resource Whitelist: \" + landResourceWhitelists + \"\\n\" +\n\t\t\t\t\" Land Probability Whitelist: \" + landProbabilityWhitelists + \"\\n\" +\n\t\t\t\t\" Land Grid Order: \" + Arrays.toString(landGridOrder) + \"\\n\" +\n\t\t\t\t\" Water Grid: \" + Arrays.toString(waterGrid) + \"\\n\" +\n\t\t\t\t\" Harbor Lines: \" + Arrays.deepToString(harborLines) + \"\\n\" +\n\t\t\t\t\" Land Neighbors: \" + Arrays.deepToString(landNeighbors) + \"\\n\" +\n\t\t\t\t\" Water Neighbors: \" + Arrays.deepToString(waterNeighbors) + \"\\n\" +\n\t\t\t\t\" Water Water Neighbors: \" + Arrays.deepToString(waterWaterNeighbors) + \"\\n\" +\n\t\t\t\t\" Land Intersections: \" + Arrays.deepToString(landIntersections) + \"\\n\" +\n\t\t\t\t\" Land Intersections Size: \" + landIntersections.length + \"\\n\" +\n\t\t\t\t\" Land Intersection Indexes: \" + Arrays.deepToString(landIntersectionIndexes) + \"\\n\" +\n\t\t\t\t\" Placement Indexes: \" + Arrays.deepToString(placementIndexes) + \"\\n\" +\n\t\t\t\t\" Placement Indexes Size: \" + placementIndexes.length + \"\\n\" +\n\t\t\t\t\" Available Resources: \" + Arrays.toString(availableResources) + \"\\n\" +\n\t\t\t\t\" Available Probabilities: \" + Arrays.toString(availableProbabilities) + \"\\n\" +\n\t\t\t\t\" Available Ordered Probabilities: \" + Arrays.toString(availableOrderedProbabilities) + \"\\n\" +\n\t\t\t\t\" Available Harbors: \" + Arrays.toString(availableHarbors) + \"\\n\" +\n\t\t\t\t\" Ordered Harbors: \" + Arrays.toString(orderedHarbors) + \"\\n\" +\n\t\t\t\t\" Placement Blacklists: \" + deepToString(placementBlacklists) + \"\\n\" +\n\t\t\t\t\"]\";\n\t}\n\t\n\tpublic static Builder newBuilder() {\n\t\treturn new Builder();\n\t}\n\t\n\tpublic static class Builder {\n\t\tprivate String name;\n\t\tprivate String title;\n\t\tprivate int lowResourceNumber;\n\t\tprivate int highResourceNumber;\n\t\tprivate int[] landGridProbabilities;\n\t\tprivate Resource[] landGridResources;\n\t\tprivate Point[] landGrid;\n\t\tprivate String[] landGridWhitelists;\n\t\tprivate Map<String, List<Resource>> landResourceWhitelists;\n\t\tprivate Map<String, List<Integer>> landProbabilityWhitelists;\n\t\tprivate int[] landGridOrder;\n\t\tprivate Point[] waterGrid;\n\t\tprivate int[][] harborLines;\n\t\tprivate int[][] landNeighbors;\n\t\tprivate int[][] waterNeighbors;\n\t\tprivate int[][] waterWaterNeighbors;\n\t\tprivate int[][] landIntersections;\n\t\tprivate int[][] landIntersectionIndexes;\n\t\tprivate int[][] placementIndexes;\n\t\tprivate Resource[] availableResources;\n\t\tprivate int[] availableProbabilities;\n\t\tprivate int[] availableOrderedProbabilities;\n\t\tprivate Resource[] availableHarbors;\n\t\tprivate int[] orderedHarbors;\n\t\tprivate Point[] unknownGrid;\n\t\tprivate Resource[] availableUnknownResources;\n\t\tprivate int[] availableUnknownProbabilities;\n\t\tprivate List<int[]> placementBlacklists;\n\t\tprivate ArrayList<Integer> theftOrder;\n\t\t\n\t\tprivate Builder() {}\n\t\t\n\t\tpublic CatanMap build() {\n\t\t\treturn new CatanMap(this);\n\t\t}\n\t\t\n\t\tpublic String getName() {\n\t\t\treturn name;\n\t\t}\n\n\t\tpublic String getTitle() {\n\t\t\treturn title;\n\t\t}\n\n\t\tpublic int getLowResourceNumber() {\n\t\t\treturn lowResourceNumber;\n\t\t}\n\n\t\tpublic int getHighResourceNumber() {\n\t\t\treturn highResourceNumber;\n\t\t}\n\n\t\tpublic int[] getLandGridProbabilities() {\n\t\t\treturn landGridProbabilities;\n\t\t}\n\n\t\tpublic Resource[] getLandGridResources() {\n\t\t\treturn landGridResources;\n\t\t}\n\n\t\tpublic Point[] getLandGrid() {\n\t\t\treturn landGrid;\n\t\t}\n\n\t\tpublic String[] getLandGridWhitelists() {\n\t\t\treturn landGridWhitelists;\n\t\t}\n\n\t\tpublic Map<String, List<Resource>> getLandResourceWhitelists() {\n\t\t\treturn landResourceWhitelists;\n\t\t}\n\n\t\tpublic Map<String, List<Integer>> getLandProbabilityWhitelists() {\n\t\t\treturn landProbabilityWhitelists;\n\t\t}\n\n\t\tpublic int[] getLandGridOrder() {\n\t\t\treturn landGridOrder;\n\t\t}\n\n\t\tpublic Point[] getWaterGrid() {\n\t\t\treturn waterGrid;\n\t\t}\n\n\t\tpublic int[][] getHarborLines() {\n\t\t\treturn harborLines;\n\t\t}\n\n\t\tpublic int[][] getLandNeighbors() {\n\t\t\treturn landNeighbors;\n\t\t}\n\n\t\tpublic int[][] getWaterNeighbors() {\n\t\t\treturn waterNeighbors;\n\t\t}\n\n\t\tpublic int[][] getWaterWaterNeighbors() {\n\t\t\treturn waterWaterNeighbors;\n\t\t}\n\n\t\tpublic int[][] getLandIntersections() {\n\t\t\treturn landIntersections;\n\t\t}\n\n\t\tpublic int[][] getLandIntersectionIndexes() {\n\t\t\treturn landIntersectionIndexes;\n\t\t}\n\n\t\tpublic int[][] getPlacementIndexes() {\n\t\t\treturn placementIndexes;\n\t\t}\n\n\t\tpublic Resource[] getAvailableResources() {\n\t\t\treturn availableResources;\n\t\t}\n\n\t\tpublic int[] getAvailableProbabilities() {\n\t\t\treturn availableProbabilities;\n\t\t}\n\n\t\tpublic int[] getAvailableOrderedProbabilities() {\n\t\t\treturn availableOrderedProbabilities;\n\t\t}\n\n\t\tpublic Resource[] getAvailableHarbors() {\n\t\t\treturn availableHarbors;\n\t\t}\n\n\t\tpublic int[] getOrderedHarbors() {\n\t\t\treturn orderedHarbors;\n\t\t}\n\n\t\tpublic Point[] getUnknownGrid() {\n\t\t\treturn unknownGrid;\n\t\t}\n\n\t\tpublic Resource[] getAvailableUnknownResources() {\n\t\t\treturn availableUnknownResources;\n\t\t}\n\n\t\tpublic int[] getAvailableUnknownProbabilities() {\n\t\t\treturn availableUnknownProbabilities;\n\t\t}\n\n\t\tpublic List<int[]> getPlacementBlacklists() {\n\t\t\treturn placementBlacklists;\n\t\t}\n\n\t\tpublic ArrayList<Integer> getTheftOrder() {\n\t\t\treturn theftOrder;\n\t\t}\n\n\t\tpublic Builder setName(String name) {\n\t\t\tthis.name = name;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setTitle(String title) {\n\t\t\tthis.title = title;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setLowResourceNumber(int lowResourceNumber) {\n\t\t\tthis.lowResourceNumber = lowResourceNumber;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setHighResourceNumber(int highResourceNumber) {\n\t\t\tthis.highResourceNumber = highResourceNumber;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setLandGridProbabilities(int[] landGridProbabilities) {\n\t\t\tthis.landGridProbabilities = landGridProbabilities;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setLandGridResources(Resource[] landGridResources) {\n\t\t\tthis.landGridResources = landGridResources;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setLandGrid(Point[] landGrid) {\n\t\t\tthis.landGrid = landGrid;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setLandGridWhitelists(String[] landGridWhitelists) {\n\t\t\tthis.landGridWhitelists = landGridWhitelists;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setLandResourceWhitelists(\n\t\t\t\tMap<String, List<Resource>> landResourceWhitelists) {\n\t\t\tthis.landResourceWhitelists = landResourceWhitelists;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setLandProbabilityWhitelists(\n\t\t\t\tMap<String, List<Integer>> landProbabilityWhitelists) {\n\t\t\tthis.landProbabilityWhitelists = landProbabilityWhitelists;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setLandGridOrder(int[] landGridOrder) {\n\t\t\tthis.landGridOrder = landGridOrder;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setWaterGrid(Point[] waterGrid) {\n\t\t\tthis.waterGrid = waterGrid;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setHarborLines(int[][] harborLines) {\n\t\t\tthis.harborLines = harborLines;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setLandNeighbors(int[][] landNeighbors) {\n\t\t\tthis.landNeighbors = landNeighbors;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setWaterNeighbors(int[][] waterNeighbors) {\n\t\t\tthis.waterNeighbors = waterNeighbors;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setWaterWaterNeighbors(int[][] waterWaterNeighbors) {\n\t\t\tthis.waterWaterNeighbors = waterWaterNeighbors;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setLandIntersections(int[][] landIntersections) {\n\t\t\tthis.landIntersections = landIntersections;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setLandIntersectionIndexes(int[][] landIntersectionIndexes) {\n\t\t\tthis.landIntersectionIndexes = landIntersectionIndexes;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setPlacementIndexes(int[][] placementIndexes) {\n\t\t\tthis.placementIndexes = placementIndexes;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setAvailableResources(Resource[] availableResources) {\n\t\t\tthis.availableResources = availableResources;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setAvailableProbabilities(int[] availableProbabilities) {\n\t\t\tthis.availableProbabilities = availableProbabilities;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setAvailableOrderedProbabilities(int[] availableOrderedProbabilities) {\n\t\t\tthis.availableOrderedProbabilities = availableOrderedProbabilities;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setAvailableHarbors(Resource[] availableHarbors) {\n\t\t\tthis.availableHarbors = availableHarbors;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setOrderedHarbors(int[] orderedHarbors) {\n\t\t\tthis.orderedHarbors = orderedHarbors;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setUnknownGrid(Point[] unknownGrid) {\n\t\t\tthis.unknownGrid = unknownGrid;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setAvailableUnknownResources(Resource[] availableUnknownResources) {\n\t\t\tthis.availableUnknownResources = availableUnknownResources;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setAvailableUnknownProbabilities(int[] availableUnknownProbabilities) {\n\t\t\tthis.availableUnknownProbabilities = availableUnknownProbabilities;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setPlacementBlacklists(List<int[]> placementBlacklists) {\n\t\t\tthis.placementBlacklists = placementBlacklists;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setTheftOrder(ArrayList<Integer> theftOrder) {\n\t\t\tthis.theftOrder = theftOrder;\n\t\t\treturn this;\n\t\t}\n\t}\n}", "public final class Harbor implements Parcelable {\n\tpublic final int position;\n\tpublic final Resource resource;\n\tpublic final int facing;\n\t\n\tpublic Harbor(int position, Resource resource, int facing) {\n\t\tthis.position = position;\n\t\tthis.resource = resource;\n\t\tthis.facing = facing;\n\t}\n\t\n\tprivate Harbor(Parcel in) {\n\t\tposition = in.readInt();\n\t\tresource = in.readParcelable(getClass().getClassLoader());\n\t\tfacing = in.readInt();\n\t}\n\t\n\t@Override\n\tpublic boolean equals(Object other) {\n\t\tif (this == other) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!(other instanceof Harbor)) {\n\t\t\treturn false;\n\t\t}\n\t\tHarbor that = (Harbor) other;\n\t\t\n\t\treturn Util.equal(this.position, that.position)\n\t\t && Util.equal(this.resource, that.resource)\n\t\t && Util.equal(this.facing, that.facing);\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Util.hashCode(position, resource, facing);\n\t}\n\n public static final Parcelable.Creator<Harbor> CREATOR = new Parcelable.Creator<Harbor>() {\n public Harbor createFromParcel(Parcel in) {\n return new Harbor(in);\n }\n\n public Harbor[] newArray(int size) {\n return new Harbor[size];\n }\n };\n\t\n\t@Override\n\tpublic int describeContents() {\n return 0;\n }\n\n\t@Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeInt(position);\n out.writeParcelable(resource, flags);\n out.writeInt(facing);\n }\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"[Harbor:\" +\n\t\t\t\t\" position: \" + position +\n\t\t\t\t\" resource: \" + resource +\n\t\t\t\t\" facing: \" + facing +\n\t\t\t\t\" ]\"+ \"\\n\";\n\t}\n}", "public final class MapType {\n\tprivate MapType() {}\n\tpublic static final int TRADITIONAL = 0;\n\tpublic static final int FAIR = 1;\n\tpublic static final int RANDOM = 2;\n\t\n\tpublic static String getString(int mapType) {\n\t\tswitch (mapType) {\n\t\tcase TRADITIONAL:\n\t\t\treturn \"TRADITIONAL\";\n\t\tcase FAIR:\n\t\t\treturn \"FAIR\";\n\t\tcase RANDOM:\n\t\t\treturn \"RANDOM\";\n\t\tdefault:\n\t\t\treturn \"UNKNOWN\";\n\t\t}\n\t}\n}", "public final class NumberOfResource {\n\tprivate NumberOfResource() {}\n\tpublic static final int DESERT = 0;\n\tpublic static final int LOW = 1;\n\tpublic static final int HIGH = 2;\n\tpublic static final int WATER = 3;\n\tpublic static final int GOLD = 4;\n\t\n\tpublic static String getString(int numberOfResource) {\n\t\tswitch (numberOfResource) {\n\t\tcase DESERT:\n\t\t\treturn \"DESERT\";\n\t\tcase LOW:\n\t\t\treturn \"LOW\";\n\t\tcase HIGH:\n\t\t\treturn \"HIGH\";\n\t\tcase WATER:\n\t\t\treturn \"WATER\";\n\t\tcase GOLD:\n\t\t\treturn \"GOLD\";\n\t\tdefault:\n\t\t\treturn \"UNKNOWN\";\n\t\t}\n\t}\n}", "public enum Resource implements Parcelable {\n\tDESERT(0xFFf0dc82, NumberOfResource.DESERT, \"desert\"),\n\tWHEAT(0xFFfad111, NumberOfResource.HIGH, \"wheat\"),\n\tCLAY(0xFFb22222, NumberOfResource.LOW, \"clay\"),\n\tROCK(0xFF9e9e9e, NumberOfResource.LOW, \"rock\"),\n\tSHEEP(0xFF66ce5f, NumberOfResource.HIGH, \"sheep\"),\n\tWOOD(0xFF0c9302, NumberOfResource.HIGH, \"wood\"),\n\tWATER(0xFF00aeef, NumberOfResource.WATER, \"water\"),\n\tGOLD(0xFFAF7817, NumberOfResource.GOLD, \"gold\");\n\n\tprivate static final Map<String, Resource> JSON_KEY_MAP = new HashMap<>();\n\tstatic {\n\t\tfor (Resource resource : Resource.values()) {\n\t\t\tJSON_KEY_MAP.put(resource.jsonKey, resource);\n\t\t}\n\t}\n\tpublic static Resource getResourceByJson(String key) {\n\t\treturn JSON_KEY_MAP.get(key);\n\t}\n\t\n\tpublic final int color;\n\tpublic final int numOfResource;\n\tpublic final String jsonKey;\n\t\n\tResource(int color, int numOfResource, String jsonKey) {\n\t\tthis.color = color;\n\t\tthis.numOfResource = numOfResource;\n\t\tthis.jsonKey = jsonKey;\n\t}\n\n public static final Parcelable.Creator<Resource> CREATOR = new Parcelable.Creator<Resource>() {\n public Resource createFromParcel(Parcel in) {\n return Resource.values()[in.readInt()];\n }\n\n public Resource[] newArray(int size) {\n return new Resource[size];\n }\n };\n\t\n\t@Override\n\tpublic int describeContents() {\n return 0;\n }\n\n\t@Override\n public void writeToParcel(Parcel out, int flags) {\n\t\tout.writeInt(ordinal());\n }\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn jsonKey;\n\t}\n}" ]
import static com.nut.bettersettlers.util.Consts.PROBABILITY_MAPPING; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import com.nut.bettersettlers.data.CatanMap; import com.nut.bettersettlers.data.Harbor; import com.nut.bettersettlers.data.MapType; import com.nut.bettersettlers.data.NumberOfResource; import com.nut.bettersettlers.data.Resource;
Resource nextResource; if (nextProb == 0) { set.add(Resource.DESERT); placedRecently = true; continue; } else if (nextProb < -1 && whitelistName != null && allowedWhitelists.containsKey(whitelistName) && allowedWhitelists.get(whitelistName).contains(Resource.DESERT)) { // Special case deserts with probs set.add(Resource.DESERT); placedRecently = true; continue; } else if (currentMap.landGridResources[nextIndex] != null) { nextResource = currentMap.landGridResources[nextIndex]; // If we have an assigned resource, use it set.add(nextResource); resourceMap.get(nextResource).add(nextProb); avail.remove(nextResource); placedRecently = true; continue; } else { nextResource = avail.remove(RAND.nextInt(avail.size())); } //BetterLog.v("Consuming: " + nextResource); boolean canPlaceHere = true; // Check to see if there's a whitelist if (whitelistName != null && allowedWhitelists.containsKey(whitelistName) && !allowedWhitelists.get(whitelistName).contains(nextResource)) { canPlaceHere = false; } if (nextProb == -1 && canPlaceHere) { // Just use it set.add(nextResource); resourceMap.get(nextResource).add(nextProb); placedRecently = true; if (whitelistName != null && allowedWhitelists.containsKey(whitelistName)) { allowedWhitelists.get(whitelistName).remove(nextResource); } continue; } // Check neighbors for same resource. if (!currentMap.name.equals("the_pirate_islands") && !currentMap.name.equals("the_pirate_islands_exp")) { for (int neighbor : currentMap.landNeighbors[nextIndex]) { //BetterLog.v(" " + neighbor); if (neighbor >= set.size()) { // Do nothing, it is not yet occupied } else { if (set.get(neighbor) == nextResource) { canPlaceHere = false; break; } else { // Do nothing, at least this neighbor isn't the same } } } } // If this number is already used by the same resource if (resourceMap.get(nextResource).contains(nextProb) && !currentMap.name.equals("the_pirate_islands") && !currentMap.name.equals("the_pirate_islands_exp")) { canPlaceHere = false; } // No 6s or 8s on golds if (nextResource == Resource.GOLD && (probs.get(nextIndex) == 6 || probs.get(nextIndex) == 8)) { canPlaceHere = false; } // If this is the last resource, check the probs of this resource int numOfResource = nextResource.numOfResource; ArrayList<Integer> tmpProbs = new ArrayList<>(); tmpProbs.addAll(resourceMap.get(nextResource)); tmpProbs.add(nextProb); if (!tmpProbs.contains(-1)) { // Skip missing probs if (numOfResource == NumberOfResource.LOW && tmpProbs.size() == currentMap.lowResourceNumber) { if (sumProbability(tmpProbs) < 3*currentMap.lowResourceNumber || sumProbability(tmpProbs) > 4*currentMap.lowResourceNumber) { canPlaceHere = false; } if (!isBalanced(tmpProbs)) { canPlaceHere = false; } } else if (numOfResource == NumberOfResource.HIGH && tmpProbs.size() == currentMap.highResourceNumber) { if (sumProbability(tmpProbs) < 3*currentMap.highResourceNumber || sumProbability(tmpProbs) > 4*currentMap.highResourceNumber) { canPlaceHere = false; } } } if (canPlaceHere) { set.add(nextResource); resourceMap.get(nextResource).add(nextProb); placedRecently = true; if (whitelistName != null && allowedWhitelists.containsKey(whitelistName)) { allowedWhitelists.get(whitelistName).remove(nextResource); } } else { tried.add(nextResource); } } } // Check for deserts at the end while (set.size() < probs.size()) { set.add(Resource.DESERT); } //BetterLog.v("Finished: " + set); return set; }
public static ArrayList<Harbor> getHarbors(CatanMap currentMap, int currentType,
2
pedrovgs/Nox
sample/src/main/java/com/github/pedrovgs/nox/sample/MainActivity.java
[ "public class NoxItem {\n\n private final String url;\n private final Integer resourceId;\n private final Integer placeholderId;\n\n public NoxItem(String url) {\n validateUrl(url);\n this.url = url;\n this.resourceId = null;\n this.placeholderId = null;\n }\n\n public NoxItem(int resourceId) {\n this.url = null;\n this.resourceId = resourceId;\n this.placeholderId = null;\n }\n\n public NoxItem(String url, int placeholderId) {\n validateUrl(url);\n this.url = url;\n this.placeholderId = placeholderId;\n this.resourceId = null;\n }\n\n public boolean hasUrl() {\n return url != null;\n }\n\n public boolean hasResourceId() {\n return resourceId != null;\n }\n\n public boolean hasPlaceholder() {\n return placeholderId != null;\n }\n\n public String getUrl() {\n return url;\n }\n\n public Integer getResourceId() {\n return resourceId;\n }\n\n public Integer getPlaceholderId() {\n return placeholderId;\n }\n\n private void validateUrl(String url) {\n if (url == null) {\n throw new NullPointerException(\"The url String used to create a NoxItem can't be null\");\n }\n }\n}", "public class NoxView extends View {\n\n private NoxConfig noxConfig;\n private Shape shape;\n private Scroller scroller;\n private NoxItemCatalog noxItemCatalog;\n private Paint paint = new Paint();\n private boolean wasInvalidatedBefore;\n private OnNoxItemClickListener listener = OnNoxItemClickListener.EMPTY;\n private GestureDetectorCompat gestureDetector;\n private int defaultShapeKey;\n private boolean useCircularTransformation;\n\n public NoxView(Context context) {\n super(context);\n initializeNoxViewConfig(context, null, 0, 0);\n }\n\n public NoxView(Context context, AttributeSet attrs) {\n super(context, attrs);\n initializeNoxViewConfig(context, attrs, 0, 0);\n }\n\n public NoxView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n initializeNoxViewConfig(context, attrs, defStyleAttr, 0);\n }\n\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n public NoxView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n super(context, attrs, defStyleAttr, defStyleRes);\n initializeNoxViewConfig(context, attrs, defStyleAttr, defStyleRes);\n }\n\n /**\n * Given a List<NoxItem> instances configured previously gets the associated resource to draw the\n * view.\n */\n @Override protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n if (noxItemCatalog == null) {\n wasInvalidatedBefore = false;\n return;\n }\n updateShapeOffset();\n for (int i = 0; i < noxItemCatalog.size(); i++) {\n if (shape.isItemInsideView(i)) {\n loadNoxItem(i);\n float left = shape.getXForItemAtPosition(i);\n float top = shape.getYForItemAtPosition(i);\n drawNoxItem(canvas, i, left, top);\n }\n }\n canvas.restore();\n wasInvalidatedBefore = false;\n }\n\n /**\n * Configures a of List<NoxItem> instances to draw this items.\n */\n public void showNoxItems(final List<NoxItem> noxItems) {\n this.post(new Runnable() {\n @Override public void run() {\n initializeNoxItemCatalog(noxItems);\n createShape();\n initializeScroller();\n refreshView();\n }\n });\n }\n\n /**\n * Used to notify when the data source has changed and is necessary to re draw the view.\n */\n public void notifyDataSetChanged() {\n if (noxItemCatalog != null) {\n noxItemCatalog.recreate();\n createShape();\n initializeScroller();\n refreshView();\n }\n }\n\n /**\n * Changes the Shape used to the one passed as argument. This method will refresh the view.\n */\n public void setShape(Shape shape) {\n validateShape(shape);\n\n this.shape = shape;\n this.shape.calculate();\n initializeScroller();\n resetScroll();\n }\n\n /**\n * Delegates touch events to the scroller instance initialized previously to implement the scroll\n * effect. If the scroller does not handle the MotionEvent NoxView will check if any NoxItem has\n * been clicked to notify a previously configured OnNoxItemClickListener.\n */\n @Override public boolean onTouchEvent(MotionEvent event) {\n super.onTouchEvent(event);\n boolean clickCaptured = processTouchEvent(event);\n boolean scrollCaptured = scroller != null && scroller.onTouchEvent(event);\n boolean singleTapCaptured = getGestureDetectorCompat().onTouchEvent(event);\n return clickCaptured || scrollCaptured || singleTapCaptured;\n }\n\n /**\n * Delegates computeScroll method to the scroller instance to implement the scroll effect.\n */\n @Override public void computeScroll() {\n super.computeScroll();\n if (scroller != null) {\n scroller.computeScroll();\n }\n }\n\n /**\n * Returns the minimum X position the view can get taking into account the scroll offset.\n */\n public int getMinX() {\n return scroller.getMinX();\n }\n\n /**\n * Returns the maximum X position the view can get taking into account the scroll offset.\n */\n public int getMaxX() {\n return scroller.getMaxX();\n }\n\n /**\n * Returns the minimum Y position the view can get taking into account the scroll offset.\n */\n public int getMinY() {\n return scroller.getMinY();\n }\n\n /**\n * Returns the minimum Y position the view can get taking into account the scroll offset.\n */\n public int getMaxY() {\n return scroller.getMaxY();\n }\n\n public int getOverSize() {\n return scroller.getOverSize();\n }\n\n /**\n * Returns the current Shape used in to draw this view.\n */\n public Shape getShape() {\n return shape;\n }\n\n /**\n * Configures a OnNoxItemClickListener instance to be notified when a NoxItem instance is\n * clicked.\n */\n public void setOnNoxItemClickListener(OnNoxItemClickListener listener) {\n validateListener(listener);\n this.listener = listener;\n }\n\n /**\n * Resets the scroll position to the 0,0.\n */\n public void resetScroll() {\n if (scroller != null) {\n scroller.reset();\n refreshView();\n }\n }\n\n /**\n * Controls visibility changes to pause or resume this custom view and avoid performance\n * problems.\n */\n @Override protected void onVisibilityChanged(View changedView, int visibility) {\n super.onVisibilityChanged(changedView, visibility);\n if (changedView != this) {\n return;\n }\n\n if (visibility == View.VISIBLE) {\n resume();\n } else {\n pause();\n }\n }\n\n /**\n * Release resources when the view has been detached from the window.\n */\n @Override protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n release();\n }\n\n /**\n * Given a NoxItem position try to load this NoxItem if the view is not performing a fast scroll\n * after a fling gesture.\n */\n private void loadNoxItem(int position) {\n if (!scroller.isScrollingFast()) {\n noxItemCatalog.load(position, useCircularTransformation);\n }\n }\n\n /**\n * Resumes NoxItemCatalog and adds a observer to be notified when a NoxItem is ready to be drawn.\n */\n private void resume() {\n noxItemCatalog.addObserver(catalogObserver);\n noxItemCatalog.resume();\n }\n\n /**\n * Pauses NoxItemCatalog and removes the observer previously configured.\n */\n private void pause() {\n noxItemCatalog.pause();\n noxItemCatalog.deleteObserver(catalogObserver);\n }\n\n /**\n * Releases NoxItemCatalog and removes the observer previously configured.\n */\n private void release() {\n noxItemCatalog.release();\n noxItemCatalog.deleteObserver(catalogObserver);\n }\n\n /**\n * Observer implementation used to be notified when a NoxItem has been loaded.\n */\n private Observer catalogObserver = new Observer() {\n @Override public void update(Observable observable, Object data) {\n Integer position = (Integer) data;\n boolean isNoxItemLoadedInsideTheView = shape != null && shape.isItemInsideView(position);\n if (isNoxItemLoadedInsideTheView) {\n refreshView();\n }\n }\n };\n\n /**\n * Tries to post a invalidate() event if another one was previously posted.\n */\n private void refreshView() {\n if (!wasInvalidatedBefore) {\n wasInvalidatedBefore = true;\n invalidate();\n }\n }\n\n private void initializeNoxItemCatalog(List<NoxItem> noxItems) {\n ImageLoader imageLoader = ImageLoaderFactory.getPicassoImageLoader(getContext());\n this.noxItemCatalog =\n new NoxItemCatalog(noxItems, (int) noxConfig.getNoxItemSize(), imageLoader);\n this.noxItemCatalog.setDefaultPlaceholder(noxConfig.getPlaceholder());\n this.noxItemCatalog.addObserver(catalogObserver);\n }\n\n private void initializeScroller() {\n scroller =\n new Scroller(this, shape.getMinX(), shape.getMaxX(), shape.getMinY(), shape.getMaxY(),\n shape.getOverSize());\n }\n\n /**\n * Checks the X and Y scroll offset to update that values into the Shape configured previously.\n */\n private void updateShapeOffset() {\n int offsetX = scroller.getOffsetX();\n int offsetY = scroller.getOffsetY();\n shape.setOffset(offsetX, offsetY);\n }\n\n /**\n * Draws a NoxItem during the onDraw method.\n */\n private void drawNoxItem(Canvas canvas, int position, float left, float top) {\n if (noxItemCatalog.isBitmapReady(position)) {\n Bitmap bitmap = noxItemCatalog.getBitmap(position);\n canvas.drawBitmap(bitmap, left, top, paint);\n } else if (noxItemCatalog.isDrawableReady(position)) {\n Drawable drawable = noxItemCatalog.getDrawable(position);\n drawNoxItemDrawable(canvas, (int) left, (int) top, drawable);\n } else if (noxItemCatalog.isPlaceholderReady(position)) {\n Drawable drawable = noxItemCatalog.getPlaceholder(position);\n drawNoxItemDrawable(canvas, (int) left, (int) top, drawable);\n }\n }\n\n /**\n * Draws a NoxItem drawable during the onDraw method given a canvas object and all the\n * information needed to draw the Drawable passed as parameter.\n */\n private void drawNoxItemDrawable(Canvas canvas, int left, int top, Drawable drawable) {\n if (drawable != null) {\n int itemSize = (int) noxConfig.getNoxItemSize();\n drawable.setBounds(left, top, left + itemSize, top + itemSize);\n drawable.draw(canvas);\n }\n }\n\n /**\n * Initializes a Shape instance given the NoxView configuration provided programmatically or\n * using XML styleable attributes.\n */\n private void createShape() {\n if (shape == null) {\n float firstItemMargin = noxConfig.getNoxItemMargin();\n float firstItemSize = noxConfig.getNoxItemSize();\n int viewHeight = getMeasuredHeight();\n int viewWidth = getMeasuredWidth();\n int numberOfElements = noxItemCatalog.size();\n ShapeConfig shapeConfig =\n new ShapeConfig(numberOfElements, viewWidth, viewHeight, firstItemSize, firstItemMargin);\n shape = ShapeFactory.getShapeByKey(defaultShapeKey, shapeConfig);\n } else {\n shape.setNumberOfElements(noxItemCatalog.size());\n }\n shape.calculate();\n }\n\n /**\n * Initializes a NoxConfig instance given the NoxView configuration provided programmatically or\n * using XML styleable attributes.\n */\n private void initializeNoxViewConfig(Context context, AttributeSet attrs, int defStyleAttr,\n int defStyleRes) {\n noxConfig = new NoxConfig();\n TypedArray attributes = context.getTheme()\n .obtainStyledAttributes(attrs, R.styleable.nox, defStyleAttr, defStyleRes);\n initializeNoxItemSize(attributes);\n initializeNoxItemMargin(attributes);\n initializeNoxItemPlaceholder(attributes);\n initializeShapeConfig(attributes);\n initializeTransformationConfig(attributes);\n attributes.recycle();\n }\n\n /**\n * Configures the nox item default size used in NoxConfig, Shape and NoxItemCatalog to draw nox\n * item instances during the onDraw execution.\n */\n private void initializeNoxItemSize(TypedArray attributes) {\n float noxItemSizeDefaultValue = getResources().getDimension(R.dimen.default_nox_item_size);\n float noxItemSize = attributes.getDimension(R.styleable.nox_item_size, noxItemSizeDefaultValue);\n noxConfig.setNoxItemSize(noxItemSize);\n }\n\n /**\n * Configures the nox item default margin used in NoxConfig, Shape and NoxItemCatalog to draw nox\n * item instances during the onDraw execution.\n */\n private void initializeNoxItemMargin(TypedArray attributes) {\n float noxItemMarginDefaultValue = getResources().getDimension(R.dimen.default_nox_item_margin);\n float noxItemMargin =\n attributes.getDimension(R.styleable.nox_item_margin, noxItemMarginDefaultValue);\n noxConfig.setNoxItemMargin(noxItemMargin);\n }\n\n /**\n * Configures the placeholder used if there is no another placeholder configured in the NoxItem\n * instances during the onDraw execution.\n */\n private void initializeNoxItemPlaceholder(TypedArray attributes) {\n Drawable placeholder = attributes.getDrawable(R.styleable.nox_item_placeholder);\n if (placeholder == null) {\n placeholder = getContext().getResources().getDrawable(R.drawable.ic_nox);\n }\n noxConfig.setPlaceholder(placeholder);\n }\n\n /**\n * Configures the Shape used to show the list of NoxItems.\n */\n private void initializeShapeConfig(TypedArray attributes) {\n defaultShapeKey =\n attributes.getInteger(R.styleable.nox_shape, ShapeFactory.FIXED_CIRCULAR_SHAPE_KEY);\n }\n\n /**\n * Configures the visual transformation applied to the NoxItem resources loaded, images\n * downloaded from the internet and resources loaded from the system.\n */\n private void initializeTransformationConfig(TypedArray attributes) {\n useCircularTransformation =\n attributes.getBoolean(R.styleable.nox_use_circular_transformation, true);\n }\n\n private void validateShape(Shape shape) {\n if (shape == null) {\n throw new NullPointerException(\"You can't pass a null Shape instance as argument.\");\n }\n if (noxItemCatalog != null && shape.getNumberOfElements() != noxItemCatalog.size()) {\n throw new IllegalArgumentException(\n \"The number of items in the Shape instance passed as argument doesn't match with \"\n + \"the current number of NoxItems.\");\n }\n }\n\n private void validateListener(OnNoxItemClickListener listener) {\n if (listener == null) {\n throw new NullPointerException(\n \"You can't configure a null instance of OnNoxItemClickListener as NoxView listener.\");\n }\n }\n\n /**\n * Returns a GestureDetectorCompat lazy instantiated created to handle single tap events and\n * detect if a NoxItem has been clicked to notify the previously configured listener.\n */\n private GestureDetectorCompat getGestureDetectorCompat() {\n if (gestureDetector == null) {\n GestureDetector.OnGestureListener gestureListener = new SimpleOnGestureListener() {\n\n @Override public boolean onSingleTapUp(MotionEvent e) {\n boolean handled = false;\n int position = shape.getNoxItemHit(e.getX(), e.getY());\n if (position >= 0) {\n handled = true;\n NoxItem noxItem = noxItemCatalog.getNoxItem(position);\n listener.onNoxItemClicked(position, noxItem);\n }\n return handled;\n }\n };\n gestureDetector = new GestureDetectorCompat(getContext(), gestureListener);\n }\n return gestureDetector;\n }\n\n private boolean processTouchEvent(MotionEvent event) {\n if (shape == null) {\n return false;\n }\n\n boolean handled = false;\n float x = event.getX();\n float y = event.getY();\n int noxItemHit = shape.getNoxItemHit(x, y);\n boolean isNoxItemHit = noxItemHit >= 0;\n switch (event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n if (isNoxItemHit) {\n changeNoxItemStateToPressed(noxItemHit);\n handled = true;\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n case MotionEvent.ACTION_UP:\n for (int i = 0; i < noxItemCatalog.size(); i++) {\n if (shape.isItemInsideView(i)) {\n changeNoxItemStateToNotPressed(i);\n handled = true;\n }\n }\n break;\n default:\n }\n return handled;\n }\n\n private void changeNoxItemStateToPressed(int noxItemPosition) {\n int[] stateSet = new int[2];\n stateSet[0] = android.R.attr.state_pressed;\n stateSet[1] = android.R.attr.state_enabled;\n setNoxItemState(noxItemPosition, stateSet);\n }\n\n private void changeNoxItemStateToNotPressed(int noxItemPosition) {\n int[] stateSet = new int[2];\n stateSet[0] = -android.R.attr.state_pressed;\n stateSet[1] = android.R.attr.state_enabled;\n setNoxItemState(noxItemPosition, stateSet);\n }\n\n private void setNoxItemState(int noxItemPosition, int[] stateSet) {\n boolean refreshView = false;\n if (noxItemCatalog.isDrawableReady(noxItemPosition)) {\n Drawable drawable = noxItemCatalog.getDrawable(noxItemPosition);\n drawable.setState(stateSet);\n refreshView = true;\n } else if (noxItemCatalog.isPlaceholderReady(noxItemPosition)) {\n Drawable drawable = noxItemCatalog.getPlaceholder(noxItemPosition);\n drawable.setState(stateSet);\n refreshView = true;\n }\n if (refreshView) {\n refreshView();\n }\n }\n\n /**\n * Method created for testing purposes. Configures the Scroller to be used by NoxView.\n * This method is needed because we don't have access to the view constructor.\n */\n void setScroller(Scroller scroller) {\n this.scroller = scroller;\n }\n\n /**\n * Method created for testing purposes. Configures the NoxItemCatalog to be used by NoxView.\n * This method is needed because we don't have access to the view constructor.\n */\n void setNoxItemCatalog(NoxItemCatalog noxItemCatalog) {\n this.noxItemCatalog = noxItemCatalog;\n }\n\n /**\n * Method created for testing purposes. Returns the NoxItemCatalog to be used by NoxView.\n * This method is needed because we don't have access to the view constructor.\n */\n NoxItemCatalog getNoxItemCatalog() {\n return noxItemCatalog;\n }\n}", "public interface OnNoxItemClickListener {\n\n OnNoxItemClickListener EMPTY = new OnNoxItemClickListener() {\n @Override public void onNoxItemClicked(int position, NoxItem noxItem) {\n\n }\n };\n\n void onNoxItemClicked(int position, NoxItem noxItem);\n}", "public abstract class Shape {\n\n private final ShapeConfig shapeConfig;\n\n private float[] noxItemsXPositions;\n private float[] noxItemsYPositions;\n private int offsetX;\n private int offsetY;\n private int minX;\n private int maxX;\n private int minY;\n private int maxY;\n\n public Shape(ShapeConfig shapeConfig) {\n this.shapeConfig = shapeConfig;\n int numberOfElements = shapeConfig.getNumberOfElements();\n this.noxItemsXPositions = new float[numberOfElements];\n this.noxItemsYPositions = new float[numberOfElements];\n }\n\n /**\n * Configures the new offset to apply to the Shape.\n */\n public void setOffset(int offsetX, int offsetY) {\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n }\n\n /**\n * Shape extensions have implement this method and configure the position in the x and y axis for\n * every NoxItem.\n */\n public abstract void calculate();\n\n /**\n * Returns the X position of a NoxItem for the current Shape.\n */\n public final float getXForItemAtPosition(int position) {\n return noxItemsXPositions[position];\n }\n\n /**\n * Returns the Y position of a NoxItem for the current Shape.\n */\n public final float getYForItemAtPosition(int position) {\n return noxItemsYPositions[position];\n }\n\n /**\n * Returns true if the view should be rendered inside the view window taking into account the\n * offset applied by the scroll effect.\n */\n public final boolean isItemInsideView(int position) {\n float x = (getXForItemAtPosition(position) + offsetX);\n float y = (getYForItemAtPosition(position) + offsetY);\n float itemSize = getNoxItemSize();\n int viewWidth = shapeConfig.getViewWidth();\n boolean matchesHorizontally = x + itemSize >= 0 && x <= viewWidth;\n float viewHeight = shapeConfig.getViewHeight();\n boolean matchesVertically = y + itemSize >= 0 && y <= viewHeight;\n return matchesHorizontally && matchesVertically;\n }\n\n /**\n * Returns the minimum X position the view should show during the scroll process.\n */\n public final int getMinX() {\n return (int) (this.minX - getNoxItemMargin());\n }\n\n /**\n * Returns the maximum X position the view should show during the scroll process.\n */\n public final int getMaxX() {\n return (int) (this.maxX + getNoxItemSize() + getNoxItemMargin()\n - getShapeConfig().getViewWidth());\n }\n\n /**\n * Returns the minimum Y position the view should show during the scroll process.\n */\n public final int getMinY() {\n return (int) (this.minY - getNoxItemMargin());\n }\n\n /**\n * Returns the maximum Y position the view should show during the scroll process.\n */\n public final int getMaxY() {\n return (int) (this.maxY + getNoxItemMargin() + getNoxItemSize()\n - getShapeConfig().getViewHeight());\n }\n\n /**\n * Returns the over scroll used by the view during the fling process. By default this value will\n * be equals to the configured margin.\n */\n public int getOverSize() {\n return (int) shapeConfig.getItemMargin();\n }\n\n /**\n * Returns the ShapeConfig used to create this Shape.\n */\n public final ShapeConfig getShapeConfig() {\n return shapeConfig;\n }\n\n /**\n * Returns the number of elements the Shape is using to calculate NoxItems positions.\n */\n public int getNumberOfElements() {\n return getShapeConfig().getNumberOfElements();\n }\n\n /**\n * Returns the position of the NoxView if any of the previously configured NoxItem instances is\n * hit. If there is no any NoxItem hit this method returns -1.\n */\n public int getNoxItemHit(float x, float y) {\n int noxItemPosition = -1;\n for (int i = 0; i < getNumberOfElements(); i++) {\n float noxItemX = getXForItemAtPosition(i) + offsetX;\n float noxItemY = getYForItemAtPosition(i) + offsetY;\n float itemSize = getNoxItemSize();\n boolean matchesHorizontally = x >= noxItemX && x <= noxItemX + itemSize;\n boolean matchesVertically = y >= noxItemY && y <= noxItemY + itemSize;\n if (matchesHorizontally && matchesVertically) {\n noxItemPosition = i;\n break;\n }\n }\n return noxItemPosition;\n }\n\n /**\n * Configures the number of element the Shape is going to use to calculate NoxItems positions.\n * This method resets the previous position calculus.\n */\n public void setNumberOfElements(int numberOfElements) {\n this.shapeConfig.setNumberOfElements(numberOfElements);\n this.noxItemsXPositions = new float[numberOfElements];\n this.noxItemsYPositions = new float[numberOfElements];\n }\n\n /**\n * Configures the X position for a given NoxItem indicated with the item position. This method\n * uses two counters to calculate the Shape minimum and maximum X position used to configure the\n * Shape scroll.\n */\n protected final void setNoxItemXPosition(int position, float x) {\n noxItemsXPositions[position] = x;\n minX = (int) Math.min(x, minX);\n maxX = (int) Math.max(x, maxX);\n }\n\n /**\n * Configures the Y position for a given NoxItem indicated with the item position. This method\n * uses two counters to calculate the Shape minimum and maximum Y position used to configure the\n * Shape scroll.\n */\n protected final void setNoxItemYPosition(int position, float y) {\n noxItemsYPositions[position] = y;\n minY = (int) Math.min(y, minY);\n maxY = (int) Math.max(y, maxY);\n }\n\n /**\n * Returns the NoxItem size taking into account the scale factor.\n */\n protected float getNoxItemSize() {\n return getShapeConfig().getItemSize();\n }\n\n /**\n * Returns the NoxIte margin taking into account the scale factor.\n */\n private float getNoxItemMargin() {\n return getShapeConfig().getItemMargin();\n }\n}", "public class ShapeConfig {\n\n private int numberOfElements;\n private final int viewWidth;\n private final int viewHeight;\n private final float itemSize;\n private final float itemMargin;\n\n public ShapeConfig(int numberOfElements, int viewWidth, int viewHeight, float itemSize,\n float itemMargin) {\n this.numberOfElements = numberOfElements;\n this.viewWidth = viewWidth;\n this.viewHeight = viewHeight;\n this.itemSize = itemSize;\n this.itemMargin = itemMargin;\n }\n\n public int getNumberOfElements() {\n return numberOfElements;\n }\n\n public int getViewWidth() {\n return viewWidth;\n }\n\n public int getViewHeight() {\n return viewHeight;\n }\n\n public float getItemSize() {\n return itemSize;\n }\n\n public float getItemMargin() {\n return itemMargin;\n }\n\n public void setNumberOfElements(int numberOfElements) {\n this.numberOfElements = numberOfElements;\n }\n}" ]
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import com.github.pedrovgs.nox.NoxItem; import com.github.pedrovgs.nox.NoxView; import com.github.pedrovgs.nox.OnNoxItemClickListener; import com.github.pedrovgs.nox.shape.Shape; import com.github.pedrovgs.nox.shape.ShapeConfig; import java.util.ArrayList; import java.util.List;
/* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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.github.pedrovgs.nox.sample; /** * Sample activity created to show how to use NoxView with a List of NoxItem instances. * * @author Pedro Vicente Gomez Sanchez. */ public class MainActivity extends ActionBarActivity { private static final String LOGTAG = "MainActivity"; private NoxView noxView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); configureNoxView(); } private void configureNoxView() { noxView = (NoxView) findViewById(R.id.nox_view); noxView.post(new Runnable() { @Override public void run() { int numberOfItems = configureNoxItems(); configureShape(numberOfItems); configureClickListeners(); } }); } private int configureNoxItems() { List<NoxItem> noxItems = new ArrayList<NoxItem>(); noxItems.add(new NoxItem(R.drawable.ic_contacts)); noxItems.add(new NoxItem(R.drawable.ic_apps)); noxView.showNoxItems(noxItems); return noxItems.size(); } private void configureShape(int numberOfItems) { int width = noxView.getWidth(); int height = noxView.getHeight(); float itemSize = getResources().getDimension(R.dimen.nox_item_size); float itemMargin = getResources().getDimension(R.dimen.main_activity_nox_item_margin); ShapeConfig shapeConfig = new ShapeConfig(numberOfItems, width, height, itemSize, itemMargin);
Shape verticalLinearShape = new VerticalLinearShape(shapeConfig);
3
cert-se/megatron-java
src/se/sitic/megatron/fileprocessor/MultithreadedDnsProcessor.java
[ "public class AppProperties {\n // -- Keys in properties file --\n\n // Implicit\n public static final String JOB_TYPE_NAME_KEY = \"implicit.jobTypeName\";\n\n // General\n public static final String LOG4J_FILE_KEY = \"general.log4jConfigFile\";\n public static final String LOG_DIR_KEY = \"general.logDir\";\n public static final String JOB_TYPE_CONFIG_DIR_KEY = \"general.jobTypeConfigDir\";\n public static final String SLURP_DIR_KEY = \"general.slurpDir\";\n public static final String OUTPUT_DIR_KEY = \"general.outputDir\";\n public static final String TMP_DIR_KEY = \"general.tmpDir\";\n public static final String INPUT_CHAR_SET_KEY = \"general.inputCharSet\";\n // Deprecated: geoIp.databaseFile (use defaultValuegeoIp.countryDatabaseFile instead)\n public static final String GEO_IP_DATABASE_FILE_KEY = \"geoIp.databaseFile\";\n public static final String GEO_IP_COUNTRY_DATABASE_FILE_KEY = \"geoIp.countryDatabaseFile\";\n public static final String GEO_IP_ASN_DATABASE_FILE_KEY = \"geoIp.asnDatabaseFile\";\n public static final String GEO_IP_CITY_DATABASE_FILE_KEY = \"geoIp.cityDatabaseFile\";\n public static final String GEO_IP_USE_CITY_DATABASE_FOR_COUNTRY_LOOKUPS_KEY = \"geoIp.useCityDatabaseForCountryLookups\";\n public static final String FILENAME_MAPPER_LIST_KEY = \"general.filenameMapperList\";\n public static final String USE_DNS_JAVA_KEY = \"general.useDnsJava\";\n public static final String WHOIS_SERVER_KEY = \"general.whoisServer\";\n public static final String HIGH_PRIORITY_THRESHOLD_KEY = \"general.highPriorityNotification.threshold\";\n public static final String TIMESTAMP_WARNING_MAX_AGE_KEY = \"general.timestampWarning.maxAge\";\n public static final String PRINT_PROGRESS_INTERVAL_KEY = \"general.printProgressInterval\";\n public static final String FILE_ALREADY_PROCESSED_ACTION_KEY = \"general.fileAlreadyProcessedAction\";\n \n // dnsjava\n public static final String DNS_JAVA_USE_DNS_JAVA_KEY = \"dnsJava.useDnsJava\";\n public static final String DNS_JAVA_USE_SIMPLE_RESOLVER_KEY = \"dnsJava.useSimpleResolver\";\n public static final String DNS_JAVA_DNS_SERVERS_KEY = \"dnsJava.dnsServers\";\n public static final String DNS_JAVA_TIME_OUT_KEY = \"dnsJava.timeOut\";\n \n // Database\n public static final String DB_USERNAME_KEY = \"db.username\";\n public static final String DB_PASSWORD_KEY = \"db.password\";\n public static final String DB_SERVER_KEY = \"db.server\";\n public static final String DB_PORT_KEY = \"db.port\";\n public static final String DB_NAME_KEY = \"db.name\";\n public static final String JDBC_URL_KEY = \"db.jdbc.url\";\n public static final String JDBC_DRIVER_CLASS_KEY = \"db.jdbc.driverClassName\";\n\n // BGP\n public static final String BGP_IMPORT_FILE_KEY = \"bgp.importFile\";\n public static final String BGP_HARD_CODED_PREFIXES_KEY = \"bgp.hardCodedPrefixes\";\n \n // Export\n public static final String EXPORT_TEMPLATE_DIR_KEY = \"export.templateDir\";\n public static final String EXPORT_HEADER_FILE_KEY = \"export.headerFile\";\n public static final String EXPORT_ROW_FILE_KEY = \"export.rowFile\";\n public static final String EXPORT_FOOTER_FILE_KEY = \"export.footerFile\";\n public static final String EXPORT_CHAR_SET_KEY = \"export.charSet\";\n public static final String EXPORT_TIMESTAMP_FORMAT_KEY = \"export.timestampFormat\";\n public static final String EXPORT_REWRITERS_KEY = \"export.rewriters\";\n public static final String EXPORT_JOB_TYPE_NAME_MAPPER_KEY = \"export.jobTypeNameMapper\"; \n\n // Mail\n public static final String MAIL_SMTP_HOST_KEY = \"mail.smtpHost\";\n public static final String MAIL_DEBUG_KEY = \"mail.debug\";\n public static final String MAIL_FROM_ADDRESS_KEY = \"mail.fromAddress\";\n public static final String MAIL_TO_ADDRESSES_KEY = \"mail.toAddresses\";\n public static final String MAIL_CC_ADDRESSES_KEY = \"mail.ccAddresses\";\n public static final String MAIL_BCC_ADDRESSES_KEY = \"mail.bccAddresses\";\n public static final String MAIL_ARCHIVE_BCC_ADDRESSES_KEY = \"mail.archiveBccAddresses\";\n public static final String MAIL_SUMMARY_TO_ADDRESSES_KEY = \"mail.mailJobSummary.toAddresses\";\n public static final String MAIL_NOTIFICATION_TO_ADDRESSES_KEY = \"mail.highPriorityNotification.toAddresses\";\n public static final String MAIL_REPLY_TO_ADDRESSES_KEY = \"mail.replyToAddresses\";\n public static final String MAIL_HTML_MAIL_KEY = \"mail.htmlMail\";\n public static final String MAIL_IP_QUARANTINE_PERIOD_KEY = \"mail.ipQuarantinePeriod\";\n \n public static final String MAIL_SUBJECT_TEMPLATE_KEY = \"mail.subjectTemplate\";\n public static final String MAIL_JOB_SUMMARY_SUBJECT_TEMPLATE_KEY = \"mail.mailJobSummary.subjectTemplate\";\n public static final String MAIL_TEMPLATE_DIR_KEY = \"mail.templateDir\";\n public static final String MAIL_DEFAULT_LANGUAGE_CODE_KEY = \"mail.defaultLanguageCode\";\n public static final String MAIL_HEADER_FILE_KEY = \"mail.headerFile\";\n public static final String MAIL_ROW_FILE_KEY = \"mail.rowFile\";\n public static final String MAIL_FOOTER_FILE_KEY = \"mail.footerFile\";\n public static final String MAIL_ATTACHMENT_HEADER_FILE_KEY = \"mail.attachmentHeaderFile\";\n public static final String MAIL_ATTACHMENT_ROW_FILE_KEY = \"mail.attachmentRowFile\";\n public static final String MAIL_ATTACHMENT_FOOTER_FILE_KEY = \"mail.attachmentFooterFile\"; \n public static final String MAIL_ATTACHMENT_NAME_KEY = \"mail.attachmentName\";\n public static final String MAIL_TIMESTAMP_FORMAT_KEY = \"mail.timestampFormat\";\n public static final String MAIL_RAISE_ERROR_FOR_DEBUG_TEMPLATE_KEY = \"mail.raiseErrorForDebugTemplate\";\n \n // Mail Encryption\n public static final String MAIL_ENCRYPTION_TYPE_KEY = \"mail.encryptionType\";\n public static final String MAIL_ENCRYPTION_KEYPATH_KEY = \"mail.encryptionKeyPath\";\n public static final String MAIL_ENCRYPTION_SMIME_PW_KEY = \"mail.enryptionSMIMEpw\";\n public static final String MAIL_ENCRYPTION_PGP_PW_KEY = \"mail.enryptionPGPpw\";\n public static final String MAIL_ENCRYPTION_ENCRYPT_KEY = \"mail.encryptMail\";\n public static final String MAIL_ENCRYPTION_SIGN_KEY = \"mail.signMail\";\n\n // Filters\n public static final String FILTER_PRE_LINE_PROCESSOR_KEY = \"filter.preLineProcessor.classNames\";\n public static final String FILTER_PRE_PARSER_KEY = \"filter.preParser.classNames\";\n public static final String FILTER_PRE_DECORATOR_KEY = \"filter.preDecorator.classNames\";\n public static final String FILTER_PRE_STORAGE_KEY = \"filter.preStorage.classNames\";\n public static final String FILTER_PRE_EXPORT_KEY = \"filter.preExport.classNames\";\n public static final String FILTER_PRE_MAIL_KEY = \"filter.preMail.classNames\";\n public static final String FILTER_EXCLUDE_REG_EXP_KEY = \"filter.regExpLineFilter.excludeRegExp\";\n public static final String FILTER_INCLUDE_REG_EXP_KEY = \"filter.regExpLineFilter.includeRegExp\";\n public static final String FILTER_LINE_NUMBER_EXCLUDE_INTERVALS_KEY = \"filter.lineNumberFilter.excludeIntervals\";\n public static final String FILTER_LINE_NUMBER_INCLUDE_INTERVALS_KEY = \"filter.lineNumberFilter.includeIntervals\";\n public static final String FILTER_PRIORITY_INCLUDE_INTERVALS_KEY = \"filter.priorityFilter.includeIntervals\";\n public static final String FILTER_EXCLUDE_COUNTRY_CODES_KEY = \"filter.countryCodeFilter.excludeCountryCodes\";\n public static final String FILTER_INCLUDE_COUNTRY_CODES_KEY = \"filter.countryCodeFilter.includeCountryCodes\";\n public static final String FILTER_COUNTRY_CODE_ORGANIZATION_KEY = \"filter.countryCodeFilter.organizationToFilter\";\n public static final String FILTER_EXCLUDE_AS_NUMBERS_KEY = \"filter.asnFilter.excludeAsNumbers\";\n public static final String FILTER_INCLUDE_AS_NUMBERS_KEY = \"filter.asnFilter.includeAsNumbers\";\n public static final String FILTER_ASN_ORGANIZATION_KEY = \"filter.asnFilter.organizationToFilter\";\n public static final String FILTER_ATTRIBUTE_NAME_KEY = \"filter.attributeFilter.attributeName\";\n public static final String FILTER_ATTRIBUTE_EXCLUDE_REG_EXP_KEY = \"filter.attributeFilter.excludeRegExp\";\n public static final String FILTER_ATTRIBUTE_INCLUDE_REG_EXP_KEY = \"filter.attributeFilter.includeRegExp\";\n public static final String FILTER_OCCURRENCE_ATTRIBUTE_NAMES_KEY = \"filter.occurrenceFilter.attributeNames\"; \n public static final String FILTER_OCCURRENCE_EXCLUDE_INTERVALS_KEY = \"filter.occurrenceFilter.excludeIntervals\";\n public static final String FILTER_OCCURRENCE_INCLUDE_INTERVALS_KEY = \"filter.occurrenceFilter.includeIntervals\";\n public static final String FILTER_OCCURRENCE_FILE_SORTED_KEY = \"filter.occurrenceFilter.fileSorted\";\n public static final String FILTER_MATCH_IP_ADDRESS_KEY = \"filter.organizationFilter.matchIpAddress\";\n public static final String FILTER_MATCH_HOSTNAME_KEY = \"filter.organizationFilter.matchHostname\";\n public static final String FILTER_MATCH_ASN_KEY = \"filter.organizationFilter.matchAsn\";\n \n // File Processor\n public static final String FILE_PROCESSOR_CLASS_NAME_KEY = \"fileProcessor.className\";\n public static final String FILE_PROCESSOR_CLASS_NAMES_KEY = \"fileProcessor.classNames\";\n public static final String FILE_PROCESSOR_DELETE_TMP_FILES_KEY = \"fileProcessor.deleteTmpFiles\";\n public static final String FILE_PROCESSOR_OS_COMMAND_KEY = \"fileProcessor.osCommandProcessor.command\";\n public static final String FILE_PROCESSOR_DIFF_COMMAND_KEY = \"fileProcessor.diffProcessor.command\";\n public static final String FILE_PROCESSOR_DIFF_OLD_FILES_DIR_KEY = \"fileProcessor.diffProcessor.oldFilesDir\";\n public static final String FILE_PROCESSOR_DIFF_NO_OF_BACKUPS_TO_KEEP_KEY = \"fileProcessor.diffProcessor.noOfBackupsToKeep\";\n public static final String FILE_PROCESSOR_XML_TO_ROW_START_ELEMENT_KEY = \"fileProcessor.xmlToRowFileProcessor.startElement\";\n public static final String FILE_PROCESSOR_XML_TO_ROW_ELEMENTS_TO_SAVE_KEY = \"fileProcessor.xmlToRowFileProcessor.elementsToSave\";\n public static final String FILE_PROCESSOR_XML_TO_ROW_OUTPUT_SEPARATOR_KEY = \"fileProcessor.xmlToRowFileProcessor.outputSeparator\";\n // Deprecated: fileProcessor.xmlToRowFileProcessor.deleteOutputFile (use fileProcessor.deleteTmpFiles instead)\n public static final String FILE_PROCESSOR_XML_TO_ROW_DELETE_OUTPUT_FILE_KEY = \"fileProcessor.xmlToRowFileProcessor.deleteOutputFile\";\n public static final String FILE_PROCESSOR_DNS_NO_OF_THREADS_KEY = \"fileProcessor.multithreadedDnsProcessor.noOfThreads\";\n public static final String FILE_PROCESSOR_DNS_REVERSE_DNS_LOOKUP_KEY = \"fileProcessor.multithreadedDnsProcessor.reverseDnsLookup\";\n public static final String FILE_PROCESSOR_DNS_REG_EXP_IP_KEY = \"fileProcessor.multithreadedDnsProcessor.regExpIp\";\n public static final String FILE_PROCESSOR_DNS_REG_EXP_HOSTNAME_KEY = \"fileProcessor.multithreadedDnsProcessor.regExpHostname\";\n \n // Line Processor\n public static final String LINE_PROCESSOR_CLASS_NAME_KEY = \"lineProcessor.className\";\n public static final String LINE_MERGER_START_REG_EXP_KEY = \"lineProcessor.merger.startRegExp\";\n public static final String LINE_MERGER_END_REG_EXP_KEY = \"lineProcessor.merger.endRegExp\";\n public static final String LINE_MERGER_RESTART_IF_START_FOUND_KEY = \"lineProcessor.merger.restartIfStartFound\";\n public static final String LINE_MERGER_SEPARATOR_KEY = \"lineProcessor.merger.separator\";\n public static final String LINE_SPLITTER_SEPARATOR_REG_EXP_KEY = \"lineProcessor.splitter.separatorRegExp\";\n public static final String LINE_SPLITTER_ITEM_REG_EXP_KEY = \"lineProcessor.splitter.itemRegExp\";\n public static final String LINE_SPLITTER_APPEND_ORIGINAL_LOG_ROW_KEY = \"lineProcessor.splitter.appendOriginalLogRow\";\n \n // Decorators\n public static final String DECORATOR_CLASS_NAMES_KEY = \"decorator.classNames\";\n public static final String DECORATOR_PRE_EXPORT_CLASS_NAMES_KEY = \"decorator.preExport.classNames\";\n public static final String DECORATOR_PRE_MAIL_CLASS_NAMES_KEY = \"decorator.preMail.classNames\";\n public static final String DECORATOR_COMBINED_DECORATOR_CLASS_NAMES_KEY = \"decorator.combinedDecorator.classNames\";\n public static final String DECORATOR_USE_ORGANIZATION_MATCHER_KEY = \"decorator.useOrganizationMatcher\";\n public static final String DECORATOR_MATCH_IP_ADDRESS_KEY = \"decorator.organizationMatcher.matchIpAddress\";\n public static final String DECORATOR_MATCH_HOSTNAME_KEY = \"decorator.organizationMatcher.matchHostname\";\n public static final String DECORATOR_MATCH_ASN_KEY = \"decorator.organizationMatcher.matchAsn\";\n public static final String DECORATOR_COUNTRY_CODES_TO_ADD_KEY = \"decorator.countryCodeFromHostnameDecorator.countryCodesToAdd\";\n public static final String DECORATOR_USE_ASN_IN_LOG_ENTRY_KEY = \"decorator.asnGeoIpDecorator.useAsnInLogEntry\";\n public static final String DECORATOR_ADD_AS_NAME_KEY = \"decorator.asnGeoIpDecorator.addAsName\";\n public static final String DECORATOR_URL_TO_HOSTNAME_USE_PRIMARY_ORG_KEY = \"decorator.urlToHostnameDecorator.usePrimaryOrg\";\n public static final String DECORATOR_GEOLOCATION_FIELDS_TO_ADD_KEY = \"decorator.geolocationDecorator.fieldsToAdd\";\n \n // Parser\n public static final String PARSER_CLASS_NAME_KEY = \"parser.className\";\n public static final String PARSER_PARSE_ERROR_THRESHOLD_KEY = \"parser.parseErrorThreshold\";\n public static final String PARSER_MAX_NO_OF_PARSE_ERRORS = \"parser.maxNoOfParseErrors\";\n public static final String PARSER_TIME_STAMP_FORMAT_KEY = \"parser.timestampFormat\";\n public static final String PARSER_ADD_CURRENT_DATE_TO_TIMESTAMP_KEY = \"parser.addCurrentDateToTimestamp\";\n public static final String PARSER_DEFAULT_TIME_ZONE_KEY = \"parser.defaultTimeZone\";\n public static final String PARSER_CHECK_UNUSED_VARIABLES_KEY = \"parser.checkUnusedVariables\";\n public static final String PARSER_LINE_REG_EXP_KEY = \"parser.lineRegExp\";\n public static final String PARSER_ITEM_PREFIX = \"parser.item.\";\n public static final String PARSER_ADDITIONAL_ITEM_PREFIX = \"parser.item.additionalItem.\";\n public static final String PARSER_FREE_TEXT_KEY = \"parser.item.freeText\";\n public static final String PARSER_TRIM_VALUE_KEY = \"parser.trimValue\";\n public static final String PARSER_REMOVE_ENCLOSING_CHARS_FROM_VALUE_KEY = \"parser.removeEnclosingCharsFromValue\";\n public static final String PARSER_REWRITERS_KEY = \"parser.rewriters\";\n public static final String PARSER_REMOVE_TRAILING_SPACES_KEY = \"parser.removeTrailingSpaces\";\n public static final String PARSER_EXPAND_IP_RANGE_WITH_ZERO_OCTETS_KEY = \"parser.expandIpRangeWithZeroOctets\";\n \n // RSS\n public static final String RSS_FACTORY_CLASS_NAME_KEY = \"rss.factoryClassName\";\n public static final String RSS_FORMAT_KEY = \"rss.format\";\n // Job RSS\n public static final String RSS_JOB_ENABLED_KEY = \"rss.job.enabled\";\n public static final String RSS_JOB_FILE_KEY = \"rss.job.file\";\n public static final String RSS_JOB_CONTENT_TITLE_KEY = \"rss.job.content.title\";\n public static final String RSS_JOB_CONTENT_LINK_KEY = \"rss.job.content.link\";\n public static final String RSS_JOB_CONTENT_DESCRIPTION_KEY = \"rss.job.content.description\";\n public static final String RSS_JOB_CONTENT_AUTHOR_KEY = \"rss.job.content.author\";\n public static final String RSS_JOB_CONTENT_COPYRIGHT_KEY = \"rss.job.content.copyright\";\n public static final String RSS_JOB_MAX_NO_OF_ITEMS_KEY = \"rss.job.maxNoOfItems\";\n public static final String RSS_JOB_ITEM_EXPIRE_TIME_IN_MINUTES_KEY = \"rss.job.itemExpireTimeInMinutes\";\n // Stats RSS\n public static final String RSS_STATS_FORMAT_KEY = \"rss.stats.format\";\n public static final String RSS_STATS_FILE_KEY = \"rss.stats.file\";\n public static final String RSS_STATS_CONTENT_TITLE_KEY = \"rss.stats.content.title\";\n public static final String RSS_STATS_CONTENT_LINK_KEY = \"rss.stats.content.link\";\n public static final String RSS_STATS_CONTENT_DESCRIPTION_KEY = \"rss.stats.content.description\";\n public static final String RSS_STATS_CONTENT_AUTHOR_KEY = \"rss.stats.content.author\";\n public static final String RSS_STATS_CONTENT_COPYRIGHT_KEY = \"rss.stats.content.copyright\";\n public static final String RSS_STATS_MAX_NO_OF_ITEMS_KEY = \"rss.stats.maxNoOfItems\";\n public static final String RSS_STATS_ITEM_EXPIRE_TIME_IN_MINUTES_KEY = \"rss.stats.itemExpireTimeInMinutes\";\n\n // Report\n // Deprecated: flash.outputDir (use report.outputDir instead)\n public static final String FLASH_NO_OF_WEEKS_KEY = \"flash.noOfWeeks\";\n // Deprecated: flash.noOfWeeks (use report.statistics.noOfWeeks instead)\n public static final String FLASH_OUTPUT_DIR_KEY = \"flash.outputDir\";\n public static final String REPORT_CLASS_NAMES_KEY = \"report.classNames\";\n public static final String REPORT_OUTPUT_DIR_KEY = \"report.outputDir\";\n public static final String REPORT_TEMPLATE_DIR_KEY = \"report.templateDir\";\n public static final String REPORT_STATISTICS_NO_OF_WEEKS_KEY = \"report.statistics.noOfWeeks\";\n public static final String REPORT_GEOLOCATION_NO_OF_WEEKS_KEY = \"report.geolocation.noOfWeeks\";\n public static final String REPORT_GEOLOCATION_GENERATE_INTERNAL_REPORT_KEY = \"report.geolocation.generateInternalReport\";\n public static final String REPORT_GEOLOCATION_NO_OF_ENTRIES_IN_CITY_REPORT_KEY = \"report.geolocation.noOfEntriesInCityReport\";\n public static final String REPORT_GEOLOCATION_JOB_TYPE_KILL_LIST_KEY = \"report.geolocation.jobTypeKillList\";\n public static final String REPORT_GEOLOCATION_ORGANIZATION_TYPE_KILL_LIST_KEY = \"report.geolocation.organizationTypeKillList\";\n public static final String REPORT_GEOLOCATION_ORGANIZATION_TYPE_NAME_MAPPER_KEY = \"report.geolocation.organizationTypeNameMapper\";\n public static final String REPORT_ORGANIZATION_NO_OF_HOURS_KEY = \"report.organization.noOfHours\";\n public static final String REPORT_ORGANIZATION_JOB_TYPES_KEY = \"report.organization.jobTypes\";\n public static final String REPORT_ORGANIZATION_RECIPIENTS_KEY = \"report.organization.recipients\";\n \n // Import\n public static final String CONTACTS_IMPORT_FILE_KEY = \"import.dataFile\";\n \n // UI (management command line user interface)\n public static final String UI_DEFAULT_CC_KEY = \"ui.organizationHandler.defaultCountryCode\";\n public static final String UI_DEFAULT_LC_KEY = \"ui.organizationHandler.defaultLanguageCode\";\n public static final String UI_OUTPUT_DIR_KEY = \"ui.organizationHandler.outputDir\";\n public static final String UI_VALID_ROLES_KEY = \"ui.organizationHandler.validRoles\";\n public static final String UI_TIMESTAMP_FORMAT_KEY = \"ui.organizationHandler.timestampFormat\";\n \n // TicketHandler\n public static final String TICKET_HANDLER_CLASS = \"ticketHandler.className\";\n public static final String TICKET_HANDLER_CREATE_CHILD = \"ticketHandler.createChild\";\n public static final String TICKET_HANDLER_VALUE_KEYS = \"ticketHandler.valueKeys\";\n public static final String TICKET_HANDLER_SENDS_MAIL = \"ticketHandler.sendsMail\";\n public static final String TICKET_HANDLER_QUEUE_NAME = \"ticketHandler.queueName\";\n public static final String TICKET_HANDLER_USER = \"ticketHandler.user\";\n public static final String TICKET_HANDLER_PASSWORD = \"ticketHandler.password\";\n public static final String TICKET_HANDLER_TICKET_OWNER = \"ticketHandler.ticketOwner\";\n public static final String TICKET_HANDLER_URL = \"ticketHandler.url\";\n public static final String TICKET_HANDLER_RESOLVE_AFTER_SEND = \"ticketHandler.resolveAfterSend\";\n public static final String TICKET_HANDLER_RESOLVED_STATUS = \"ticketHandler.resolvedStatus\";\n public static final String TICKET_HANDLER_RESOLVE_SLEEP_TIME = \"ticketHandler.resolveSleepTime\";\n public static final String TICKET_HANDLER_TO_ADDRESS = \"ticketHandler.toAddress\";\n public static final String TICKET_HANDLER_FROM_ADDRESS = \"ticketHandler.fromAddress\";\n public static final String TICKET_HANDLER_ARCHIVE_ADDRESS = \"ticketHandler.archiveAddress\";\n \n \n\n /** Filename for Megatron global properties. */\n public static final String GLOBALS_PROPS_FILE = \"/etc/megatron/megatron-globals.properties\";\n\n /** Key in system properties for global properties file. */\n public static final String MEGATRON_CONFIG_FILE_KEY = \"megatron.configfile\";\n\n // Cannot use logging becuse it's not yet initialized.\n // private static final Logger log = Logger.getLogger(GlobalProperties.class);\n\n private static final String TRUE = \"true\";\n\n private static AppProperties singleton;\n\n private Map<String, String> globalProps;\n private TypedProperties globalTypedProps;\n private List<File> jobTypeFiles;\n private List<String> jobTypeNames;\n private List<String> inputFiles;\n\n\n /**\n * Returns singleton.\n */\n public static synchronized AppProperties getInstance() {\n if (singleton == null) {\n singleton = new AppProperties();\n }\n return singleton;\n }\n\n\n /**\n * Constructor. Private due to singleton.\n */\n private AppProperties() {\n // empty\n }\n\n\n /**\n * Loads properties file and parses specified command line arguments.\n */\n public void init(String[] args) throws MegatronException, CommandLineParseException {\n // -- Hard-coded properties\n // Use US as default locale. Dates with names, e.g. 04/Jul/2009, may otherwise be incorrect.\n Locale.setDefault(Locale.US);\n \n // Use UTC as default time-zone. All time-stamps in db are in UTC-time.\n TimeZone.setDefault(TimeZone.getTimeZone(\"UTC\"));\n\n // -- Read global properties and parse command line\n this.globalProps = loadGlobalProperties();\n parseCommandLine(args);\n this.globalTypedProps = new TypedProperties(globalProps, null);\n\n // -- init jobTypeFiles and jobTypeNames\n this.jobTypeFiles = listJobTypeFiles();\n this.jobTypeNames = new ArrayList<String>();\n for (Iterator<File> iterator = jobTypeFiles.iterator(); iterator.hasNext(); ) {\n String filename = iterator.next().getName();\n this.jobTypeNames.add(StringUtil.removeSuffix(filename, \".properties\"));\n }\n }\n\n\n /**\n * Returns global properties.<p>\n * Note: This method should be used sparsely. Use TypedProperties-object created by\n * createTypedPropertiesForCli or createTypedPropertiesForWeb instead.\n */\n public TypedProperties getGlobalProperties() {\n return globalTypedProps;\n }\n\n \n /**\n * Maps specified filename (without path) to a job-type.\n * \n * @return found job-type, or null if not found.\n */\n public String mapFilenameToJobType(String filename, boolean ignoreCliArgument) {\n String result = null;\n Logger log = Logger.getLogger(getClass());\n\n if (!ignoreCliArgument) { \n result = globalTypedProps.getString(TypedProperties.CLI_JOB_TYPE_KEY, null);\n if (result != null) {\n log.debug(\"Using job-type specified in CLI-argument: \" + result);\n return result;\n }\n }\n \n List<NameValuePair> nvList = globalTypedProps.getNameValuePairList(FILENAME_MAPPER_LIST_KEY, null);\n if (nvList != null) {\n for (Iterator<NameValuePair> iterator = nvList.iterator(); (result == null) && iterator.hasNext(); ) {\n NameValuePair nv = iterator.next();\n try {\n if (filename.matches(nv.getName())) {\n log.debug(\"Job-type found: \" + nv.getValue() + \". Filename '\" + filename + \"' matches reg-exp '\" + nv.getName() + \"'.\");\n result = nv.getValue();\n }\n } catch(PatternSyntaxException e) {\n log.error(\"Invalid reg-exp in filename mapper: \" + nv.getName());\n }\n }\n } else {\n log.error(\"Filename mapper not defined in config. Property name: \" + FILENAME_MAPPER_LIST_KEY);\n }\n \n return result;\n }\n\n \n /**\n * Creates properties for specified job-type, which includes CLI-arguments and global properties.\n * Use this method in the CLI application.\n */\n public TypedProperties createTypedPropertiesForCli(String jobType) throws MegatronException {\n try {\n Map<String, String> jobTypeProps = loadJobTypeProperties(jobType);\n return new TypedProperties(jobTypeProps, Collections.singletonList(globalProps));\n } catch (MegatronException e) {\n throw new MegatronException(\"Invalid job-type name: \" + jobType, e);\n } \n }\n\n \n /**\n * Creates properties for specified job-type, which includes specifed CLI-arguments and global properties.\n * CLI-properties are used in the web application, but assigned for each run.\n * Use this method in the web application.\n * \n * @param jobType job-type name, e.g. \"shadowserver-ddos\".\n * @param cliArgs CLI-arguments. Key: CLI-consts, e.g. CLI_NO_DB. Value: argument value, e.g. \"true\". \n */\n public TypedProperties createTypedPropertiesForWeb(String jobType, Map<String, String> cliArgs) throws MegatronException {\n try {\n Map<String, String> jobTypeProps = loadJobTypeProperties(jobType);\n for (Iterator<String> iterator = cliArgs.keySet().iterator(); iterator.hasNext(); ) {\n String key = iterator.next();\n String value = cliArgs.get(key);\n jobTypeProps.put(key, value);\n }\n return new TypedProperties(jobTypeProps, Collections.singletonList(globalProps));\n } catch (MegatronException e) {\n throw new MegatronException(\"Invalid job-type name: \" + jobType, e);\n } \n }\n\n\n /**\n * Returns input filenames specified at the command line.\n */\n public List<String> getInputFiles() {\n return this.inputFiles;\n }\n\n \n public List<File> getJobTypeFiles() {\n return this.jobTypeFiles;\n }\n\n\n public List<String> getJobTypeNames() {\n return this.jobTypeNames;\n }\n\n\n public String getJobTypeConfigDir() {\n return globalTypedProps.getString(JOB_TYPE_CONFIG_DIR_KEY, null);\n }\n \n \n public String getJdbcUrl() {\n // Format: jdbc:mysql://{db.server}:{db.port}/{db.name}\n String result = globalTypedProps.getString(JDBC_URL_KEY, \"jdbc:mysql://{db.server}:{db.port}/{db.name}\");\n String dbServer = globalTypedProps.getString(DB_SERVER_KEY, \"127.0.0.1\");\n String dbPort = globalTypedProps.getString(DB_PORT_KEY, \"3306\");\n String dbName = globalTypedProps.getString(DB_NAME_KEY, \"ossec\");\n\n result = StringUtil.replace(result, \"{db.server}\", dbServer);\n result = StringUtil.replace(result, \"{db.port}\", dbPort);\n result = StringUtil.replace(result, \"{db.name}\", dbName);\n\n return result;\n }\n\n \n /**\n * Loads global properties.\n *\n * @throws MegatronException if global properties cannot be read.\n */\n private Map<String, String> loadGlobalProperties() throws MegatronException {\n String filename = System.getProperty(MEGATRON_CONFIG_FILE_KEY);\n filename = (filename != null) ? filename : GLOBALS_PROPS_FILE;\n return loadPropertiesFile(filename);\n }\n\n\n /**\n * Loads job-type properties.\n *\n * @throws IOException if properties cannot be read.\n */\n private Map<String, String> loadJobTypeProperties(String jobTypeName) throws MegatronException {\n String filename = FileUtil.concatPath(getJobTypeConfigDir(), jobTypeName + \".properties\");\n Map<String, String> result = loadPropertiesFile(filename); \n result.put(JOB_TYPE_NAME_KEY, jobTypeName);\n return result;\n }\n\n\n /**\n * Loads specified properties file.\n *\n * @throws MegatronException if global properties cannot be read.\n */\n private Map<String, String> loadPropertiesFile(String filename) throws MegatronException {\n // The class Properties cannot be used:\n // 1. Back-slashes in regular expressions are removed.\n // 2. Order is not preserved.\n\n // LinkedHashMap preserves insertion order.\n Map<String, String> result = new LinkedHashMap<String, String>();\n\n final String nameValueSeparator = \"=\";\n\n File file = new File(filename);\n BufferedReader in = null;\n try {\n in = new BufferedReader(new InputStreamReader(new FileInputStream(file), \"UTF-8\"));\n\n int lineNo = 0;\n String line = null;\n while ((line = in.readLine()) != null) {\n ++lineNo;\n String trimmedLine = line.trim();\n if ((trimmedLine.length() == 0) || trimmedLine.startsWith(Constants.CONFIG_COMMENT_PREFIX)) {\n continue;\n }\n\n // split line into name-value\n int index = line.indexOf(nameValueSeparator);\n if ((index == -1) || (index == 0)) {\n String msg = \"Parse error at line \" + lineNo + \": Separator not found.\";\n throw new IOException(msg);\n }\n String name = line.substring(0, index);\n String value = ((index + 1) < line.length()) ? line.substring(index + 1, line.length()) : \"\";\n result.put(name, value);\n }\n } catch (IOException e) {\n String msg = \"Cannot read properties file: \" + file.getAbsolutePath();\n System.err.println(msg);\n throw new MegatronException(msg, e);\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (IOException e) {\n String msg = \"Cannot close properties file: \" + file.getAbsolutePath();\n System.err.println(msg);\n throw new MegatronException(msg, e);\n }\n }\n }\n\n return result;\n }\n\n\n /**\n * Parsers specified command line arguments and adds them to properties map.\n */\n @SuppressWarnings(\"unused\")\n private void parseCommandLine(String[] args) throws MegatronException, CommandLineParseException {\n if (args == null) {\n return;\n }\n\n inputFiles = new ArrayList<String>();\n for (int i = 0; i < args.length; i++) {\n String arg = args[i].trim();\n\n if (arg.startsWith(\"-\")) {\n if (arg.equals(\"--version\") || arg.equals(\"-v\")) {\n throw new CommandLineParseException(CommandLineParseException.SHOW_VERSION_ACTION);\n } else if (arg.equals(\"--help\") || arg.equals(\"-h\")) {\n throw new CommandLineParseException(CommandLineParseException.SHOW_USAGE_ACTION);\n } else if (arg.equals(\"--slurp\") || arg.equals(\"-s\")) {\n globalProps.put(TypedProperties.CLI_SLURP_KEY, TRUE);\n } else if (arg.equals(\"--export\") || arg.equals(\"-e\")) {\n globalProps.put(TypedProperties.CLI_EXPORT_KEY, TRUE);\n } else if (arg.equals(\"--delete\") || arg.equals(\"-d\") || arg.equals(\"--delete-all\") || arg.equals(\"-D\")) {\n // job specified after delete switch? \n int nextIndex = i + 1;\n if ((nextIndex < args.length) && !args[nextIndex].startsWith(\"-\")) {\n i = nextIndex;\n globalProps.put(TypedProperties.CLI_JOB_KEY, args[i]);\n } else {\n // otherwise --job must be present\n List<String> argList = new ArrayList<String>(Arrays.asList(args));\n if (!(argList.contains(\"--job\") || argList.contains(\"--j\"))) {\n throw new CommandLineParseException(\"Job name not specified.\");\n }\n }\n \n if (arg.equals(\"--delete\") || arg.equals(\"-d\")) {\n globalProps.put(TypedProperties.CLI_DELETE_KEY, TRUE);\n } else {\n globalProps.put(TypedProperties.CLI_DELETE_ALL_KEY, TRUE); \n }\n } else if (arg.equals(\"--job\") || arg.equals(\"-j\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n globalProps.put(TypedProperties.CLI_JOB_KEY, args[i]);\n } else if (arg.equals(\"--job-type\") || arg.equals(\"-t\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n globalProps.put(TypedProperties.CLI_JOB_TYPE_KEY, args[i]);\n } else if (arg.equals(\"--output-dir\") || arg.equals(\"-o\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n String outputDirStr = args[i];\n File outputDir = new File(outputDirStr);\n if (!outputDir.isDirectory()) {\n throw new MegatronException(\"Output directory not found: \" + outputDir.getAbsolutePath());\n }\n globalProps.put(TypedProperties.CLI_OUTPUT_DIR_KEY, outputDirStr);\n } else if (arg.equals(\"--id\") || arg.equals(\"-i\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n String idStr = args[i];\n try {\n long id = Long.parseLong(idStr);\n if (id <= 0L) {\n throw new NumberFormatException(\"Id is zero or negative.\"); \n }\n } catch (NumberFormatException e) {\n throw new CommandLineParseException(\"Invalid RTIR id (--id): \" + idStr, e);\n }\n globalProps.put(TypedProperties.CLI_ID_KEY, idStr);\n } else if (arg.equals(\"--prio\") || arg.equals(\"-p\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n String prioStr = args[i];\n// Skip check. OK with a list of intervals, e.g. --prio 55-60,70-75\n// try {\n// long prio = Long.parseLong(prioStr);\n// if ((prio < 0L) || (prio > 100L)) {\n// throw new NumberFormatException(\"Prio is not in range.\"); \n// }\n// } catch (NumberFormatException e) {\n// String msg = \"Invalid prio (--prio): \" + prioStr + \". Use --list-prios to list priorities.\";\n// throw new CommandLineParseException(msg, e);\n// }\n globalProps.put(TypedProperties.CLI_PRIO_KEY, prioStr);\n } else if (arg.equals(\"--list-prios\") || arg.equals(\"-P\")) {\n globalProps.put(TypedProperties.CLI_LIST_PRIOS_KEY, TRUE);\n } else if (arg.equals(\"--list-jobs\") || arg.equals(\"-l\")) {\n globalProps.put(TypedProperties.CLI_LIST_JOBS_KEY, TRUE);\n // days specified after switch?\n int nextIndex = i + 1;\n if ((nextIndex < args.length) && !args[nextIndex].startsWith(\"-\")) {\n i = nextIndex;\n String val = args[i];\n try {\n int days = Integer.parseInt(val);\n if ((days <= 0) || (days > 1000)) {\n throw new NumberFormatException(\"No. of days must be in the range 1-1000.\"); \n }\n } catch (NumberFormatException e) {\n throw new CommandLineParseException(\"Invalid no. of days (--list-jobs): \" + val, e);\n }\n globalProps.put(TypedProperties.CLI_DAYS_IN_LIST_JOBS_KEY, val);\n }\n } else if (arg.equals(\"--whois\") || arg.equals(\"-w\")) {\n globalProps.put(TypedProperties.CLI_WHOIS_KEY, TRUE);\n if (++i >= args.length) {\n throw new CommandLineParseException(\"Missing list of IPs and hostnames (or file) to argument \" + arg);\n }\n while (i < args.length) {\n inputFiles.add(args[i]); \n ++i;\n }\n } else if (arg.equals(\"--job-info\") || arg.equals(\"-I\")) {\n // job specified after switch? \n int nextIndex = i + 1;\n if ((nextIndex < args.length) && !args[nextIndex].startsWith(\"-\")) {\n i = nextIndex;\n globalProps.put(TypedProperties.CLI_JOB_KEY, args[i]);\n } else {\n // otherwise --job must be present\n List<String> argList = new ArrayList<String>(Arrays.asList(args));\n if (!(argList.contains(\"--job\") || argList.contains(\"--j\"))) {\n throw new CommandLineParseException(\"Job name not specified.\");\n }\n }\n globalProps.put(TypedProperties.CLI_JOB_INFO_KEY, TRUE);\n } else if (arg.equals(\"--no-db\") || arg.equals(\"-n\")) {\n globalProps.put(TypedProperties.CLI_NO_DB_KEY, TRUE);\n } else if (arg.equals(\"--stdout\") || arg.equals(\"-S\")) {\n globalProps.put(TypedProperties.CLI_STDOUT_KEY, TRUE);\n } else if (arg.equals(\"--import-contacts\")) {\n globalProps.put(TypedProperties.CLI_IMPORT_CONTACTS_KEY, TRUE);\n } else if (arg.equals(\"--import-bgp\")) {\n globalProps.put(TypedProperties.CLI_IMPORT_BGP_KEY, TRUE);\n } else if (arg.equals(\"--update-netname\")) {\n globalProps.put(TypedProperties.CLI_UPDATE_NETNAME_KEY, TRUE);\n } else if (arg.equals(\"--add-addresses\") || arg.equals(\"--delete-addresses\")) {\n if (arg.equals(\"--delete-addresses\")) {\n globalProps.put(TypedProperties.CLI_DELETE_ADDRESSES_KEY, TRUE);\n } else {\n globalProps.put(TypedProperties.CLI_ADD_ADDRESSES_KEY, TRUE);\n }\n ++i;\n if ((i < args.length) && !args[i].startsWith(\"-\")) {\n globalProps.put(TypedProperties.CLI_ADDRESSES_FILE_KEY, args[i]);\n } else {\n throw new CommandLineParseException(\"Missing address file to argument \" + arg);\n }\n } else if (arg.equals(\"--create-rss\")) {\n globalProps.put(TypedProperties.CLI_CREATE_STATS_RSS_KEY, TRUE);\n } else if (arg.equals(\"--create-xml\")) {\n // --create-xml is deprecated. Use --create-reports instead. \n globalProps.put(TypedProperties.CLI_CREATE_FLASH_XML_KEY, TRUE);\n } else if (arg.equals(\"--create-reports\")) {\n globalProps.put(TypedProperties.CLI_CREATE_REPORTS_KEY, TRUE);\n } else if (arg.equals(\"--create-report\")) {\n ++i;\n if (i == args.length) {\n throw new CommandLineParseException(\"Missing argument to \" + arg);\n }\n String className = args[i];\n try {\n Class<?> reportGeneratorClass = Class.forName(className);\n IReportGenerator reportGenerator = (IReportGenerator)reportGeneratorClass.newInstance();\n } catch (Exception e) {\n // ClassNotFoundException, InstantiationException, IllegalAccessException\n String msg = \"Argument for --create-report must be a Java-class that implements IReportGenerator: \" + className;\n throw new MegatronException(msg, e);\n }\n globalProps.put(TypedProperties.CLI_CREATE_REPORT_KEY, className);\n } else if (arg.equals(\"--ui-org\")) {\n globalProps.put(TypedProperties.CLI_UI_ORGANIZATIONS, TRUE); \n } else if (arg.equals(\"--mail-dry-run\") || arg.equals(\"-1\")) {\n globalProps.put(TypedProperties.CLI_MAIL_DRY_RUN_KEY, TRUE);\n } else if (arg.equals(\"--mail-dry-run2\") || arg.equals(\"-2\")) {\n globalProps.put(TypedProperties.CLI_MAIL_DRY_RUN2_KEY, TRUE);\n } else if (arg.equals(\"--mail\") || arg.equals(\"-m\")) {\n globalProps.put(TypedProperties.CLI_MAIL_KEY, TRUE);\n } else if (arg.equals(\"--use-org2\") || arg.equals(\"-b\")) {\n globalProps.put(TypedProperties.CLI_USE_ORG2_KEY, TRUE);\n } else {\n throw new CommandLineParseException(\"Unrecognized option: \" + arg);\n }\n } else {\n File file = new File(arg);\n if (!file.canRead()) {\n throw new MegatronException(\"Cannot read input file: \" + file.getAbsolutePath());\n }\n inputFiles.add(arg);\n }\n }\n }\n\n\n private List<File> listJobTypeFiles() throws MegatronException {\n String dirStr = globalProps.get(JOB_TYPE_CONFIG_DIR_KEY);\n if (StringUtil.isNullOrEmpty(dirStr)) {\n throw new MegatronException(\"Job-type config dir not specified in global properties.\");\n }\n File file = new File(dirStr);\n File[] files = file.listFiles(new FileFilter() {\n @Override\n public boolean accept(File pathname) {\n return pathname.getName().endsWith(\".properties\");\n }\n });\n if (files == null) {\n throw new MegatronException(\"Cannot list job-type config files in directory: \" + file.getAbsolutePath());\n }\n\n List<File> result = new ArrayList<File>(Arrays.asList(files));\n return result;\n }\n\n}", "public class JobContext {\n private TypedProperties props;\n private Job job;\n private DbManager dbManager;\n \n /** Time job was started (in ms). */\n private long startedTimestamp;\n\n /** Total number of lines in file. */\n private long noOfLines = -1L;\n\n /** Line number in file that is currently processing. */\n private long lineNo = 0L;\n\n /** As lineNo, but after optional ILineProcessor-step which merge or split lines. */\n private long lineNoAfterProcessor = 0L;\n \n /** No. of lines filtered. If a line processor is used this number may be skewed (filters may exist before and after a merger or splitter). */\n private long noOfFilteredLines = 0L;\n\n /** No. of parse errors. */\n private long noOfParseExceptions = 0L;\n\n /** No. of saved log entries. */\n private long noOfSavedEntries = 0L;\n\n /** No. of log entries connected to high priority organizations. */\n private long noOfHighPriorityEntries = 0L;\n\n /** No. of exported log entries. */\n private long noOfExportedEntries = 0L;\n\n /** Name-value table to store untyped data that needs to be shared e.g. between two decorators. */\n private Map<String, Object> additionalData;\n\n \n /**\n * Constructor.\n */\n public JobContext(TypedProperties props, Job job) {\n this.props = props;\n this.job = job;\n }\n\n \n /**\n * Displays message to operator. If CLI, the console is used.\n * If web application, the message is appended to a buffer that\n * is displayed at the end of the job. \n */\n public void writeToConsole(String msg) {\n System.out.println(msg);\n \n // TODO add support for web application\n }\n\n \n public TypedProperties getProps() {\n return this.props;\n }\n\n \n public Job getJob() {\n return this.job;\n }\n\n \n public DbManager getDbManager() {\n return dbManager;\n }\n\n\n public void setDbManager(DbManager dbManager) {\n this.dbManager = dbManager;\n }\n\n \n public long getLineNo() {\n return lineNo;\n }\n\n\n public void incLineNo(int incValue) {\n this.lineNo += incValue;\n }\n\n \n public long getLineNoAfterProcessor() {\n return lineNoAfterProcessor;\n }\n\n\n public void incLineNoAfterProcessor(int incValue) {\n this.lineNoAfterProcessor += incValue;\n }\n\n \n public long getNoOfFilteredLines() {\n return noOfFilteredLines;\n }\n\n\n public void incNoOfFilteredLines(int incValue) {\n this.noOfFilteredLines += incValue;\n }\n\n\n public long getNoOfParseExceptions() {\n return noOfParseExceptions;\n }\n\n\n public void incNoOfParseExceptions(int incValue) {\n this.noOfParseExceptions += incValue;\n }\n\n \n public long getNoOfSavedEntries() {\n return noOfSavedEntries;\n }\n\n\n public void incNoOfSavedEntries(int incValue) {\n this.noOfSavedEntries += incValue;\n }\n\n \n public long getNoOfHighPriorityEntries() {\n return noOfHighPriorityEntries;\n }\n\n\n public void incNoOfHighPriorityEntries(int incValue) {\n this.noOfHighPriorityEntries += incValue;\n }\n\n \n public long getNoOfExportedEntries() {\n return noOfExportedEntries;\n }\n\n\n public void incNoOfExportedEntries(int incValue) {\n this.noOfExportedEntries += incValue;\n }\n\n \n public long getStartedTimestamp() {\n return startedTimestamp;\n }\n\n\n public void setStartedTimestamp(long startedTimestamp) {\n this.startedTimestamp = startedTimestamp;\n }\n\n\n public long getNoOfLines() {\n return noOfLines;\n }\n\n\n public void setNoOfLines(long noOfLines) {\n this.noOfLines = noOfLines;\n }\n \n \n public Object getAdditionalData(String key) {\n if (additionalData == null) {\n return null;\n }\n return additionalData.get(key);\n }\n \n \n public void addAdditionalData(String key, Object value) {\n if (additionalData == null) {\n additionalData = new HashMap<String, Object>();\n }\n additionalData.put(key, value);\n }\n\n\n}", "public class TypedProperties {\n // Keys for CLI arguments. \n public static final String CLI_SLURP_KEY = \"cli.slurp\";\n public static final String CLI_EXPORT_KEY = \"cli.export\";\n public static final String CLI_DELETE_KEY = \"cli.delete\"; \n public static final String CLI_DELETE_ALL_KEY = \"cli.deleteAll\"; \n public static final String CLI_JOB_KEY = \"cli.job\";\n public static final String CLI_JOB_TYPE_KEY = \"cli.jobType\";\n public static final String CLI_OUTPUT_DIR_KEY = \"cli.outputDir\";\n public static final String CLI_ID_KEY = \"cli.id\";\n public static final String CLI_PRIO_KEY = \"cli.prio\"; \n public static final String CLI_LIST_PRIOS_KEY = \"cli.listPrios\";\n public static final String CLI_LIST_JOBS_KEY = \"cli.listJobs\";\n public static final String CLI_WHOIS_KEY = \"cli.whois\"; \n public static final String CLI_DAYS_IN_LIST_JOBS_KEY = \"cli.daysInListJobs\";\n public static final String CLI_JOB_INFO_KEY = \"cli.jobInfo\";\n public static final String CLI_NO_DB_KEY = \"cli.noDb\";\n public static final String CLI_STDOUT_KEY = \"cli.stdout\";\n public static final String CLI_IMPORT_CONTACTS_KEY = \"cli.importContacts\";\n public static final String CLI_IMPORT_BGP_KEY = \"cli.importBgp\";\n public static final String CLI_UPDATE_NETNAME_KEY = \"cli.updateNetname\";\n public static final String CLI_ADD_ADDRESSES_KEY = \"cli.addAddresses\";\n public static final String CLI_DELETE_ADDRESSES_KEY = \"cli.deleteAddresses\";\n public static final String CLI_ADDRESSES_FILE_KEY = \"cli.addressFileKey\";\n public static final String CLI_CREATE_STATS_RSS_KEY = \"cli.createStatsRss\";\n public static final String CLI_CREATE_FLASH_XML_KEY = \"cli.createFlashXml\";\n public static final String CLI_CREATE_REPORTS_KEY = \"cli.createReports\";\n public static final String CLI_CREATE_REPORT_KEY = \"cli.createReport\"; \n public static final String CLI_UI_ORGANIZATIONS = \"cli.uiOrganizations\"; \n public static final String CLI_MAIL_DRY_RUN_KEY = \"cli.mailDryRun\";\n public static final String CLI_MAIL_DRY_RUN2_KEY = \"cli.mailDryRun2\";\n public static final String CLI_MAIL_KEY = \"cli.mail\";\n public static final String CLI_USE_ORG2_KEY = \"cli.useOrg2\";\n\n private static final Logger log = Logger.getLogger(TypedProperties.class);\n\n /** Strings that is converted to \"true\" (case insensitive). */\n private static final String[] TRUE_STRINGS = { \"1\", \"true\", \"on\" };\n\n /** Main properies. */\n private Map<String, String> props;\n\n /** Properties to look in if value is missing in props. Starts from the end. May be null. */\n private LinkedList<Map<String, String>> additionalPropsList;\n\n\n /**\n * Constructor.\n *\n * @param props Properties (not null).\n * @param additionalPropsList Properties to look in if value is missing in props. Starts from the end. May be null.\n */\n public TypedProperties(Map<String, String> props, List<Map<String, String>> additionalPropsList) {\n if (props == null) {\n throw new NullPointerException(\"Argument is null: props\");\n }\n\n this.props = props;\n if (additionalPropsList != null) {\n this.additionalPropsList = new LinkedList<Map<String, String>>(additionalPropsList);\n }\n }\n\n \n /**\n * Adds specified additional properties, which will override already \n * defined properties. Use this method to add or modified properties. \n */\n public void addAdditionalProps(Map<String, String> props) {\n this.additionalPropsList.add(props);\n }\n \n \n /**\n * Returns property value for specified key. If property is not found in\n * properties, or in additional properties, specifed default value is\n * returned.\n *\n * @param key name of property.\n * @param defaultValue value returned if property was not found, or in\n * case of exception.\n */\n public String getString(String key, String defaultValue) {\n String result = props.get(key);\n\n if ((result == null) && (additionalPropsList != null)) {\n for (ListIterator<Map<String, String>> iterator = additionalPropsList.listIterator(additionalPropsList.size()); iterator.hasPrevious(); ) {\n Map<String, String> map = iterator.previous();\n result = map.get(key);\n if (result != null) {\n break;\n }\n }\n }\n\n return (result != null) ? result : defaultValue;\n }\n\n\n /**\n * Returns string array for specified key.<p>\n * Format in properties file:<pre>\n * name.0=value0\n * name.1=value1\n * [...]\n * </pre>\n *\n * @param key name of property.\n * @param defaultValue value returned if property was not found.\n */\n public String[] getStringList(String key, String[] defaultValue) {\n String[] result = null;\n\n // find map that contains list\n Map<String, String> map = null;\n if (props.containsKey(key + \".0\") || props.containsKey(key + \".1\")) {\n map = props;\n } else if (additionalPropsList != null) {\n for (ListIterator<Map<String, String>> iterator = additionalPropsList.listIterator(additionalPropsList.size()); iterator.hasPrevious(); ) {\n Map<String, String> candidateMap = iterator.previous();\n if (candidateMap.containsKey(key + \".0\") || candidateMap.containsKey(key + \".1\")) {\n map = candidateMap;\n break;\n }\n }\n }\n\n // create result from list in map\n if (map != null) {\n List<String> resultList = new ArrayList<String>();\n int i = map.containsKey(key + \".0\") ? 0 : 1;\n while (true) {\n String value = map.get(key + \".\" + Integer.toString(i++));\n if (value != null) {\n resultList.add(value);\n } else {\n break;\n }\n }\n result = resultList.toArray(new String[resultList.size()]);\n }\n\n return (result != null) ? result : defaultValue;\n }\n\n \n /**\n * Returns string array for property value that is comma separated.\n */\n public String[] getStringListFromCommaSeparatedValue(String key, String[] defaultValue, boolean trim) {\n String str = getString(key, null);\n if (str == null) {\n return defaultValue;\n }\n\n String[] result = str.split(\",\");\n if (result != null) {\n for (int i = 0; i < result.length; i++) {\n result[i] = result[i].trim();\n }\n } else {\n result = defaultValue;\n }\n \n return result;\n }\n\n \n /**\n * @see #getStringList(String, String[])\n */\n public List<NameValuePair> getNameValuePairList(String key, List<NameValuePair> defaultList) {\n List<NameValuePair> result = null;\n\n final String delim = \"=\";\n String[] strList = getStringList(key, null);\n if (strList != null) {\n result = new ArrayList<NameValuePair>(strList.length);\n for (int i = 0; i < strList.length; i++) {\n String[] headTail = StringUtil.splitHeadTail(strList[i], delim, false);\n if (StringUtil.isNullOrEmpty(headTail[0]) || StringUtil.isNullOrEmpty(headTail[1])) {\n String msg = \"Cannot parse NameValuePair-list property: \" + key + \", value: \" + Arrays.toString(strList);\n log.error(msg);\n result = defaultList;\n break;\n }\n result.add(new NameValuePair(headTail[0], headTail[1]));\n }\n }\n\n return result;\n }\n\n\n /**\n * @see #getString(String, String)\n */\n public long getLong(String key, long defaultValue) {\n String longStr = getString(key, null);\n\n long result = defaultValue;\n if (longStr != null) {\n try {\n result = Long.parseLong(longStr.trim());\n } catch (NumberFormatException e) {\n String msg = \"Cannot parse integer property: \" + key + \", value: \" + longStr;\n log.error(msg, e);\n result = defaultValue;\n }\n }\n\n return result;\n }\n\n\n /**\n * @see #getString(String, String)\n */\n public int getInt(String key, int defaultValue) {\n return (int)getLong(key, defaultValue);\n }\n\n\n /**\n * @see #getString(String, String)\n */\n public double getDouble(String key, double defaultValue) {\n String doubleStr = getString(key, null);\n\n double result = defaultValue;\n if (doubleStr != null) {\n try {\n result = Double.parseDouble(doubleStr.trim());\n } catch (NumberFormatException e) {\n String msg = \"Cannot parse decimal number property: \" + key + \", value: \" + doubleStr;\n log.error(msg, e);\n result = defaultValue;\n }\n }\n\n return result;\n }\n\n\n /**\n * @see #getString(String, String)\n */\n public float getFloat(String key, float defaultValue) {\n return (float)getDouble(key, defaultValue);\n }\n\n\n /**\n * @see #getString(String, String)\n */\n public boolean getBoolean(String key, boolean defaultValue) {\n String booleanStr = getString(key, null);\n\n boolean result = false;\n if (booleanStr != null) {\n booleanStr = booleanStr.trim();\n for (int i = 0; i < TRUE_STRINGS.length; i++) {\n if (TRUE_STRINGS[i].equalsIgnoreCase(booleanStr)) {\n result = true;\n break;\n }\n }\n } else {\n result = defaultValue;\n }\n\n return result;\n }\n\n\n /**\n * @see #getString(String, String)\n * @see se.sitic.megatron.util.DateUtil#DATE_TIME_FORMAT_WITH_SECONDS\n */\n public Date getDate(String key, String format, Date defaultValue) {\n String dateStr = getString(key, null);\n\n Date result = defaultValue;\n if (dateStr != null) {\n try {\n result = DateUtil.parseDateTime(format, dateStr);\n } catch (ParseException e) {\n String msg = \"Cannot parse date property: \" + key + \", value: \" + dateStr;\n log.error(msg, e);\n result = defaultValue;\n }\n }\n\n return result;\n }\n\n\n /**\n * Returns true if specified property exists.\n *\n * @param key name of property.\n */\n public boolean existsProperty(String key) {\n return (getString(key, null) != null);\n }\n\n \n /**\n * Returns all property keys. \n */\n public Set<String> keySet() {\n Set<String> result = new HashSet<String>();\n\n result.addAll(props.keySet());\n for (Iterator<Map<String, String>> iterator = additionalPropsList.iterator(); iterator.hasNext(); ) {\n result.addAll(iterator.next().keySet());\n }\n return result;\n }\n\n \n /**\n * Returns CLI switch: --slurp\n */\n public boolean isSlurp() {\n return getBoolean(CLI_SLURP_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --export\n */\n public boolean isExport() {\n return getBoolean(CLI_EXPORT_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --delete\n */\n public boolean isDelete() {\n return getBoolean(CLI_DELETE_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --delete-all\n */\n public boolean isDeleteAll() {\n return getBoolean(CLI_DELETE_ALL_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --job\n */\n public String getJob() {\n return getString(CLI_JOB_KEY, \"\");\n }\n\n \n /**\n * Returns CLI switch: --job-type\n */\n public String getJobType() {\n return getString(CLI_JOB_TYPE_KEY, \"\");\n }\n\n \n /**\n * Returns CLI switch: --output-dir\n */\n public String getOutputDir() {\n String result = getString(CLI_OUTPUT_DIR_KEY, \"\");\n if (result.length() == 0) {\n result = getString(AppProperties.OUTPUT_DIR_KEY, \"tmp/export\");\n }\n return result;\n }\n\n \n /**\n * Returns CLI switch: --id\n */\n public String getParentTicketId() {\n return getString(CLI_ID_KEY, \"\");\n }\n\n \n /**\n * Returns CLI switch: --prio\n */\n public String getPrio() {\n return getString(CLI_PRIO_KEY, \"\");\n }\n\n \n /**\n * Returns CLI switch: --list-prios\n */\n public boolean isListPrios() {\n return getBoolean(CLI_LIST_PRIOS_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --list-jobs\n */\n public boolean isListJobs() {\n return getBoolean(CLI_LIST_JOBS_KEY, false);\n }\n\n \n /**\n * Returns no of days (if specified) for --list-jobs. \n */\n public int getDaysInListJobs() {\n int defaultVal = 2;\n String val = getString(CLI_DAYS_IN_LIST_JOBS_KEY, defaultVal + \"\");\n try {\n return Integer.parseInt(val);\n } catch (NumberFormatException e) {\n log.error(\"Cannot not parse --list-jobs integer value: \" + val);\n return defaultVal;\n }\n }\n\n \n /**\n * Returns CLI switch: --job-info\n */\n public boolean isJobInfo() {\n return getBoolean(CLI_JOB_INFO_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --whois\n */\n public boolean isWhois() {\n return getBoolean(CLI_WHOIS_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --no-db\n */\n public boolean isNoDb() {\n return getBoolean(CLI_NO_DB_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --stdout\n */\n public boolean isStdout() {\n return getBoolean(CLI_STDOUT_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --import-contacts\n */\n public boolean isImportContacts() {\n return getBoolean(CLI_IMPORT_CONTACTS_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --import-bgp\n */\n public boolean isImportBgp() {\n return getBoolean(CLI_IMPORT_BGP_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --update-netname\n */\n public boolean isUpdateNetname() {\n return getBoolean(CLI_UPDATE_NETNAME_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --add-addresses\n */\n public boolean isAddAddresses() {\n return getBoolean(CLI_ADD_ADDRESSES_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --delete-addresses\n */\n public boolean isDeleteAddresses() {\n return getBoolean(CLI_DELETE_ADDRESSES_KEY, false);\n }\n\n \n /**\n * Returns address file for CLI switch --add-addresses or --delete-addresses. \n */\n public String getAddressesFile() {\n return getString(CLI_ADDRESSES_FILE_KEY, \"\");\n }\n\n \n /**\n * Returns CLI switch: --create-rss\n */\n public boolean isCreateStatsRss() {\n return getBoolean(CLI_CREATE_STATS_RSS_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --create-xml\n * <p>\n * --create-xml is deprecated. Use --create-reports instead.\n */\n public boolean isCreateFlashXml() {\n return getBoolean(CLI_CREATE_FLASH_XML_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --create-reports\n */\n public boolean isCreateReports() {\n return getBoolean(CLI_CREATE_REPORTS_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --create-report\n */\n public String getCreateReport() {\n return getString(CLI_CREATE_REPORT_KEY, null);\n }\n\n \n /**\n * Returns CLI switch: --ui-org\n */\n public boolean isUiOrg() {\n return getBoolean(CLI_UI_ORGANIZATIONS, false);\n }\n\n\n /**\n * Returns CLI switch: --mail-dry-run\n */\n public boolean isMailDryRun() {\n return getBoolean(CLI_MAIL_DRY_RUN_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --mail-dry-run2\n */\n public boolean isMailDryRun2() {\n return getBoolean(CLI_MAIL_DRY_RUN2_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --mail\n */\n public boolean isMail() {\n return getBoolean(CLI_MAIL_KEY, false);\n }\n\n \n /**\n * Returns CLI switch: --use-org2\n */\n public boolean isUseOrg2() {\n return getBoolean(CLI_USE_ORG2_KEY, false);\n }\n\n}", "public abstract class Constants {\n\n /** Line break in files etc. */\n public static final String LINE_BREAK = \"\\n\";\n\n /** UTF-8 character-set in Java core API. */\n public static final String UTF8 = \"UTF-8\";\n\n /** ISO-8859 character-set in Java core API. */\n public static final String ISO8859 = \"ISO-8859-1\";\n\n /** MIME-type for plain text. */\n public static final String MIME_TEXT_PLAIN = \"text/plain\";\n \n /** Comments in config files starts with this string. */\n public static final String CONFIG_COMMENT_PREFIX = \"#\";\n\n /** Hash algoritm to use. */\n public static final String DIGEST_ALGORITHM = \"md5\";\n\n /** Job type name to use when name is missing in the job_type table. */\n public static final String DEFAULT_JOB_TYPE = \"default\";\n \n // Values for the property filter.countryCodeFilter.organizationToFilter\n // and filter.asnFilter.organizationToFilter\n public static final String ORGANIZATION_PRIMARY = \"primary\";\n public static final String ORGANIZATION_SECONDARY = \"secondary\";\n public static final String ORGANIZATION_BOTH = \"both\";\n\n // Additional format strings for parser.timestampFormat.\n public static final String TIME_STAMP_FORMAT_EPOCH_IN_SEC = \"epochInSec\";\n public static final String TIME_STAMP_FORMAT_EPOCH_IN_MS = \"epochInMs\";\n public static final String TIME_STAMP_FORMAT_WINDOWS_EPOCH = \"windowsEpoch\";\n \n}", "public abstract class IpAddressUtil {\n private static final Logger log = Logger.getLogger(IpAddressUtil.class);\n private static final int HOST_NAME_CACHE_MAX_ENTRIES = 2048;\n \n private static Map<Long, String> hostNameCache;\n private static boolean useDnsJava;\n private static boolean useSimpleResolver; \n private static SimpleResolver simpleResolver;\n \n private static final Matcher IP_ADDRESS_MATCHER = Pattern.compile(\"(\\\\d{1,3})\\\\.(\\\\d{1,3})\\\\.(\\\\d{1,3})\\\\.(\\\\d{1,3})\").matcher(\"\");\n \n \n static {\n TypedProperties globalProps = AppProperties.getInstance().getGlobalProperties();\n\n if (globalProps.existsProperty(AppProperties.USE_DNS_JAVA_KEY) && !globalProps.existsProperty(AppProperties.DNS_JAVA_USE_DNS_JAVA_KEY)) {\n // use deprecated property\n useDnsJava = globalProps.getBoolean(AppProperties.USE_DNS_JAVA_KEY, true);\n } else {\n useDnsJava = globalProps.getBoolean(AppProperties.DNS_JAVA_USE_DNS_JAVA_KEY, true);\n }\n if (useDnsJava) {\n String dnsServers = globalProps.getString(AppProperties.DNS_JAVA_DNS_SERVERS_KEY, null);\n if (dnsServers != null) {\n System.getProperties().put(\"dns.server\", dnsServers);\n }\n int timeOut = globalProps.getInt(AppProperties.DNS_JAVA_TIME_OUT_KEY, 4);\n useSimpleResolver = globalProps.getBoolean(AppProperties.DNS_JAVA_USE_SIMPLE_RESOLVER_KEY, true);\n if (useSimpleResolver) {\n try {\n simpleResolver = new SimpleResolver();\n simpleResolver.setTimeout(timeOut);\n } catch (UnknownHostException e) {\n log.error(\"Cannot initialize DNS service (SimpleResolver). Bad DNS server?\", e);\n }\n }\n Lookup.getDefaultResolver().setTimeout(timeOut);\n } \n \n hostNameCache = Collections.synchronizedMap(new LinkedHashMap<Long, String>(HOST_NAME_CACHE_MAX_ENTRIES, .75F, true) {\n private static final long serialVersionUID = 1L;\n\n @Override\n protected boolean removeEldestEntry(Map.Entry<Long, String> eldest) {\n return size() > HOST_NAME_CACHE_MAX_ENTRIES;\n }\n });\n }\n\n \n /**\n * Converts specified IP-range as a string to numeric values.\n * <p>\n * Supported formats:<ul>\n * <li>192.121.218.4\n * <li>192.121.218.0/20\n * <li>192.121.x.x\n * <li>192.121.218.0-255\n * <li>192.121.218.0-192.121.220.255\n * </li>\n * \n * @return IP-range in an array with two elements (start address, end address).\n */\n public static long[] convertIpRange(String ipRange) throws MegatronException {\n // param check\n if (StringUtil.isNullOrEmpty(ipRange) || (ipRange.trim().length() < \"0.0.0.0\".length())) {\n throw new MegatronException(\"IP-range is null or too small: \" + ipRange);\n }\n \n if (ipRange.toLowerCase().contains(\"x\")) {\n ipRange = expandWildCardOctets(ipRange.toLowerCase().trim(), \"x\");\n }\n \n long[] result = null;\n try {\n if (ipRange.contains(\"/\")) {\n // format: 192.121.218.0/20\n result = convertBgpPrefix(ipRange, 32);\n } else if (ipRange.contains(\"-\")) {\n result = new long[2];\n String[] headTail = StringUtil.splitHeadTail(ipRange.trim(), \"-\", false);\n if ((headTail[0].length() == 0) || (headTail[1].length() == 0)) {\n throw new MegatronException(\"Invalid format for IP-range: \" + ipRange);\n }\n if (headTail[1].contains(\".\")) {\n // format: 192.121.218.0-192.121.220.255\n result[0] = convertIpAddress(headTail[0]);\n result[1] = convertIpAddress(headTail[1]);\n } else {\n // format: 192.121.218.0-255\n String[] ipAddressHeadTail = StringUtil.splitHeadTail(headTail[0].trim(), \".\", true);\n if ((ipAddressHeadTail[0].length() == 0) || (ipAddressHeadTail[1].length() == 0)) {\n throw new MegatronException(\"Invalid start IP-address in IP-range: \" + ipRange);\n }\n String endIpAddress = ipAddressHeadTail[0] + \".\" + headTail[1];\n result[0] = convertIpAddress(headTail[0]);\n result[1] = convertIpAddress(endIpAddress);\n }\n } else {\n // format: 192.121.218.4\n result = new long[2];\n result[0] = convertIpAddress(ipRange);\n result[1] = convertIpAddress(ipRange);\n }\n } catch (UnknownHostException e) {\n throw new MegatronException(\"Cannot convert IP-address in IP-range: \" + ipRange, e);\n }\n \n // check range\n if (result[0] > result[1]) {\n throw new MegatronException(\"Start address is greater than end address in IP-range: \" + ipRange);\n }\n \n return result;\n }\n\n \n /**\n * As convertIpRange(String) but with the option to expand trailing \n * zero octets.\n * \n * @param expandZeroOctets expand trailing zero octets? If true, e.g. \n * \"202.131.0.0\" will be expanded to \"202.131.0.0/16\".\n */\n public static long[] convertIpRange(String ipRange, boolean expandZeroOctets) throws MegatronException {\n if (!expandZeroOctets) {\n return convertIpRange(ipRange);\n }\n \n // param check\n if (StringUtil.isNullOrEmpty(ipRange) || (ipRange.trim().length() < \"0.0.0.0\".length())) {\n throw new MegatronException(\"IP-range is null or too small: \" + ipRange);\n }\n\n if (ipRange.contains(\".0\")) {\n ipRange = expandWildCardOctets(ipRange, \"0\");\n } else if (ipRange.contains(\".000\")) {\n ipRange = expandWildCardOctets(ipRange, \"000\");\n }\n \n return convertIpRange(ipRange);\n }\n\n \n /**\n * Converts a BGP-prefix to an IP-range.\n * \n * @param bgpPrefix may include slash or not. Example: \"202.88.48.0/20\" or \"202.131.0.0\".\n * \n * @return IP-range in an array with two elements (start address, end address).\n */\n public static long[] convertBgpPrefix(String bgpPrefix) throws MegatronException {\n return convertBgpPrefix(bgpPrefix, 24);\n }\n \n\n /**\n * Converts specified integer IP-address to an InetAddress-object.\n * \n * @throws UnknownHostException if specified IP-address is invalid.\n */\n public static InetAddress convertIpAddress(long ipAddress) throws UnknownHostException {\n // How to convert ip-number to integer:\n // http://www.aboutmyip.com/AboutMyXApp/IP2Integer.jsp\n \n // ff.ff.ff.ff = 256*16777216 + 256*65536 + 256*256 + 256 = 4311810304\n if ((ipAddress <= 0L) || (ipAddress >= 4311810304L)) {\n throw new UnknownHostException(\"IP-address out of range: \" + ipAddress);\n }\n \n byte[] ip4Address = convertLongAddressToBuf(ipAddress);\n return InetAddress.getByAddress(ip4Address);\n }\n\n \n /**\n * Converts specified integer IP-address in the format XX.XX.XX.XX to an InetAddress-object.\n * \n * @throws UnknownHostException if specified IP-address is invalid.\n */\n public static long convertIpAddress(String ipAddress) throws UnknownHostException {\n if (ipAddress == null) {\n throw new UnknownHostException(\"Invalid IP-address; is null.\");\n }\n \n String[] tokens = ipAddress.trim().split(\"\\\\.\");\n if ((tokens == null) || (tokens.length != 4)) {\n throw new UnknownHostException(\"Invalid IP-address: \" + ipAddress);\n }\n \n long result = 0L;\n long factor = 1;\n for (int i = 3; i >= 0; i--) {\n try {\n int intToken = Integer.parseInt(tokens[i]);\n if ((intToken < 0) || (intToken > 255)) {\n throw new UnknownHostException(\"Invalid IP-address: \" + ipAddress);\n }\n result += intToken*factor;\n factor = factor << 8;\n } catch (NumberFormatException e) {\n throw new UnknownHostException(\"Invalid IP-address: \" + ipAddress);\n }\n }\n \n return result;\n }\n\n\n /**\n * Converts specified integer IP-address to its string representation.\n * \n * @param includeHostName will do a reverse name lookup and append host \n * name to result if lookup successful.\n * \n * @return ip-adress, or empty string if specified address is invalid or\n * in case of an exception. Example: \"130.239.8.25 (wsunet.umdc.umu.se)\". \n */\n public static String convertIpAddress(long ipAddress, boolean includeHostName) {\n if (ipAddress == 0L) {\n return \"\";\n }\n\n String hostAddress = null;\n try {\n hostAddress = convertIpAddressToString(ipAddress);\n } catch (UnknownHostException e) {\n String msg = \"Cannot convert IP-address (address probably invalid): \" + ipAddress;\n log.warn(msg, e);\n hostAddress = \"\";\n }\n \n String hostName = null;\n if (includeHostName) {\n hostName = reverseDnsLookupInternal(ipAddress, true);\n }\n \n StringBuilder result = new StringBuilder(256); \n result.append(hostAddress);\n if (!StringUtil.isNullOrEmpty(hostName)) {\n result.append(\" (\").append(hostName).append(\")\");\n }\n\n return result.toString();\n }\n\n \n /**\n * Converts specified integer IP-address and mask the two last octets.\n * <p>Note: This method is not thread-safe.\n * \n * @return ip-adress, or empty string if specified address is invalid or\n * in case of an exception. Example: \"130.239.x.x\". \n */\n public static String convertAndMaskIpAddress(long ipAddress) {\n String result = convertIpAddress(ipAddress, false);\n if (!StringUtil.isNullOrEmpty(result)) {\n // keep first two numbers in ip-address\n String replaceStr = \"$1.$2.x.x\";\n IP_ADDRESS_MATCHER.reset(result);\n String resultMasked = IP_ADDRESS_MATCHER.replaceFirst(replaceStr);\n if (result.equals(resultMasked)) {\n // may be some error if not masked at all; mask everything\n resultMasked = \"x.x.x.x\";\n }\n // log.debug(\"Masked IP-address: \" + result + \" --> \" + resultMasked);\n result = resultMasked;\n }\n \n return result;\n }\n \n \n /**\n * Returns IP-address as an integer for specified hostname, or 0L\n * if lookup fails.\n */\n public static long dnsLookup(String hostname) {\n long result = 0L;\n String hostAddress = null;\n\n try {\n hostname = hostname.trim();\n InetAddress inetAddress = null;\n if (useDnsJava) {\n inetAddress = Address.getByName(hostname);\n } else {\n inetAddress = InetAddress.getByName(hostname);\n }\n hostAddress = inetAddress.getHostAddress();\n } catch (UnknownHostException e) {\n String msg = \"DNS lookup failed for hostname: \" + hostname;\n log.debug(msg, e);\n }\n \n try {\n if (hostAddress != null) {\n result = convertIpAddress(hostAddress);\n }\n } catch (UnknownHostException e) {\n String msg = \"Connot convert IP-address to an integer: \" + hostAddress;\n log.warn(msg, e);\n }\n\n return result;\n }\n\n \n /**\n * Returns hostname from specified ip-address, or empty string\n * if lookup fails. \n */\n public static String reverseDnsLookup(long ipAddress) {\n return reverseDnsLookupInternal(ipAddress, true);\n }\n\n \n /**\n * As reverseDnsLookup(long), but without cache.\n */\n public static String reverseDnsLookupWithoutCache(long ipAddress) {\n return reverseDnsLookupInternal(ipAddress, false);\n }\n\n \n private static String reverseDnsLookupInternal(long ipAddress, boolean useCache) {\n String result = null;\n \n // -- Cache lookup\n Long cacheKey = null;\n if (useCache) {\n cacheKey = new Long(ipAddress);\n result = hostNameCache.get(cacheKey);\n if (result != null) {\n // log.debug(\"Cache hit: \" + ipAddress + \":\" + result);\n return result;\n }\n }\n \n // -- Reverse DNS lookup \n try {\n if (useDnsJava) {\n if (useSimpleResolver) {\n result = reverseDnsLookupUsingDnsJavaSimpleResolver(ipAddress);\n } else {\n result = reverseDnsLookupUsingDnsJavaExtendedResolver(ipAddress);\n }\n } else {\n result = reverseDnsLookupUsingJdk(ipAddress);\n }\n // -- Validate hostname\n validateHostname(result);\n } catch(IOException e) {\n // UnknownHostException, IOException\n result = \"\";\n if (log.isDebugEnabled()) {\n String ipAddressStr = null;\n try {\n ipAddressStr = convertIpAddressToString(ipAddress);\n } catch (UnknownHostException e2) {\n ipAddressStr = Long.toString(ipAddress);\n }\n String msg = \"Reverse DNS lookup failed for IP-address: \" + ipAddressStr;\n log.debug(msg, e);\n }\n }\n \n // -- Add to cache (even empty entries)\n if (useCache) {\n if (log.isDebugEnabled()) {\n String ipAddressStr = null;\n try {\n ipAddressStr = convertIpAddressToString(ipAddress);\n } catch (UnknownHostException e2) {\n ipAddressStr = Long.toString(ipAddress);\n }\n log.debug(\"Adds hostname to cache: \" + ipAddress + \" [\" + ipAddressStr + \"]:\" + result);\n }\n hostNameCache.put(cacheKey, result);\n }\n \n return result;\n }\n\n \n private static String reverseDnsLookupUsingJdk(long ipAddress) throws UnknownHostException {\n // -- Convert ip-address (long) to string\n InetAddress inetAddress = convertIpAddress(ipAddress);\n String hostAddress = inetAddress.getHostAddress();\n if (StringUtil.isNullOrEmpty(hostAddress)) {\n throw new UnknownHostException(\"Cannot convert IP-address: \" + ipAddress);\n }\n\n // -- Reverse DNS lookup \n log.debug(\"Making a reverse DNS lookup for \" + ipAddress);\n String result = inetAddress.getHostName();\n log.debug(\"Lookup result: \" + result);\n if (StringUtil.isNullOrEmpty(result) || result.equals(hostAddress)) {\n throw new UnknownHostException(\"Reverse DNS lookup failed: \" + hostAddress);\n }\n return result;\n }\n\n \n private static String reverseDnsLookupUsingDnsJavaExtendedResolver(long ipAddress) throws UnknownHostException {\n byte[] address = convertLongAddressToBuf(ipAddress);\n Name name = ReverseMap.fromAddress(InetAddress.getByAddress(address));\n Record[] records = new Lookup(name, Type.PTR).run();\n if (records == null) {\n throw new UnknownHostException();\n }\n String result = ((PTRRecord)records[0]).getTarget().toString();\n // remove trailing \".\"\n result = result.endsWith(\".\") ? result.substring(0, result.length() - 1) : result;\n return result;\n }\n\n \n private static String reverseDnsLookupUsingDnsJavaSimpleResolver(long ipAddress) throws IOException {\n String result = null;\n byte[] address = convertLongAddressToBuf(ipAddress);\n Name name = ReverseMap.fromAddress(InetAddress.getByAddress(address));\n Record record = Record.newRecord(name, Type.PTR, DClass.IN);\n Message query = Message.newQuery(record);\n Message response = simpleResolver.send(query);\n Record[] answers = response.getSectionArray(Section.ANSWER);\n if (answers.length != 0) {\n // If PTR-record exists this will be at index 1 or above (more than one PTR-record may exist)\n Record answer = (answers.length > 1) ? answers[1] : answers[0]; \n result = answer.rdataToString();\n // remove trailing \".\"\n result = result.endsWith(\".\") ? result.substring(0, result.length() - 1) : result;\n } else {\n throw new IOException(\"Empty DNS response.\");\n }\n return result;\n }\n \n \n private static String convertIpAddressToString(long ipAddress) throws UnknownHostException {\n InetAddress inetAddress = convertIpAddress(ipAddress);\n String result = inetAddress.getHostAddress();\n if (StringUtil.isNullOrEmpty(result)) {\n throw new UnknownHostException(\"Cannot convert IP-address: \" + ipAddress);\n }\n return result;\n }\n \n \n private static byte[] convertLongAddressToBuf(long ipAddress) {\n byte[] result = new byte[4];\n result[0] = (byte)((ipAddress >> 24) & 0xFF);\n result[1] = (byte)((ipAddress >> 16) & 0xFF);\n result[2] = (byte)((ipAddress >> 8) & 0xFF);\n result[3] = (byte)((ipAddress >> 0) & 0xFF);\n return result;\n }\n\n \n /**\n * Validates specified hostname.\n * \n * @throws UnknownHostException if hostname contain malicious or invalid content.\n */\n private static void validateHostname(String hostName) throws UnknownHostException {\n // More info: http://en.wikipedia.org/wiki/Hostname\n \n // Valid letters: a..z, A..Z, 0..9, -\n for (int i = 0; i < hostName.length(); i++) {\n char ch = hostName.charAt(i);\n if (!((('a' <= ch) && (ch <= 'z')) || (('A' <= ch) && (ch <= 'Z')) || (('0' <= ch) && (ch <= '9')) || (((ch == '-') || (ch == '.')) && (i > 0)))) {\n throw new UnknownHostException(\"Host name contains illegal character: \" + ch + \". Host name: \" + hostName);\n }\n }\n // Validate total length\n if (hostName.length() > 255) {\n throw new UnknownHostException(\"Host name too long: \" + hostName);\n }\n // Exists empty labels?\n if (hostName.indexOf(\"..\") != -1) {\n throw new UnknownHostException(\"Host name contains an empty label: \" + hostName);\n }\n // Validate label length\n String[] labels = hostName.split(\"\\\\.\");\n for (int i = 0; i < labels.length; i++) {\n if (StringUtil.isNullOrEmpty(labels[i])) {\n throw new UnknownHostException(\"Host name contains an empty label: \" + hostName);\n }\n if (labels[i].length() > 63) {\n throw new UnknownHostException(\"Host name contains an label that is too long: \" + hostName);\n }\n }\n }\n\n \n /**\n * Expands trailing octets that contains specified wildcard. \n * A BGP prefix is returned.\n * <p>\n * Example: (\"202.131.x.x\", \"x\") returns \"202.131.0.0/16\", \n * (\"202.131.101.0\", \"0\") returns \"202.131.101.0/24\".\n */\n private static String expandWildCardOctets(String ipRange, String wildCard) throws MegatronException {\n String result = ipRange;\n int mask = 32;\n boolean wildcardFound = true;\n while (wildcardFound) {\n int lengthBefore = result.length();\n result = StringUtil.removeSuffix(result, \".\" + wildCard);\n wildcardFound = result.length() < lengthBefore;\n if (wildcardFound) {\n mask -= 8;\n }\n }\n if (mask == 32) {\n result = ipRange;\n } else if ((mask < 8) || result.equals(wildCard)) {\n throw new MegatronException(\"Cannot expand wildcard IP-range: \" + ipRange);\n } else {\n String suffix = StringUtil.nCopyString(\".0\", (32 - mask) / 8);\n result = result + suffix + \"/\" + mask;\n }\n \n return result;\n }\n\n \n private static long[] convertBgpPrefix(String bgpPrefix, int maxMask) throws MegatronException {\n // param check\n if (StringUtil.isNullOrEmpty(bgpPrefix) || (bgpPrefix.trim().length() < \"0.0.0.0\".length())) {\n throw new MegatronException(\"BGP-prefix is null or too small: \" + bgpPrefix);\n }\n \n long[] result = new long[2];\n bgpPrefix = bgpPrefix.trim(); \n bgpPrefix = bgpPrefix.endsWith(\"/\") ? bgpPrefix.substring(0, bgpPrefix.length()-1) : bgpPrefix;\n int slashIndex = bgpPrefix.indexOf(\"/\");\n if (slashIndex != -1) {\n // Format: 202.88.48.0/20 (endAddress: 202.88.63.255)\n // 202 . 88 . 48 . 0\n // =\n // 11001010 . 01011000 . 00110000 . 00000000\n // and\n // 11111111 . 11111111 . 11110000 . 00000000 mask with 20 1's; bitMaskHead\n // =\n // 11001010 . 01011000 . 0011\n // or\n // 1111 . 11111111 bitMaskTail\n //\n // 11001010 . 01011000 . 00111111 . 11111111 (= 202.88.63.255)\n \n String startAddressStr = bgpPrefix.substring(0, slashIndex);\n try {\n result[0] = convertIpAddress(startAddressStr);\n } catch (UnknownHostException e) {\n throw new MegatronException(\"Cannot convert IP-address in BGP-prefix: \" + bgpPrefix, e);\n }\n String maskStr = bgpPrefix.substring(slashIndex+1);\n int mask = 0;\n try {\n mask = Integer.parseInt(maskStr);\n } catch (NumberFormatException e) {\n throw new MegatronException(\"Cannot parse mask in BGP-prefix: \" + maskStr + \" (\" + bgpPrefix + \").\", e);\n }\n if ((mask <= 1) || (mask > maxMask)) {\n throw new MegatronException(\"Invalid BGP-prefix mask: \" + mask + \" (\" + bgpPrefix + \").\");\n }\n long bitMaskHead = ((1L << mask) - 1) << (32 - mask);\n long bitMaskTail = (1L << (32 - mask)) - 1;\n result[1] = (result[0] & bitMaskHead) | bitMaskTail; \n } else {\n // Format: 202.131.0.0 (endAddress: 202.131.255.255)\n try {\n result[0] = convertIpAddress(bgpPrefix);\n } catch (UnknownHostException e) {\n throw new MegatronException(\"Cannot convert IP-address in BGP-prefix: \" + bgpPrefix, e);\n }\n // add \"#\" as suffix temporary, e.g. \"202.131.0.0#\"\n String endAddressStr = bgpPrefix + \"#\";\n endAddressStr = StringUtil.replace(endAddressStr, \".0.0.0#\", \".255.255.255#\");\n endAddressStr = StringUtil.replace(endAddressStr, \".0.0#\", \".255.255#\");\n endAddressStr = StringUtil.replace(endAddressStr, \".0#\", \".255#\");\n endAddressStr = endAddressStr.substring(0, endAddressStr.length()-1);\n try {\n result[1] = convertIpAddress(endAddressStr);\n } catch (UnknownHostException e) {\n throw new MegatronException(\"Cannot convert end IP-address in BGP-prefix: \" + bgpPrefix, e);\n }\n }\n return result;\n }\n\n}", "public abstract class StringUtil {\n\n\n /**\n * Replaces a substring in a string with another string. Replaces all\n * occurrences.\n * <p>\n * Example: replace(\"name=@name@\", \"@name@\", \"hubba\") --> \"name=hubba\".\n *\n * @throws NullPointerException if the from- or to-argument is null.\n */\n public static String replace(String str, String from, String to) {\n return replaceInternal(str, from, to, false);\n }\n\n \n /**\n * As replace, but replace one the first occurrence. \n */\n public static String replaceFirst(String str, String from, String to) {\n return replaceInternal(str, from, to, true);\n }\n\n\n /**\n * Removes prefix from specified string.<p>\n * Example: removePrefix(\"foobar.config\", \"foobar.\") --> \"config\"\n */\n public static String removePrefix(String str, String prefix) {\n if ((str == null) || (prefix == null)) {\n return str;\n }\n\n String result = null;\n int hitIndex = str.indexOf(prefix);\n if (hitIndex == 0) {\n if (prefix.length() < str.length()) {\n result = str.substring(prefix.length());\n } else {\n result = \"\";\n }\n } else {\n result = str;\n }\n\n return result;\n }\n\n\n /**\n * Removes suffix from specified string.<p>\n * Example: removeSuffix(\"foobar.config\", \".config\") --> \"foobar\"\n */\n public static String removeSuffix(String str, String suffix) {\n if ((str == null) || (suffix == null)) {\n return str;\n }\n\n String result = str;\n int hitIndex = str.lastIndexOf(suffix);\n if ((hitIndex != -1) && ((hitIndex + suffix.length()) == str.length())) {\n result = result.substring(0, hitIndex);\n }\n return result;\n }\n\n\n /**\n * Splits specified string in two parts at delimiter position.\n *\n * @param str string to split.\n * @param delim delimiter that marks split between head and tail.\n * @param reverse is search for delimiter reverse (search starts at end of string)?\n * @return null if one argument is null, otherwise a String-array of length\n * two in following format: { head, tail }. If delimiter is not\n * found, then tail is empty if isReverse is false or\n * head is empty if isReverse is true. Delimiter is not\n * included.\n */\n public static String[] splitHeadTail(String str, String delim, boolean reverse) {\n // check param\n if ((str == null) || (delim == null)) {\n return null;\n }\n\n String[] result = new String[2];\n int hitPos = reverse ? str.lastIndexOf(delim) : str.indexOf(delim);\n if (hitPos != -1) {\n result[0] = str.substring(0, hitPos);\n int tailPos = hitPos + delim.length();\n if (tailPos < str.length()) {\n result[1] = str.substring(tailPos);\n } else {\n result[1] = \"\";\n }\n } else {\n if (reverse) {\n result[0] = \"\";\n result[1] = str;\n } else {\n result[0] = str;\n result[1] = \"\";\n }\n }\n\n return result;\n }\n\n\n /**\n * Returns true if specified string is null or empty.\n */\n public static boolean isNullOrEmpty(String str) {\n return str == null || str.length() == 0;\n }\n\n\n /**\n * Returns specified string if not null, otherwise an empty string.\n */\n public static String getNotNull(String str) {\n return (str != null) ? str : \"\";\n }\n\n\n /**\n * Returns specified string if not null, otherwise specified default value.\n */\n public static String getNotNull(String str, String defaultStr) {\n return (str != null) ? str : defaultStr;\n }\n\n\n /**\n * Converts specifed byte-array to hex-string.\n */\n public static String encode(byte[] buf) {\n StringBuffer result = new StringBuffer(2 * buf.length);\n\n for (int i = 0; i < buf.length; i++) {\n int byteAsInt = buf[i] & 0xFF;\n if (byteAsInt < 16) {\n result.append(\"0\");\n }\n result.append(Integer.toString(byteAsInt, 16).toLowerCase());\n }\n\n return result.toString();\n }\n\n\n /**\n * Converts specified hex-string to byte-array.\n */\n public static byte[] decodeHexString(String hexStr) throws NumberFormatException {\n if (hexStr == null) {\n return null;\n }\n // is every digit of size two?\n if ((hexStr.length() % 2) != 0) {\n throw new NumberFormatException(\"Bad hex-string. Length of string must be even.\");\n }\n\n byte[] result = new byte[hexStr.length() / 2];\n for (int i = 0; i < hexStr.length(); i += 2) {\n String hexDigit = hexStr.substring(i, i + 2);\n int byteValue = Integer.parseInt(hexDigit, 16);\n result[i / 2] = (byte)(byteValue & 0xFF);\n }\n\n return result;\n }\n\n\n /**\n * Encodes specifed text using named entities, e.g \"<\" converts\n * to \"&amp;lt;\".\n * <p>\n * The result is safe to include in XML or HTML.\n */\n public static String encodeCharacterEntities(String str) {\n if (str == null) {\n return null;\n }\n\n StringBuilder result = new StringBuilder(str.length() + 50);\n for (int i = 0; i < str.length(); i++) {\n char chr = str.charAt(i);\n switch (chr) {\n case '<':\n result.append(\"&lt;\");\n break;\n case '>':\n result.append(\"&gt;\");\n break;\n case '&':\n result.append(\"&amp;\");\n break;\n case '\"':\n result.append(\"&quot;\");\n break;\n default:\n result.append(chr);\n }\n }\n return result.toString();\n }\n\n \n /**\n * Removes line beaks from specified string.\n */\n public static String removeLineBreaks(String str, String replaceWith) {\n String result = str;\n result = replace(result, \"\\n\", replaceWith);\n result = replace(result, \"\\r\", replaceWith);\n return result;\n }\n\n\n /**\n * Removes trailing white spaces (including line breaks) from \n * specified string.\n */\n public static String removeTrailingSpaces(String str) {\n if ((str == null) || (str.length() == 0)) {\n return str;\n }\n\n int endIndex = 0;\n for (int i = (str.length()-1); i >= 0; i--) {\n if (!Character.isWhitespace(str.charAt(i))) {\n endIndex = i + 1;\n break;\n }\n }\n \n return str.substring(0, endIndex);\n }\n \n \n /**\n * Removes enclosing characters from string.\n * Example: str=\"'foobar'\", enclosingChars=\"'\" will return \"foobar\". \n */\n public static String removeEnclosingChars(String str, String enclosingChars) {\n if ((str == null) || !(str.startsWith(enclosingChars) && str.endsWith(enclosingChars))) {\n return str;\n }\n\n return removeSuffix(removePrefix(str, enclosingChars), enclosingChars); \n }\n\n \n /**\n * Truncates specified string if longer than max length. \"...\" is added\n * as suffix to mark that the string have been truncated.\n */\n public static String truncateString(String str, int maxLength) {\n if ((str == null) || (str.length() <= maxLength)) {\n return str;\n }\n final String suffix = \"...\";\n if (maxLength < suffix.length()) {\n return suffix;\n }\n \n StringBuilder result = new StringBuilder(maxLength);\n int endIndex = maxLength - suffix.length();\n result.append(str.substring(0, endIndex)).append(suffix);\n\n return result.toString();\n }\n\n \n /**\n * Returns a string containing strToCopy duplicated\n * noOfCopies times.\n */\n public static String nCopyString(String strToCopy, int noOfCopies) {\n // check param\n if (strToCopy == null) {\n return null;\n }\n\n StringBuilder result = new StringBuilder(noOfCopies * strToCopy.length());\n for (int i = 0; i < noOfCopies; i++) {\n result.append(strToCopy);\n }\n\n return result.toString();\n }\n\n \n /**\n * Pads specified string in head with spaces.\n */\n public static String leftPad(String str, int len) {\n return pad(str, len, \" \", true);\n }\n\n\n /**\n * Pads specified string in tail with spaces.\n */\n public static String rightPad(String str, int len) {\n return pad(str, len, \" \", false);\n }\n\n\n /**\n * Pads specified string in head with pad-string.\n */\n public static String leftPad(String str, int len, String padString) {\n return pad(str, len, padString, true);\n }\n\n\n /**\n * Pads specified string in tail with pad-string.\n */\n public static String rightPad(String str, int len, String padString) {\n return pad(str, len, padString, false);\n }\n\n \n /**\n * Returns specified files as a string list. Returns never null.\n */\n public static String toString(List<File> files, boolean shortName) {\n if (files == null) {\n return \"[null]\";\n }\n\n StringBuilder result = new StringBuilder(256);\n for (Iterator<File> iterator = files.iterator(); iterator.hasNext(); ) {\n File file = iterator.next();\n if (result.length() > 0) {\n result.append(\", \");\n }\n\n String filename = shortName ? file.getName() : file.getAbsolutePath();\n result.append(filename);\n }\n\n return result.toString();\n }\n\n \n /**\n * Returns specified list as a string where every element is quoted and\n * comma separated.\n */\n public static String toQuotedString(List<?> list) {\n return toQuotedString(list, \"\\\"\");\n }\n\n \n /**\n * As toQuotedString, but use a single quote instead of a double quote.\n */\n public static String toSingleQuotedString(List<?> list) {\n return toQuotedString(list, \"\\'\");\n }\n\n \n /**\n * Returns specified list as a string where every element is quoted with\n * specified character and comma separated.\n */\n private static String toQuotedString(List<?> list, String quoteChar) {\n if ((list == null) || (list.size() == 0)) {\n return \"\";\n }\n \n StringBuffer result = new StringBuffer(256);\n for (Iterator<?> iterator = list.iterator(); iterator.hasNext(); ) {\n Object obj = iterator.next();\n String str = (obj != null) ? obj.toString() : \"\";\n if (result.length() > 0) {\n result.append(\",\");\n }\n result.append(quoteChar).append(str).append(quoteChar);\n }\n\n return result.toString();\n }\n\n \n /**\n * Pads specified string with pad-string.\n */\n private static String pad(String str, int len, String padString, boolean leftPad) {\n if ((str == null) || (str.length() >= len) || (padString == null)) {\n return str;\n }\n\n int n = (len - str.length()) / padString.length();\n String paddedString = nCopyString(padString, n);\n StringBuilder result = new StringBuilder(len);\n if (leftPad) {\n result.append(paddedString).append(str);\n } else {\n result.append(str).append(paddedString);\n }\n\n return result.toString();\n }\n \n \n @SuppressWarnings(\"null\")\n private static String replaceInternal(String str, String from, String to, boolean replaceFirst) {\n if (str == null) {\n return null;\n }\n if ((from == null) || (to == null)) {\n throw new NullPointerException(\"from- or to-argument is null.\");\n }\n\n StringBuilder result = null;\n int fromlength = 0;\n int index = 0;\n boolean quit = false;\n while (!quit) {\n int hitIndex = str.indexOf(from, index);\n if (hitIndex < 0) {\n break;\n }\n if (result == null) {\n result = new StringBuilder(str.length() + 40);\n fromlength = from.length();\n }\n result.append(str.substring(index, hitIndex));\n result.append(to);\n index = hitIndex + fromlength;\n quit = replaceFirst;\n }\n if (index == 0) {\n return str;\n }\n result.append(str.substring(index));\n return result.toString();\n }\n\n\n}" ]
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.UnknownHostException; import java.text.DecimalFormat; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.log4j.Logger; import se.sitic.megatron.core.AppProperties; import se.sitic.megatron.core.JobContext; import se.sitic.megatron.core.MegatronException; import se.sitic.megatron.core.TypedProperties; import se.sitic.megatron.util.Constants; import se.sitic.megatron.util.DateUtil; import se.sitic.megatron.util.IpAddressUtil; import se.sitic.megatron.util.StringUtil;
package se.sitic.megatron.fileprocessor; /** * Extracts hostnames or IP addresses from the input file, and makes DNS lookups * respective reverse DNS lookups in multiple threads to improve performance. * <p> * The result is saved in a map, which is used by IpAddressDecorator and * HostnameDecorator. * <p> * TODO: Add support to write the result (IP address or hostname) in the file * instead of storing the result in memory. */ public class MultithreadedDnsProcessor implements IFileProcessor { /** Key for dnsMap in JobContext.additionalData */ public static final String DNS_MAP_KEY = "MultithreadedDnsProcessor.dnsMap"; /** Key for reverseDnsMap in JobContext.additionalData */ public static final String REVERSE_DNS_MAP_KEY = "MultithreadedDnsProcessor.reverseDnsMap"; // protected due to acess from innner class protected static final Logger log = Logger.getLogger(MultithreadedDnsProcessor.class); private static final String END_ITEM_MARKER = "---- End of Queue ----"; // protected due to acess from innner class protected CountDownLatch allThreadsFinishedLatch; protected BlockingQueue<String> queue; protected Map<String, Long> dnsMap; protected Map<Long, String> reverseDnsMap; private JobContext jobContext; private TypedProperties props; private int noOfThreads; private Matcher matcher; private Set<String> processedItems; private long printProgressInterval; private long lastProgressPrintTime; private long lastProgressPrintLineNo; private long noOfProcessedItems; private long noOfUniqueProcessedItems; public MultithreadedDnsProcessor() { // empty } @Override public void init(JobContext jobContext) throws MegatronException { this.jobContext = jobContext; props = jobContext.getProps(); // -- Setup result maps, queue, matcher etc. int initialCapacity = (int)jobContext.getNoOfLines(); if (initialCapacity < 16) { initialCapacity = 32; } processedItems = new HashSet<String>(initialCapacity); queue = new ArrayBlockingQueue<String>(256); boolean reverseDnsLookup = props.getBoolean(AppProperties.FILE_PROCESSOR_DNS_REVERSE_DNS_LOOKUP_KEY, true); String regExp = null; if (reverseDnsLookup) { reverseDnsMap = Collections.synchronizedMap(new HashMap<Long, String>(initialCapacity)); jobContext.addAdditionalData(REVERSE_DNS_MAP_KEY, reverseDnsMap); regExp = props.getString(AppProperties.FILE_PROCESSOR_DNS_REG_EXP_IP_KEY, null); if (StringUtil.isNullOrEmpty(regExp)) { throw new MegatronException("Regular expression not defined: " + AppProperties.FILE_PROCESSOR_DNS_REG_EXP_IP_KEY); } } else { dnsMap = Collections.synchronizedMap(new HashMap<String, Long>(initialCapacity)); jobContext.addAdditionalData(DNS_MAP_KEY, dnsMap); regExp = props.getString(AppProperties.FILE_PROCESSOR_DNS_REG_EXP_HOSTNAME_KEY, null); if (StringUtil.isNullOrEmpty(regExp)) { throw new MegatronException("Regular expression not defined: " + AppProperties.FILE_PROCESSOR_DNS_REG_EXP_HOSTNAME_KEY); } } try { matcher = Pattern.compile(regExp).matcher(""); } catch (PatternSyntaxException e) { String msg = "Cannot compile reg-exp: " + regExp; throw new MegatronException(msg, e); } // init attributes for printProgress lastProgressPrintTime = System.currentTimeMillis(); lastProgressPrintLineNo = 0L; printProgressInterval = 1000L*props.getLong(AppProperties.PRINT_PROGRESS_INTERVAL_KEY, 15L); // -- Setup threads noOfThreads = props.getInt(AppProperties.FILE_PROCESSOR_DNS_NO_OF_THREADS_KEY, 100); if (jobContext.getNoOfLines() < 10L) { noOfThreads = 4; } allThreadsFinishedLatch = new CountDownLatch(noOfThreads); for (int i = 0; i < noOfThreads; i++) { Thread thread = null; if (reverseDnsLookup) { thread = new Thread(new ReverseDnsLookupConsumer()); } else { thread = new Thread(new DnsLookupConsumer()); } String name = "Consumer-" + i; thread.setName(name); log.debug("Starting DNS lookup consumer thread: " + name); thread.start(); } } @Override public File execute(File inputFile) throws MegatronException { long t1 = System.currentTimeMillis(); // -- Read file BufferedReader in = null; try { String charSet = props.getString(AppProperties.INPUT_CHAR_SET_KEY, Constants.UTF8); in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), charSet)); long lineNo = 0L; String line = null; while ((line = in.readLine()) != null) { matcher.reset(line); while (matcher.find()) { if (matcher.groupCount() > 0) { for (int i = 1; i <= matcher.groupCount(); i++) { processItem(matcher.group(i)); } } else { processItem(matcher.group()); } } ++lineNo; printProgress(lineNo - queue.size()); } if ((noOfProcessedItems == 0L) && (lineNo > 10L)) { throw new MegatronException("No IP addresses or hostnames extracted. Please check regular expression: " + AppProperties.FILE_PROCESSOR_DNS_REG_EXP_IP_KEY + " or " + AppProperties.FILE_PROCESSOR_DNS_REG_EXP_HOSTNAME_KEY); } } catch (IOException e) { String msg = "Cannot read file: " + inputFile.getAbsolutePath(); throw new MegatronException(msg, e); } finally { try { if (in != null) in.close(); } catch (Exception ignored) {} } // -- Add "end of queue" items for (int i = 0; i < noOfThreads; i++) { try { queue.put(END_ITEM_MARKER); } catch (InterruptedException e) { throw new MegatronException("Cannot put 'end of queue' marker in queue (should not happen)", e); } } // -- Wait for threads to finish log.debug("All items added to queue; waiting for threads to finish."); try { allThreadsFinishedLatch.await(); } catch (InterruptedException e) { throw new MegatronException("Wait for all threads to finish interrupted (should not happen)", e); } String durationStr = DateUtil.formatDuration(System.currentTimeMillis() - t1); log.info("Total time for DNS lookups: " + durationStr); return inputFile; } @Override public void close(boolean jobSuccessful) throws MegatronException { if (dnsMap != null) { log.info("No. of parsed hostnames for DNS lookup [total / total unique]: " + noOfProcessedItems + " / " + noOfUniqueProcessedItems); log.info("No. of DNS lookups (hostname --> ip) [successful / failed]: " + dnsMap.size() + " / " + (noOfUniqueProcessedItems - dnsMap.size())); } else { log.info("No. of parsed IP addresses for reverse DNS lookup [total / total unique]: " + noOfProcessedItems + " / " + noOfUniqueProcessedItems); log.info("No. of DNS lookups (ip --> hostname) [successful / failed]: " + reverseDnsMap.size() + " / " + (noOfUniqueProcessedItems - reverseDnsMap.size())); } } /** * Process specified IP address or hostname. */ private void processItem(String itemStr) throws MegatronException { if (StringUtil.isNullOrEmpty(itemStr)) { return; } ++noOfProcessedItems; if (processedItems.contains(itemStr)) { return; } ++noOfUniqueProcessedItems; processedItems.add(itemStr); try { queue.put(itemStr); } catch (InterruptedException e) { throw new MegatronException("Cannot put DNS item in queue (should not happen)", e); } } private void printProgress(long lineNo) { long now = System.currentTimeMillis(); if ((printProgressInterval > 0L) && ((lastProgressPrintTime + printProgressInterval) < now)) { long noOfLines = jobContext.getNoOfLines(); double progress = 100d*((double)lineNo / (double)noOfLines); double linesPerSecond = ((double)lineNo - (double)lastProgressPrintLineNo) / (((double)now - (double)lastProgressPrintTime) / 1000d); DecimalFormat format = new DecimalFormat("0.00"); String progressStr = format.format(progress); String lineInfoStr = lineNo + " of " + noOfLines + " lines"; String linesPerSecondStr = format.format(linesPerSecond); String msg = "DNS Prefetch: " + progressStr + "% (" + lineInfoStr + ", " + linesPerSecondStr + " lines/second)"; if (props.isStdout()) { log.info(msg); } else { jobContext.writeToConsole(msg); } lastProgressPrintLineNo = lineNo; lastProgressPrintTime = now; } } /** * Takes an item (hostname or IP address) from queue and process it * (DNS lookup or reverse DNS lookup). */ private abstract class AbstractConsumer implements Runnable { public AbstractConsumer() { // empty } @Override public void run() { try { while (true) { String itemStr = queue.take(); if (itemStr == END_ITEM_MARKER) { break; } processItem(itemStr); } } catch (InterruptedException e) { log.error("DNS lookup or reverse DNS lookup failed; thread interrupted (should not happened).", e); } allThreadsFinishedLatch.countDown(); log.debug("Thread is exiting: " + Thread.currentThread().getName()); } protected abstract void processItem(String itemStr); } /** * Makes a DNS lookup. */ private class DnsLookupConsumer extends AbstractConsumer { public DnsLookupConsumer() { // empty } @Override protected void processItem(String itemStr) {
long ipAddress = IpAddressUtil.dnsLookup(itemStr);
4
HackGSU/mobile-android
app/src/main/java/com/hackgsu/fall2016/android/views/AnnouncementsRecyclerView.java
[ "public class DataStore {\n\tprivate static ArrayList<AboutPerson> aboutPeople;\n\tprivate static ArrayList<Announcement> announcements = new ArrayList<>();\n\tprivate static String openingCeremoniesRoomNumber;\n\tprivate static ArrayList<ScheduleEvent> scheduleEvents = new ArrayList<>();\n\n\tstatic {\n\t\taboutPeople = new ArrayList<>();\n\n\t\taboutPeople.add(new AboutPerson(\"Alex Mitchell\", \"iOS Developer\", \"https://goo.gl/cHty7J\", R.drawable.alex_pic));\n\t\taboutPeople.add(new AboutPerson(\"Viraj Shah\", \"iOS Developer\", \"https://goo.gl/v5YZaL\", R.drawable.viraj_pic));\n\t\taboutPeople.add(new AboutPerson(\"Harsha Goli\", \"iOS Developer\", \"https://goo.gl/UCVv11\", R.drawable.harsha_pic));\n\t\taboutPeople.add(new AboutPerson(\"Dylan Welch\", \"iOS Developer\", \"https://goo.gl/8RDDyo\", R.drawable.dylan_pic));\n\t\taboutPeople.add(new AboutPerson(\"Josh King\", \"Android Developer\", \"https://goo.gl/Izv7vk\", R.drawable.josh_pic));\n\t\taboutPeople.add(new AboutPerson(\"Pranathi Venigandla\", \"Android Developer\", \"https://goo.gl/S8KP2A\", R.drawable.pranathi_pic));\n\t\taboutPeople.add(new AboutPerson(\"Solomon Arnett\", \"Web Developer\", \"https://goo.gl/QbIimx\", R.drawable.solo_pic));\n\t\taboutPeople.add(new AboutPerson(\"Sri Rajasekaran\", \"Web Developer\", \"https://goo.gl/7GZoGB\", R.drawable.sri_pic));\n\t\taboutPeople.add(new AboutPerson(\"Abhinav Reddy\", \"Web Developer\", \"https://goo.gl/PSCYbR\", R.drawable.abhinav_pic));\n\t}\n\n\tpublic static ArrayList<AboutPerson> getAboutPeople () {\n\t\treturn aboutPeople;\n\t}\n\n\tpublic static ArrayList<Announcement> getAnnouncements (boolean onlyReturnBookmarkedAnnouncements) {\n\t\tif (!onlyReturnBookmarkedAnnouncements) { return getAnnouncements(); }\n\n\t\tArrayList<Announcement> filteredAnnouncements = new ArrayList<>();\n\t\tfor (Announcement announcement : getAnnouncements()) { if (announcement.isBookmarkedByMe()) { filteredAnnouncements.add(announcement); } }\n\t\tCollections.sort(filteredAnnouncements);\n\t\treturn filteredAnnouncements;\n\t}\n\n\tpublic static ArrayList<Announcement> getAnnouncements () {\n\t\treturn announcements;\n\t}\n\n\tpublic static String getOpeningCeremoniesRoomNumber () {\n\t\treturn openingCeremoniesRoomNumber;\n\t}\n\n\tpublic static ArrayList<ScheduleEvent> getScheduleEvents () {\n\t\treturn scheduleEvents;\n\t}\n\n\tpublic static void setAnnouncements (Context context, ArrayList<Announcement> announcements) {\n\t\tCollections.sort(announcements);\n\t\tAnnouncementController.setIsBookmarkedByMeBasedOnPrefs(context, announcements);\n\t\tAnnouncementController.setIsLikedByMeBasedOnPrefs(context, announcements);\n\t\tDataStore.announcements = announcements;\n\t}\n\n\tpublic static void setOpeningCeremoniesRoomNumber (String openingCeremoniesRoomNumber) {\n\t\tDataStore.openingCeremoniesRoomNumber = openingCeremoniesRoomNumber;\n\t}\n\n\tpublic static void setScheduleEvents (ArrayList<ScheduleEvent> scheduleEvents) {\n\t\tDataStore.scheduleEvents = scheduleEvents;\n\t}\n}", "public class HackGSUApplication extends Application {\n\tpublic static final String IS_IN_DEV_MODE = \"is_in_dev_mode\";\n\tpublic static final String NOTIFICATIONS_ENABLED = \"notifications_enabled\";\n\tprivate FirebaseAuth firebaseAuth;\n\tprivate FirebaseAuth.AuthStateListener firebaseAuthListener;\n\n\tpublic static boolean areNotificationsEnabled (Context context) {\n\t\treturn getPrefs(context).getBoolean(NOTIFICATIONS_ENABLED, true);\n\t}\n\n\t@NonNull\n\tprivate static Announcement convertDataSnapshotToAnnouncement (DataSnapshot child) {\n\t\tAnnouncement announcement = child.getValue(Announcement.class);\n\t\tannouncement.setFirebaseKey(child.getKey());\n\t\treturn announcement;\n\t}\n\n\tpublic static float convertDpToPx (float dp, Context context) {\n\t\treturn dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);\n\t}\n\n\tpublic static void delayRunnableOnUI (final long millsToDelay, final Runnable runnableToRun) {\n\t\tnew Thread(new Runnable() {\n\t\t\tpublic void run () {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(millsToDelay);\n\t\t\t\t} catch (InterruptedException ignored) {}\n\n\t\t\t\t(new Handler(Looper.getMainLooper())).post(runnableToRun);\n\t\t\t}\n\t\t}).start();\n\t}\n\n\tpublic static LocalDateTime getDateTimeOfHackathon (int dayIndex, int hour, int minute) {\n\t\treturn getDateTimeOfHackathon().plusDays(dayIndex).withHourOfDay(hour).withMinuteOfHour(minute);\n\t}\n\n\t@NonNull\n\tpublic static LocalDateTime getDateTimeOfHackathon () {\n\t\treturn new LocalDateTime().withDate(2017, 3, 31).withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(30).withHourOfDay(19);\n\t}\n\n\tpublic static SharedPreferences getPrefs (Context context) {\n\t\treturn PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());\n\t}\n\n\tpublic static DateTimeFormatter getTimeFormatter24OrNot (Context context) {\n\t\treturn getTimeFormatter24OrNot(context, new DateTimeFormatterBuilder());\n\t}\n\n\tpublic static DateTimeFormatter getTimeFormatter24OrNot (Context context, DateTimeFormatterBuilder dateTimeFormatterBuilder) {\n\t\tif (DateFormat.is24HourFormat(context)) {\n\t\t\tdateTimeFormatterBuilder.appendHourOfDay(2).appendLiteral(\":\").appendMinuteOfHour(2);\n\t\t}\n\t\telse {\n\t\t\tdateTimeFormatterBuilder.appendHourOfHalfday(1).appendLiteral(\":\").appendMinuteOfHour(2).appendLiteral(\" \").appendPattern(\"a\");\n\t\t}\n\t\treturn dateTimeFormatterBuilder.toFormatter();\n\t}\n\n\t@NonNull\n\tpublic static Runnable getUrlRunnable (final Context context, final String url, final boolean openInApp) {\n\t\treturn new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run () {\n\t\t\t\topenWebUrl(context, url, openInApp);\n\t\t\t}\n\t\t};\n\t}\n\n\tpublic static void hideKeyboard (View parentViewToGetFocus, Context context) {\n\t\tView view = parentViewToGetFocus.findFocus();\n\t\tif (view != null) {\n\t\t\tInputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);\n\t\t\timm.hideSoftInputFromWindow(view.getWindowToken(), 0);\n\t\t}\n\t}\n\n\tpublic static boolean isInDevMode (Context context) { return getPrefs(context).getBoolean(IS_IN_DEV_MODE, false); }\n\n\tpublic static boolean isNullOrEmpty (String s) {\n\t\treturn s == null || s.equals(\"\");\n\t}\n\n\tpublic static boolean isOneFalse (boolean... b) {\n\t\tfor (boolean bool : b) {\n\t\t\tif (!bool) { return true; }\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic static void openWebUrl (Context context, String url, boolean withinApp) {\n\t\tif (withinApp) {\n\t\t\tIntent codeOfConductViewIntent = new Intent(context, FullscreenWebViewActivity.class);\n\t\t\tcodeOfConductViewIntent.putExtra(FullscreenWebViewActivity.EXTRA_URL, url);\n\t\t\tcodeOfConductViewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\t\t\tcontext.startActivity(codeOfConductViewIntent);\n\t\t}\n\t\telse {\n\t\t\tIntent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));\n\t\t\tcontext.startActivity(intent);\n\t\t}\n\t}\n\n\tpublic static void parseDataSnapshotForAnnouncements (Context context, DataSnapshot snapshot) {\n\t\tArrayList<Announcement> announcements = new ArrayList<>();\n\t\tfor (DataSnapshot child : snapshot.getChildren()) {\n\t\t\tAnnouncement announcement = convertDataSnapshotToAnnouncement(child);\n\t\t\tannouncements.add(announcement);\n\t\t}\n\n\t\tCollections.sort(announcements);\n\t\tDataStore.setAnnouncements(context, announcements);\n\t\tBusUtils.post(new AnnouncementsUpdatedEvent(announcements));\n\t}\n\n\tpublic static void refreshAnnouncements (final Context context) {\n\t\tDatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();\n\t\tdbRef.child(AnnouncementController.getAnnouncementsTableString(context)).getRef().addListenerForSingleValueEvent(new ValueEventListener() {\n\t\t\t@Override\n\t\t\tpublic void onDataChange (DataSnapshot snapshot) {\n\t\t\t\tparseDataSnapshotForAnnouncements(context, snapshot);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onCancelled (DatabaseError databaseError) { }\n\t\t});\n\t}\n\n\tpublic static void refreshSchedule () {\n\t\tDatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();\n\t\tfinal ArrayList<ScheduleEvent> scheduleEvents = new ArrayList<>();\n\t\tdbRef.child(\"schedule\").orderByKey().getRef().addListenerForSingleValueEvent(new ValueEventListener() {\n\t\t\t@Override\n\t\t\tpublic void onDataChange (DataSnapshot snapshot) {\n\t\t\t\tscheduleEvents.clear();\n\t\t\t\tfor (DataSnapshot child : snapshot.getChildren()) {\n\t\t\t\t\tscheduleEvents.add(child.getValue(ScheduleEvent.class));\n\t\t\t\t}\n\n\t\t\t\tCollections.sort(scheduleEvents);\n\t\t\t\tBusUtils.post(new ScheduleUpdatedEvent(scheduleEvents));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onCancelled (DatabaseError databaseError) { }\n\t\t});\n\t\tDataStore.setScheduleEvents(scheduleEvents);\n\t}\n\n\tpublic static void runOnUI (Runnable runnable) {\n\t\tHackGSUApplication.delayRunnableOnUI(0, runnable);\n\t}\n\n\tpublic static void setIsInDevMode (final Activity context, boolean isInDevMode) {\n\t\tgetPrefs(context).edit().putBoolean(IS_IN_DEV_MODE, isInDevMode).apply();\n\n\t\tHackGSUApplication.toast(context, String.format(\"You're in %s mode! :D\", isInDevMode ? \"Dev\" : \"Prod\"));\n\t\tHackGSUApplication.delayRunnableOnUI(100, new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run () {\n\t\t\t\tcontext.stopService(new Intent(context, FirebaseService.class));\n\t\t\t\t//\t\t\t\tcontext.finishAffinity();\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static void setNotificationsEnabled (Context context, boolean newValue) {\n\t\tgetPrefs(context).edit().putBoolean(NOTIFICATIONS_ENABLED, newValue).apply();\n\t}\n\n\tpublic static void showKeyboard (View parentViewToGetFocus, Context context) {\n\t\tView view = parentViewToGetFocus.findFocus();\n\t\tif (view != null) {\n\t\t\tInputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);\n\t\t\timm.showSoftInput(view, 0);\n\t\t}\n\t}\n\n\tpublic static String toHumanReadableRelative (LocalDateTime timestamp) {\n\t\treturn toHumanReadableRelative(timestamp, false, true);\n\t}\n\n\tpublic static String toHumanReadableRelative (LocalDateTime timestamp, boolean seconds, boolean abreviate) {\n\t\tint flags = abreviate ? DateUtils.FORMAT_ABBREV_RELATIVE : 0;\n\t\tlong secondsFlags = seconds ? DateUtils.SECOND_IN_MILLIS : DateUtils.MINUTE_IN_MILLIS;\n\t\treturn (String) DateUtils.getRelativeTimeSpanString(timestamp.toDateTime().getMillis(), System.currentTimeMillis(), secondsFlags, flags);\n\t}\n\n\tpublic static void toast (final Context context, final String string) {\n\t\trunOnUI(new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run () {\n\t\t\t\tToast.makeText(context, string, Toast.LENGTH_LONG).show();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tpublic void onCreate () {\n\t\tsuper.onCreate();\n\n\t\tconnectToFirebaseAndDownloadData();\n\t}\n\n\t@Override\n\tpublic void onTerminate () {\n\t\tsuper.onTerminate();\n\n\t\tif (firebaseAuthListener != null) {\n\t\t\tfirebaseAuth.removeAuthStateListener(firebaseAuthListener);\n\t\t}\n\t}\n\n\tprivate void connectToFirebaseAndDownloadData () {\n\t\tAsyncTask.execute(new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run () {\n\t\t\t\tJodaTimeAndroid.init(HackGSUApplication.this);\n\n\t\t\t\tstartService(new Intent(HackGSUApplication.this, FirebaseService.class));\n\t\t\t}\n\t\t});\n\t}\n}", "public class AnnouncementController {\n\tpublic static final String ANNOUNCEMENTS_BOOKMARKED_KEY = \"announcements_bookmarked\";\n\tpublic static final String ANNOUNCEMENTS_LIKED_KEY = \"announcements_liked\";\n\tpublic static final String ANNOUNCEMENTS_NOTIFIED_KEY = \"announcements_notified\";\n\tpublic static final String ANNOUNCEMENTS_TABLE = \"announcements\";\n\tpublic static final String ANNOUNCEMENTS_TABLE_DEV = \"announcements_dev\";\n\n\tpublic static String getAnnouncementsTableString (Context context) {\n\t\treturn HackGSUApplication.isInDevMode(context) ? ANNOUNCEMENTS_TABLE_DEV : ANNOUNCEMENTS_TABLE;\n\t}\n\n\tpublic static void sendOrUpdateAnnouncement (Context context, Announcement announcement, final CallbackWithType<Void> callback) {\n\t\tFirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();\n\t\tif (currentUser != null) {\n\t\t\tDatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();\n\t\t\tDatabaseReference announcementRef = dbRef.child(getAnnouncementsTableString(context)).getRef();\n\t\t\tDatabaseReference announcementRefWithId;\n\t\t\tif (announcement.getFirebaseKey() == null || announcement.getFirebaseKey().equals(\"\")) {\n\t\t\t\tannouncementRefWithId = announcementRef.push();\n\t\t\t}\n\t\t\telse { announcementRefWithId = announcementRef.child(announcement.getFirebaseKey()); }\n\t\t\tannouncementRefWithId.setValue(announcement, new DatabaseReference.CompletionListener() {\n\t\t\t\t@SuppressLint (\"CommitPrefEdits\")\n\t\t\t\t@Override\n\t\t\t\tpublic void onComplete (DatabaseError databaseError, DatabaseReference databaseReference) {\n\t\t\t\t\tif (callback != null) {\n\t\t\t\t\t\tif (databaseError == null) { callback.onComplete(null); }\n\t\t\t\t\t\telse { callback.onError(); }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic static void setIsBookmarkedByMeBasedOnPrefs (Context context, ArrayList<Announcement> announcements) {\n\t\tif (context != null && announcements != null) {\n\t\t\tSharedPreferences prefs = HackGSUApplication.getPrefs(context);\n\t\t\tSet<String> bookmarkedAnnouncementIds = prefs.getStringSet(ANNOUNCEMENTS_BOOKMARKED_KEY, new HashSet<String>());\n\n\t\t\tfor (Announcement announcement : announcements) {\n\t\t\t\tannouncement.setBookmarkedByMe(bookmarkedAnnouncementIds.contains(announcement.getFirebaseKey()));\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void setIsLikedByMeBasedOnPrefs (Context context, ArrayList<Announcement> announcements) {\n\t\tif (context != null && announcements != null) {\n\t\t\tSharedPreferences prefs = HackGSUApplication.getPrefs(context);\n\t\t\tSet<String> bookmarkedAnnouncementIds = prefs.getStringSet(ANNOUNCEMENTS_LIKED_KEY, new HashSet<String>());\n\n\t\t\tfor (Announcement announcement : announcements) {\n\t\t\t\tannouncement.setLikedByMe(bookmarkedAnnouncementIds.contains(announcement.getFirebaseKey()));\n\t\t\t}\n\t\t}\n\t}\n\n\t@SuppressLint (\"CommitPrefEdits\")\n\tpublic static boolean shouldNotify (Context context, Announcement announcement) {\n\t\tboolean notificationsEnabled = HackGSUApplication.areNotificationsEnabled(context);\n\t\tboolean returnValue;\n\t\tif (context != null && announcement != null && !HackGSUApplication.isNullOrEmpty(announcement.getFirebaseKey())) {\n\t\t\tSharedPreferences prefs = HackGSUApplication.getPrefs(context);\n\t\t\tSet<String> notifiedAnnouncementIds = prefs.getStringSet(ANNOUNCEMENTS_NOTIFIED_KEY, new HashSet<String>());\n\t\t\treturnValue = !notifiedAnnouncementIds.contains(announcement.getFirebaseKey());\n\t\t\tif (returnValue) {\n\t\t\t\tnotifiedAnnouncementIds.add(announcement.getFirebaseKey());\n\t\t\t\tprefs.edit().remove(ANNOUNCEMENTS_NOTIFIED_KEY).commit();\n\t\t\t\tprefs.edit().putStringSet(ANNOUNCEMENTS_NOTIFIED_KEY, notifiedAnnouncementIds).commit();\n\t\t\t}\n\t\t}\n\t\telse { return notificationsEnabled; }\n\t\treturn notificationsEnabled && returnValue;\n\t}\n\n\t@SuppressLint (\"CommitPrefEdits\")\n\tpublic static void toggleBookmark (Context context, Announcement announcement) {\n\t\tif (context != null && announcement != null && announcement.getFirebaseKey() != null) {\n\t\t\tannouncement.setBookmarkedByMe(!announcement.isBookmarkedByMe());\n\n\t\t\tSharedPreferences prefs = HackGSUApplication.getPrefs(context);\n\t\t\tSet<String> bookmarkedAnnouncementIds = prefs.getStringSet(ANNOUNCEMENTS_BOOKMARKED_KEY, new HashSet<String>());\n\n\t\t\tif (announcement.isBookmarkedByMe()) { bookmarkedAnnouncementIds.add(announcement.getFirebaseKey()); }\n\t\t\telse { bookmarkedAnnouncementIds.remove(announcement.getFirebaseKey()); }\n\n\t\t\tprefs.edit().remove(ANNOUNCEMENTS_BOOKMARKED_KEY).commit();\n\t\t\tprefs.edit().putStringSet(ANNOUNCEMENTS_BOOKMARKED_KEY, bookmarkedAnnouncementIds).apply();\n\t\t}\n\t}\n\n\t@SuppressLint (\"CommitPrefEdits\")\n\tpublic static void toggleLiked (Context context, Announcement announcement) {\n\t\tif (context != null && announcement != null && announcement.getFirebaseKey() != null) {\n\t\t\tannouncement.toggleLikedByMe();\n\n\t\t\tSharedPreferences prefs = HackGSUApplication.getPrefs(context);\n\t\t\tSet<String> bookmarkedAnnouncementIds = prefs.getStringSet(ANNOUNCEMENTS_LIKED_KEY, new HashSet<String>());\n\n\t\t\tif (announcement.isLikedByMe()) { bookmarkedAnnouncementIds.add(announcement.getFirebaseKey()); }\n\t\t\telse { bookmarkedAnnouncementIds.remove(announcement.getFirebaseKey()); }\n\n\t\t\tsendOrUpdateAnnouncement(context, announcement, null);\n\n\t\t\tprefs.edit().remove(ANNOUNCEMENTS_LIKED_KEY).commit();\n\t\t\tprefs.edit().putStringSet(ANNOUNCEMENTS_LIKED_KEY, bookmarkedAnnouncementIds).apply();\n\t\t}\n\t}\n}", "public class Announcement implements Serializable, Comparable<Announcement> {\n\tprivate String bodyText;\n\tprivate boolean bookmarkedByMe;\n\tprivate String firebaseKey;\n\tprivate boolean likedByMe;\n\tprivate int likes;\n\tprivate long timestamp;\n\tprivate String title;\n\tprivate Topic topic;\n\n\tpublic Announcement (String title, String bodyText, Topic topic) {\n\t\tthis.title = title;\n\t\tthis.bodyText = bodyText;\n\t\tthis.topic = topic;\n\n\t\tsetTimestamp(System.currentTimeMillis());\n\t}\n\n\tpublic Announcement () { }\n\n\tpublic enum Topic {\n\t\tGENERAL(R.drawable.ic_announcements), TECH(R.drawable.ic_devices), FOOD(R.drawable.ic_food);\n\t\tprivate\n\t\t@DrawableRes int icon;\n\n\t\tTopic (int icon) {\n\t\t\tthis.icon = icon;\n\t\t}\n\n\t\tpublic\n\t\t@DrawableRes\n\t\tint getIcon () {\n\t\t\treturn icon;\n\t\t}\n\t}\n\n\t@Override\n\tpublic int compareTo (Announcement other) {\n\t\treturn other == null || other.getTimestampDateTime().isBefore(getTimestampDateTime()) ? -1 : 1;\n\t}\n\n\t@Exclude\n\tpublic void setFirebaseKey (String firebaseKey) {\n\t\tthis.firebaseKey = firebaseKey;\n\t}\n\n\t@Exclude\n\tpublic String getFirebaseKey () {\n\t\treturn firebaseKey;\n\t}\n\n\tpublic String getTitle () {\n\t\treturn title;\n\t}\n\n\tpublic void setTitle (String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic int getLikes () {\n\t\treturn likes;\n\t}\n\n\tpublic void setLikes (int likes) {\n\t\tthis.likes = likes;\n\t}\n\n\tpublic String getBodyText () {\n\t\treturn bodyText;\n\t}\n\n\tpublic void setBodyText (String bodyText) {\n\t\tthis.bodyText = bodyText;\n\t}\n\n\tpublic long getTimestamp () {\n\t\treturn timestamp;\n\t}\n\n\t@Exclude\n\tpublic LocalDateTime getTimestampDateTime () {\n\t\treturn new LocalDateTime(getTimestamp());\n\t}\n\n\tpublic void setTimestamp (long timestamp) {\n\t\tthis.timestamp = timestamp;\n\t}\n\n\tpublic String getTopic () {\n\t\treturn topic == null ? null : topic.name();\n\t}\n\n\tpublic void setTopic (String topic) {\n\t\ttry {\n\t\t\tthis.topic = Topic.valueOf(topic);\n\t\t} catch (IllegalArgumentException ignored) {\n\t\t\tthis.topic = Topic.GENERAL;\n\t\t}\n\t}\n\n\t@Exclude\n\tpublic void setTopicEnum (Topic topic) {\n\t\tthis.topic = topic;\n\t}\n\n\t@Exclude\n\tpublic Topic getTopicEnum () {\n\t\treturn topic;\n\t}\n\n\t@Exclude\n\tpublic String getShareText (Context context) {\n\t\t// TODO: 10/6/16 : Maybe make this share message more better..? Also add Play Store link\n\t\tDateTimeFormatter dateTimeFormatter = HackGSUApplication.getTimeFormatter24OrNot(context);\n\t\tString time = getTimestampDateTime().toString(dateTimeFormatter);\n\t\treturn String.format(\"Look at this announcement at HackGSU\\n\\ntitle: %s\\nWhen: %s - %s\\nMessage: %s\",\n\t\t\t\t\t\t\t getTitle(),\n\t\t\t\t\t\t\t HackGSUApplication.toHumanReadableRelative(getTimestampDateTime()),\n\t\t\t\t\t\t\t time,\n\t\t\t\t\t\t\t getBodyText());\n\t}\n\n\t@Exclude\n\tpublic void toggleLikedByMe () {\n\t\tif (isLikedByMe()) { unlike(); }\n\t\telse { like(); }\n\t}\n\n\t@Exclude\n\tpublic boolean isLikedByMe () {\n\t\treturn likedByMe;\n\t}\n\n\t@Exclude\n\tpublic boolean isBookmarkedByMe () {\n\t\treturn bookmarkedByMe;\n\t}\n\n\t@Exclude\n\tpublic void setBookmarkedByMe (boolean bookmarkedByMe) {\n\t\tthis.bookmarkedByMe = bookmarkedByMe;\n\t}\n\n\t@Exclude\n\tpublic void setLikedByMe (boolean likedByMe) {\n\t\tthis.likedByMe = likedByMe;\n\t}\n\n\t@Exclude\n\tprivate void like () {\n\t\tif (!isLikedByMe()) { likes++; }\n\t\tsetLikedByMe(true);\n\t}\n\n\t@Exclude\n\tprivate void unlike () {\n\t\tif (isLikedByMe()) { likes--; }\n\t\tsetLikedByMe(false);\n\t}\n}", "public class SmoothLinearLayoutManager extends LinearLayoutManager {\n\tprivate static final float MILLISECONDS_PER_INCH = 50f;\n\tprivate Context mContext;\n\n\tpublic SmoothLinearLayoutManager (Context context) {\n\t\tsuper(context);\n\t\tmContext = context;\n\t}\n\n\t@Override\n\tpublic void scrollToPosition (int position) {\n\t\tsmoothScrollTo(position);\n\t}\n\n\t@Override\n\tpublic void smoothScrollToPosition (RecyclerView recyclerView, RecyclerView.State state, final int position) {\n\t\tsmoothScrollTo(position);\n\t}\n\n\tprivate void smoothScrollTo (final int position) {\n\t\tLinearSmoothScroller smoothScroller = new LinearSmoothScroller(mContext) {\n\t\t\t@Override\n\t\t\tpublic PointF computeScrollVectorForPosition (int targetPosition) {\n\t\t\t\treturn SmoothLinearLayoutManager.this.computeScrollVectorForPosition(targetPosition);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected float calculateSpeedPerPixel (DisplayMetrics displayMetrics) {\n\t\t\t\treturn MILLISECONDS_PER_INCH / displayMetrics.densityDpi;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected int getVerticalSnapPreference () {\n\t\t\t\treturn SNAP_TO_START;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected void onStop () {\n\t\t\t\tsuper.onStop();\n\n\t\t\t\tfinal View viewAtPosition = findViewByPosition(position);\n\t\t\t\tif (viewAtPosition != null) {\n\t\t\t\t\tint dyToMakeVisible = calculateDyToMakeVisible(viewAtPosition, getVerticalSnapPreference());\n\t\t\t\t\tint timeForScrolling = calculateTimeForScrolling(dyToMakeVisible) + calculateTimeForDeceleration(dyToMakeVisible);\n\t\t\t\t\tviewAtPosition.animate()\n\t\t\t\t\t\t\t\t .setDuration(100)\n\t\t\t\t\t\t\t\t .scaleX(1.2f)\n\t\t\t\t\t\t\t\t .scaleY(1.2f)\n\t\t\t\t\t\t\t\t .alpha(0.5f)\n\t\t\t\t\t\t\t\t .setStartDelay(timeForScrolling)\n\t\t\t\t\t\t\t\t .withEndAction(new Runnable() {\n\t\t\t\t\t\t\t\t\t @Override\n\t\t\t\t\t\t\t\t\t public void run () {\n\t\t\t\t\t\t\t\t\t\t viewAtPosition.animate().setStartDelay(0).setDuration(100).scaleY(1).scaleX(1).alpha(1).start();\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\t .start();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tsmoothScroller.setTargetPosition(position);\n\t\tstartSmoothScroll(smoothScroller);\n\t}\n}" ]
import android.content.Context; import android.content.Intent; import android.content.res.ColorStateList; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.AppCompatImageButton; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.hackgsu.fall2016.android.DataStore; import com.hackgsu.fall2016.android.HackGSUApplication; import com.hackgsu.fall2016.android.R; import com.hackgsu.fall2016.android.controllers.AnnouncementController; import com.hackgsu.fall2016.android.model.Announcement; import com.hackgsu.fall2016.android.utils.SmoothLinearLayoutManager; import org.joda.time.LocalDateTime; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; import java.util.Locale;
package com.hackgsu.fall2016.android.views; public class AnnouncementsRecyclerView extends ThemedEmptyStateRecyclerView { private AnnouncementEventAdapter adapter; private SmoothLinearLayoutManager layoutManager; private boolean showOnlyBookmarked; public AnnouncementsRecyclerView (Context context) { super(context); init(null, 0); } public AnnouncementsRecyclerView (Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public AnnouncementsRecyclerView (Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } public static String getTimestampString (Context context, LocalDateTime dateTime) { String timeTillString = HackGSUApplication.toHumanReadableRelative(dateTime); DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder(); DateTimeFormatter dateTimeFormatter = HackGSUApplication.getTimeFormatter24OrNot(context, dateTimeFormatterBuilder); return String.format("%s | %s", timeTillString, dateTime.toString(dateTimeFormatter)); } public class AnnouncementEventAdapter extends Adapter<AnnouncementsEventViewHolder> { @Override public AnnouncementsEventViewHolder onCreateViewHolder (ViewGroup parent, int viewType) { View inflate = View.inflate(getContext(), R.layout.announcement_card, null); inflate.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); return new AnnouncementsEventViewHolder(inflate); } @Override public void onBindViewHolder (AnnouncementsEventViewHolder holder, int position) {
holder.loadAnnouncement(DataStore.getAnnouncements(shouldShowOnlyBookmarked()).get(position));
0
loopfz/Lucki
src/shaft/poker/agent/handranges/weightedrange/PlayerWTRange.java
[ "public interface IHandEvaluator {\n public void compute(List<Card> holecards, List<Card> board, IHandRange range, int numPlayers);\n \n public double effectiveHandStrength();\n public double rawHandStrength();\n public double posPotential();\n public double negPotential();\n }", "public interface IHandRange {\n public double handWeight(Card c1, Card c2);\n}", "public class EnumCandidate {\n private List<Card> _cards;\n private int _weight;\n \n public EnumCandidate(List<Card> cards, int weight) {\n _cards = cards;\n _weight = weight;\n }\n \n public List<Card> cards() {\n return _cards;\n }\n \n public int weight() {\n return _weight;\n }\n \n public boolean generic() {\n return _weight == 1;\n }\n \n public boolean contentsEquals (Card c1, Card c2, boolean generic) {\n if (generic && _weight == 1) {\n return false;\n }\n if (_cards.size() != 2) {\n return false;\n }\n if ((_cards.get(0).rank() == c1.rank() && _cards.get(1).rank() == c2.rank())\n || (_cards.get(0).rank() == c2.rank() && _cards.get(1).rank() == c1.rank())) {\n return true;\n }\n return false;\n }\n \n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n \n for (Card c : _cards) {\n sb.append(\" | \");\n sb.append(c.toString());\n }\n \n sb.append(\" | w:\");\n sb.append(_weight);\n \n return sb.toString();\n }\n \n /*\n * Build buckets of candidates (potential opponent hole cards and turn/river draws)\n * to increase lookahead performance\n */\n public static List<EnumCandidate> buildCandidates(List<Card> holeCards, List<Card> board) {\n \n int[] cardsLeft = new int[14];\n \n List<Card.Suit> weakSuits = new ArrayList<>(4);\n List<Card.Suit> strongSuits = new ArrayList<>(4);\n List<EnumCandidate> holeCandidates = new ArrayList(300);\n \n List<Card> c1Candidates;\n List<Card> c2Candidates;\n \n // Candidates for 1st card (all values -holes -board)\n c1Candidates = new ArrayList(Card.values());\n if (holeCards != null) {\n c1Candidates.removeAll(holeCards);\n }\n c1Candidates.removeAll(board);\n \n // Candidates for 2nd card (identical for now)\n c2Candidates = new ArrayList<>(c1Candidates);\n \n // Potential Flush suits\n for (Card.Suit s : Card.Suit.values()) {\n int count = 0;\n for (Card c : board) {\n if (c.suit() == s) {\n count++;\n }\n }\n // Can hit Flush with a single card of the suit\n if (count >= 3) {\n strongSuits.add(s);\n }\n // Can hit FLush with Suited hand\n else if (count >= 2) {\n weakSuits.add(s);\n }\n }\n \n // Add any suit with an empty (preflop) board, to distinguish suited/unsuited hands\n if (board.isEmpty()) {\n weakSuits.add(Card.Suit.HEARTS);\n }\n \n for (Card.Rank r : Card.Rank.values()) {\n cardsLeft[r.ordinal()] = 4;\n }\n if (holeCards != null) {\n for (Card c : holeCards) {\n if (!weakSuits.contains(c.suit())\n && !strongSuits.contains(c.suit())) {\n cardsLeft[c.rank().ordinal()]--;\n }\n }\n }\n for (Card c : board) {\n if (!weakSuits.contains(c.suit())\n && !strongSuits.contains(c.suit())) {\n cardsLeft[c.rank().ordinal()]--;\n }\n }\n \n for (Card c1 : c1Candidates) {\n c2Candidates.remove(c1);\n \n for (Card c2 : c2Candidates) {\n if (c1.suit() != c2.suit()) {\n if (!weakSuits.contains(c1.suit())\n && !weakSuits.contains(c2.suit())) {\n \n boolean redundant = false;\n int weight = 1;\n if (!strongSuits.contains(c1.suit())\n && !strongSuits.contains(c2.suit())) {\n for (EnumCandidate cand : holeCandidates) {\n if (cand.contentsEquals(c1, c2, true)) {\n redundant = true;\n break;\n }\n }\n if (!redundant) {\n // Non redundant generic hand, compute weight using count of cards left in the deck\n // minus suited hands or hands with a strong suit card\n if (c1.rank() != c2.rank()) {\n weight = cardsLeft[c1.rank().ordinal()] * cardsLeft[c2.rank().ordinal()]\n - (weakSuits.size() * (cardsLeft[c1.rank().ordinal()] + cardsLeft[c2.rank().ordinal()]))\n - (strongSuits.size() * (cardsLeft[c1.rank().ordinal()] - 1))\n - (strongSuits.size() * (cardsLeft[c2.rank().ordinal()] - 1));\n }\n else {\n weight = (cardsLeft[c1.rank().ordinal()] * (cardsLeft[c1.rank().ordinal()] - 1)) / 2\n - (strongSuits.size() * (cardsLeft[c1.rank().ordinal()] - 1));\n }\n }\n }\n \n if (!redundant) {\n // Non redundant, add to candidates\n List<Card> cards = new ArrayList(2);\n cards.add(c1);\n cards.add(c2);\n holeCandidates.add(new EnumCandidate(cards, weight));\n }\n }\n }\n else if (weakSuits.contains(c1.suit())) {\n // Relevant suited hand, add itself (weight = 1) as candidate\n List<Card> cards = new ArrayList(2);\n cards.add(c1);\n cards.add(c2);\n holeCandidates.add(new EnumCandidate(cards, 1));\n }\n }\n }\n \n return holeCandidates;\n //_holeCandidates = holeCandidates;\n \n /*for (Suit s : Suit.values()) {\n if (!weakSuits.contains(s)) {\n int count = 0;\n for (Card c : board) {\n if (c.suit() == s) {\n count++;\n }\n }\n for (Card c : holeCards) {\n if (c.suit() == s) {\n count++;\n }\n }\n if (count + (5 - board.size()) >= 5) {\n weakSuits.add(s);\n }\n }\n }*/\n \n /*\n c2Candidates = new ArrayList<>(c1Candidates);\n \n List<EnumCandidate> drawCandidates = new ArrayList<>(2);\n if (board.size() == 4) {\n _drawCandidates = null;\n return null;\n //c1Candidates = new ArrayList<>(1);\n //c1Candidates.add(board.get(3));\n }\n \n for (Card c1 : c1Candidates) {\n c2Candidates.remove(c1);\n \n for (Card c2 : c2Candidates) {\n if (weakSuits.contains(c1.suit())\n || strongSuits.contains(c1.suit())) {\n List<Card> cards = new ArrayList<>(2);\n cards.add(c1);\n cards.add(c2);\n drawCandidates.add(new EnumCandidate(cards, 1 * (5 - board.size())));\n }\n else {\n boolean redundant = false;\n for (EnumCandidate cand : drawCandidates) {\n if (cand.contentsEquals(c1, c2, true)) {\n redundant = true;\n break;\n }\n }\n \n if (!redundant) {\n List<Card> cards = new ArrayList<>(2);\n cards.add(c1);\n cards.add(c2);\n int weight;\n if (c1.rank() != c2.rank()) {\n weight = cardsLeft[c1.rank().ordinal()] * cardsLeft[c2.rank().ordinal()]\n - ((weakSuits.size() + strongSuits.size()) * (cardsLeft[c1.rank().ordinal()] - 1))\n - ((weakSuits.size() + strongSuits.size()) * (cardsLeft[c2.rank().ordinal()] - 1));\n }\n else {\n weight = cardsLeft[c1.rank().ordinal()] * (cardsLeft[c1.rank().ordinal()] - 1) / 2\n - ((weakSuits.size() + strongSuits.size()) * (cardsLeft[c1.rank().ordinal()] - 1));\n }\n weight *= 2;\n drawCandidates.add(new EnumCandidate(cards, weight));\n }\n }\n }\n }\n \n _drawCandidates = drawCandidates;\n \n return null;*/\n }\n\n}", "public interface IPlayerRange extends IHandRange {\n \n public boolean activePlayer();\n \n}", "public class Card implements Comparable<Card> {\n\n public enum Rank {\n DEUCE,\n THREE,\n FOUR,\n FIVE,\n SIX,\n SEVEN,\n EIGHT,\n NINE,\n TEN,\n JACK,\n QUEEN,\n KING,\n ACE\n }\n \n public enum Suit {\n CLUBS,\n SPADES,\n HEARTS,\n DIAMONDS\n }\n \n private final Rank _rank;\n private final Suit _suit;\n private static final List<Card> _values = new ArrayList<Card>(Rank.values().length * Suit.values().length) {\n {\n for (Suit suit : Suit.values()) {\n for (Rank rank : Rank.values()) {\n add(new Card(rank, suit));\n }\n }\n }\n };\n \n public Card(Rank rank, Suit suit) {\n _rank = rank;\n _suit = suit;\n }\n \n @Override\n public String toString() {\n return _rank.toString() + \" of \" + _suit.toString();\n }\n \n public Rank rank() {\n return _rank;\n }\n \n public Suit suit() {\n return _suit;\n }\n \n public static List<Card> values() {\n return _values;\n }\n \n @Override\n public int compareTo(Card o) {\n if (_rank.ordinal() > o._rank.ordinal()) {\n return 1;\n }\n else if (_rank.ordinal() < o._rank.ordinal()) {\n return -1;\n }\n return 0;\n }\n\n}", "public class Card implements Comparable<Card> {\n\n public enum Rank {\n DEUCE,\n THREE,\n FOUR,\n FIVE,\n SIX,\n SEVEN,\n EIGHT,\n NINE,\n TEN,\n JACK,\n QUEEN,\n KING,\n ACE\n }\n \n public enum Suit {\n CLUBS,\n SPADES,\n HEARTS,\n DIAMONDS\n }\n \n private final Rank _rank;\n private final Suit _suit;\n private static final List<Card> _values = new ArrayList<Card>(Rank.values().length * Suit.values().length) {\n {\n for (Suit suit : Suit.values()) {\n for (Rank rank : Rank.values()) {\n add(new Card(rank, suit));\n }\n }\n }\n };\n \n public Card(Rank rank, Suit suit) {\n _rank = rank;\n _suit = suit;\n }\n \n @Override\n public String toString() {\n return _rank.toString() + \" of \" + _suit.toString();\n }\n \n public Rank rank() {\n return _rank;\n }\n \n public Suit suit() {\n return _suit;\n }\n \n public static List<Card> values() {\n return _values;\n }\n \n @Override\n public int compareTo(Card o) {\n if (_rank.ordinal() > o._rank.ordinal()) {\n return 1;\n }\n else if (_rank.ordinal() < o._rank.ordinal()) {\n return -1;\n }\n return 0;\n }\n\n}", "public interface IPlayerActionListener {\n\n public void gameAction(ITable table, IPlayerData plData, ActionType type, int amount);\n \n public void leave(ITable table, IPlayerData plData);\n}", "public interface ITable {\n \n enum ActionType {\n FOLD,\n CALL,\n BET\n }\n \n enum Round {\n PREFLOP,\n FLOP,\n TURN,\n RIVER\n }\n \n public void runGame(int hands, int stackSize, int sBlind, int bBlind);\n \n public int numberBets();\n public int maxBets();\n public int numberCallers();\n public Round round();\n public int potSize();\n \n public int numberPlayers();\n public int numberActivePlayers();\n public int numberPlayersToAct();\n \n public int smallBlind();\n public int bigBlind();\n \n public List<Card> board();\n \n public String playerSmallBlind();\n public String playerBigBlind();\n public String playerDealer();\n \n public void registerListenerForPlayer(String id, IPlayerActionListener listener);\n public void registerPriorityListenerForPlayer(String id, IPlayerActionListener listener);\n public void registerListenAllPlayerEvents(IPlayerActionListener listener);\n public void registerEventListener(IGameEventListener listener);\n\n}", "public interface ITable {\n \n enum ActionType {\n FOLD,\n CALL,\n BET\n }\n \n enum Round {\n PREFLOP,\n FLOP,\n TURN,\n RIVER\n }\n \n public void runGame(int hands, int stackSize, int sBlind, int bBlind);\n \n public int numberBets();\n public int maxBets();\n public int numberCallers();\n public Round round();\n public int potSize();\n \n public int numberPlayers();\n public int numberActivePlayers();\n public int numberPlayersToAct();\n \n public int smallBlind();\n public int bigBlind();\n \n public List<Card> board();\n \n public String playerSmallBlind();\n public String playerBigBlind();\n public String playerDealer();\n \n public void registerListenerForPlayer(String id, IPlayerActionListener listener);\n public void registerPriorityListenerForPlayer(String id, IPlayerActionListener listener);\n public void registerListenAllPlayerEvents(IPlayerActionListener listener);\n public void registerEventListener(IGameEventListener listener);\n\n}" ]
import shaft.poker.game.table.IPlayerActionListener; import shaft.poker.game.ITable; import shaft.poker.game.ITable.*; import shaft.poker.game.table.*; import java.util.List; import shaft.poker.agent.IHandEvaluator; import shaft.poker.agent.IHandRange; import shaft.poker.agent.enumerationtools.EnumCandidate; import shaft.poker.agent.handranges.IPlayerRange; import shaft.poker.game.Card; import shaft.poker.game.Card.*;
/* * The MIT License * * Copyright 2013 Thomas Schaffer <[email protected]>. * * 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 shaft.poker.agent.handranges.weightedrange; /** * * @author Thomas Schaffer <[email protected]> */ public class PlayerWTRange implements IPlayerRange, IPlayerActionListener, IGameEventListener { private String _playerId; private IWeightTable _wt; private IFrequencyTable _freq; private IHandEvaluator _eval; private IHandRange _compositeRange; private static final double VARIANCE_FACTOR = 0.4; private static final double LOW_WEIGHT = 0.01; private static final double HIGH_WEIGHT = 1.00; private boolean _dead; private boolean _active; public PlayerWTRange(String playerId, IWeightTable wt, IFrequencyTable freq, IHandEvaluator eval, IHandRange compRange, ITable table) { _playerId = playerId; _wt = wt; _freq = freq; _eval = eval; _compositeRange = compRange; table.registerListenerForPlayer(playerId, this); table.registerEventListener(this); } private void reweight(double threshold, List<Card> board, int numPlayers, double potOdds) { double variance; variance = VARIANCE_FACTOR * (1 - threshold);
List<EnumCandidate> holeCards = EnumCandidate.buildCandidates(null, board);
2
sweer/hex-image-compress
src/pipeline/Decoder.java
[ "public class DoubleLattice extends Lattice {\r\n\t/**\r\n\t * @uml.property name=\"data\"\r\n\t */\r\n\tprivate final double[][] data;\r\n\tpublic DoubleLattice(double[][] data, int ox, int oy) {\r\n\t\tsuper(ox,oy);\r\n\t\tthis.data = data;\r\n\t}\r\n\t\r\n public DoubleLattice(DoubleLattice lattice) {\r\n this(lattice.data, lattice.ox, lattice.oy);\r\n }\r\n \r\n /**\r\n\t * @return\r\n\t * @uml.property name=\"data\"\r\n\t */\r\n public double[][] getData() {\r\n return data;\r\n }\r\n}\r", "public class LongLattice extends Lattice {\n\n public static final int SHIFT = 0;\n public static final long NAN = Long.MIN_VALUE;\n final public double min;\n final public double factor;\n protected long[][] data;\n private short[][] NANPositions;\n\n public static class Run {\n public short x;\n public short y;\n public short length;\n\n public Run(short x, short y, short length) {\n this.x = x;\n this.y = y;\n this.length = length;\n }\n }\n\n public LongLattice(long[][] data, int ox, int oy, double min, double factor) {\n super(ox, oy);\n this.data = data;\n this.min = min;\n this.factor = factor;\n }\n\n public LongLattice(LongLattice lattice) {\n this(lattice.data, lattice.ox, lattice.oy, lattice.min, lattice.factor);\n }\n\n public DoubleLattice getDequantizedLattice() {\n double descaled[][] = new double[data.length][data[0].length];\n\n for (int y = 0; y < data.length; y++) {\n long[] rowSrc = data[y];\n double[] rowDst = descaled[y];\n for (int x = 0; x < rowSrc.length; x++) {\n long b = rowSrc[x];\n if (b == NAN) {\n rowDst[x] = NaN;\n } else {\n rowDst[x] = (b + SHIFT) / factor + min;\n }\n }\n }\n return new DoubleLattice(descaled, ox, oy);\n }\n\n public long[][] getData() {\n return data;\n }\n\n public static LongLattice fromLattice(DoubleLattice source) {\n double[][] data = source.getData();\n double min = Double.MAX_VALUE;\n double max = Double.MIN_VALUE;\n for (int y = 0; y < data.length; y++) {\n double[] row = data[y];\n for (int x = 0; x < data[0].length; x++) {\n double d = row[x];\n if (isNaN(d))\n continue;\n if (d > max)\n max = d;\n if (d < min)\n min = d;\n }\n }\n\n long scaled[][] = new long[data.length][data[0].length];\n double range = max - min;\n double factor = 255 / range;\n for (int y = 0; y < data.length; y++) {\n double[] rowSrc = data[y];\n long[] rowDst = scaled[y];\n for (int x = 0; x < data[0].length; x++) {\n double d = rowSrc[x];\n if (isNaN(d)) {\n rowDst[x] = NAN;\n } else {\n rowDst[x] = (long) (Math.round((rowSrc[x] - min) * factor) - SHIFT);\n }\n }\n }\n\n return new LongLattice(scaled, source.ox, source.oy, min, factor);\n }\n\n public short[][] getNANPositions() {\n if (NANPositions == null) {\n initializeNANPositions();\n }\n return NANPositions;\n }\n\n private void initializeNANPositions() {\n int sizey = data.length;\n int sizex = data[0].length;\n NANPositions = new short[sizey][2];\n for (int y = 0; y < sizey; y++) {\n short x = 0;\n while (x < sizex && data[y][x] == NAN) {\n x++;\n }\n NANPositions[y][0] = (short) (x - 1);\n\n x = (short) (sizex - 1);\n while (x >= 0 && data[y][x] == NAN) {\n x--;\n }\n NANPositions[y][1] = (short) (x + 1);\n }\n }\n\n public short[][] getNANPositionStream() {\n short[][] source = getNANPositions();\n int size = source.length;\n short[][] result = new short[size][2];\n result[0][0] = source[0][0];\n result[0][1] = source[0][1];\n for (int i = 1; i < size; i++) {\n result[i][0] = (short) (source[i][0] - source[i - 1][0]);\n result[i][1] = (short) (source[i][1] - source[i - 1][1]);\n }\n return result;\n }\n\n public void loadNANPositionStream(short[][] source) {\n int size = data.length;\n if (size != source.length)\n throw new IllegalArgumentException(\"Parameter length = \" + source.length\n + \", data length = \" + data.length);\n\n NANPositions = new short[size][2];\n NANPositions[0][0] = source[0][0];\n NANPositions[0][1] = source[0][1];\n for (int y = 0; y < size; y++) {\n if (y > 0) {\n NANPositions[y][0] = (short) (source[y][0] + NANPositions[y - 1][0]);\n NANPositions[y][1] = (short) (source[y][1] + NANPositions[y - 1][1]);\n }\n for (int x = 0; x <= NANPositions[y][0]; x++) {\n data[y][x] = NAN;\n }\n for (int x = NANPositions[y][1]; x < data[y].length; x++) {\n data[y][x] = NAN;\n }\n }\n }\n\n public byte[] getDataAsByteStream() {\n ByteArrayOutputStream byteOut = new ByteArrayOutputStream();\n short NANPositions[][] = getNANPositions();\n\n for (int y = 0; y < data.length; y++) {\n long row[] = data[y];\n for (int x = 0; x < row.length; x++) {\n if (x <= NANPositions[y][0] || x >= NANPositions[y][1])\n continue;\n\n long d = row[x];\n if (d == NAN) {\n d = 0;\n }\n byteOut.write((byte) d);\n }\n }\n return byteOut.toByteArray();\n }\n\n public void loadDataAsByteStream(byte[] source) {\n int n = 0;\n short NANPositions[][] = getNANPositions();\n\n for (int y = 0; y < data.length; y++) {\n long row[] = data[y];\n for (int x = 0; x < row.length; x++) {\n if (x <= NANPositions[y][0] || x >= NANPositions[y][1])\n continue;\n\n row[x] = source[n++] & 0xff;\n }\n }\n\n }\n\n public List<Run> getNanRuns() {\n\n short NANPositions[][] = getNANPositions();\n List<Run> result = new LinkedList<Run>();\n for (int y = 0; y < data.length; y++) {\n long row[] = data[y];\n boolean insideRun = false;\n int runStart = -1;\n for (int x = 0; x < row.length; x++) {\n if (x <= NANPositions[y][0] || x >= NANPositions[y][1])\n continue;\n\n if (row[x] == NAN) {\n if (!insideRun) {\n insideRun = true;\n runStart = x;\n }\n continue;\n }\n\n if (insideRun) {\n result.add(new Run((short) runStart, (short) y, (short) (x - runStart)));\n insideRun = false;\n }\n }\n }\n return result;\n }\n\n public void loadNanRuns(List<Run> runs) {\n for (Run run : runs) {\n for (int x = run.x; x < run.x + run.length; x++) {\n data[run.y][x] = NAN;\n }\n }\n }\n\n public static LongLattice createCopyOf(LongLattice lattice) {\n long[][] srcData = lattice.getData();\n long[][] dstData = ArrayUtils.copyOfArray(srcData);\n return new LongLattice(dstData, lattice.ox, lattice.oy, lattice.min, lattice.factor);\n }\n}", "public static class Run {\n public short x;\n public short y;\n public short length;\n\n public Run(short x, short y, short length) {\n this.x = x;\n this.y = y;\n this.length = length;\n }\n}", "public class Compressor {\n\t\n\t/* Tailored to int as 32bit signed */\n\tprivate final static int FIRST_QUARTER = 0x200000;\n\tprivate final static int THIRD_QUARTER = 0x600000;\n\tprivate final static int HALF = 0x400000;\n\tprivate final static int HIGH = 0x7fffff;\n\tprivate final static int INITIAL_READ = 23;\n\t\n\tpublic static byte[] compress(byte[] in) {\n\t\t\n\t\tclass BitOutputBuffer {\n\t\t\tByteArrayOutputStream buf;\n\t\t\tbyte[] currentByte;\n\t\t\tbyte currentBit;\n\t\t\tBitOutputBuffer() {\n\t\t\t\tbuf = new ByteArrayOutputStream();\n\t\t\t\tcurrentByte = new byte[1];\n\t\t\t\tcurrentByte[0] = 0;\n\t\t\t\tcurrentBit = 0;\n\t\t\t}\n\t\t\tvoid writeBit(byte bit) throws IOException {\n\t\t\t\tcurrentByte[0] = (byte) ((currentByte[0]) << 1);\n\t\t\t\tcurrentByte[0] += bit;\n\t\t\t\tcurrentBit+=1;\n\t\t\t\tif (currentBit==8) {\n\t\t\t\t\tbuf.write(currentByte);\n\t\t\t\t\tcurrentByte[0] = 0;\n\t\t\t\t\tcurrentBit = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvoid flush() throws IOException {\n\t\t\t\t/* Pad the buffer with zeros */\n\t\t\t\twhile (currentBit!=0) {\n\t\t\t\t\twriteBit((byte) 0);\n\t\t\t\t}\n\t\t\t\tbuf.flush();\n\t\t\t}\n\t\t\t\n\t\t\tbyte[] toByteArray() {\n\t\t\t\ttry {\n\t\t\t\t\tbuf.flush();\n\t\t\t\t\treturn buf.toByteArray();\n\t\t\t\t}\n\t\t\t\tcatch (IOException e) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tBitOutputBuffer bitBuf = new BitOutputBuffer();\n\t\t\n\t\tint low = 0, high = HIGH, total;\n\t\tint mLow = low, mHigh = high, mStep = 0;\n\t\tint mScale = 0;\n\t\tint current = 0;\n\t\t\n\t\t/* Initialize frequency table */\n\t\tint[] freq = new int[257];\n\t\tfor (int i=0; i<257; i++) freq[i] = 1;\n\t\ttotal = 257;\n\t\t\n\t\ttry {\n\t\t\t\n\t\t\tfor (int i=0; i<in.length + 1; i++) {\n\t\t\t\t\n\t\t\t\tif (i == in.length) {\n\t\t\t\t\t/* Encode terminator if necessary */\n\t\t\t\t\tlow = total - 1;\n\t\t\t\t\thigh = total;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t/* Otherwise retrieve cumulative freq */\n\t\t\t\t\tcurrent = in[i] & 0xff; // Get unsigned value\n\t\t\t\t\tlow = 0;\n\t\t\t\t\tfor (int j=0; j<current; j++) {\n\t\t\t\t\t\tlow += freq[j];\n\t\t\t\t\t}\n\t\t\t\t\thigh = low + freq[current];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t/* 2. Update the coder */\n\t\t\t\tmStep = ( mHigh - mLow + 1 ) / total;\n\t\t\t\tmHigh = (mLow + mStep * high) - 1;\n\t\t\t\tmLow = mLow + mStep * low;\n\t\t\t\t\n\t\t\t\t/* Renormalize if possible */\n\t\t\t\twhile( (mHigh < HALF) || (mLow >= HALF) )\n\t\t\t\t{\n\t\t\t\t\tif( mHigh < HALF )\n\t\t\t\t\t{\n\t\t\t\t\t\tbitBuf.writeBit((byte) 0);\n\t\t\t\t\t\tmLow = mLow * 2;\n\t\t\t\t\t\tmHigh = mHigh * 2 + 1;\n\t\t\t\t\t\t\n\t\t\t\t\t\t/* Perform e3 mappings */\n\t\t\t\t\t\tfor(; mScale > 0; mScale-- )\n\t\t\t\t\t\t\tbitBuf.writeBit((byte) 1);\n\t\t\t\t\t}\n\t\t\t\t\telse if( mLow >= HALF )\n\t\t\t\t\t{\n\t\t\t\t\t\tbitBuf.writeBit((byte) 1);\n\t\t\t\t\t\tmLow = ( mLow - HALF ) * 2;\n\t\t\t\t\t\tmHigh = ( mHigh - HALF ) * 2 + 1;\n\t\t\t\t\t\t\n\t\t\t\t\t\t/* Perform e3 mappings */\n\t\t\t\t\t\tfor(; mScale > 0; mScale-- )\n\t\t\t\t\t\t\tbitBuf.writeBit((byte) 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\twhile((FIRST_QUARTER <= mLow) && (mHigh < THIRD_QUARTER)) {\n\t\t\t\t\tmScale++;\n\t\t\t\t\tmLow = ( mLow - FIRST_QUARTER ) * 2;\n\t\t\t\t\tmHigh = ( mHigh - FIRST_QUARTER ) * 2 + 1;\n\t\t\t\t}\t\t\n\t\t\t\t\n\t\t\t\t/* 3. Update model */\n\t\t\t\tfreq[current]+=1;\n\t\t\t\ttotal+=1;\n\t\t\t\t\n\t\t\t}\n\t\t\t/* Finish encoding */\n\t\t\tif( mLow < FIRST_QUARTER ) {\n\t\t\t\t/* Case: mLow < FirstQuarter < Half <= mHigh */\n\t\t\t\tbitBuf.writeBit((byte) 0);\n\t\t\t\t/* Perform e3-scaling */\n\t\t\t\tfor( int i=0; i<mScale+1; i++ ) \n\t\t\t\t\tbitBuf.writeBit((byte) 1);\n\t\t\t} else {\n\t\t\t\t/* Case: mLow < Half < ThirdQuarter <= mHigh */\n\t\t\t\tbitBuf.writeBit((byte) 1 );\n\t\t\t}\n\t\t\tbitBuf.flush();\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\treturn null;\n\t\t}\n\t\treturn bitBuf.toByteArray();\n\t}\n\t\n\tpublic static byte[] decompress(byte[] in) {\n\t\t\n\t\tclass BitInputBuffer {\n\t\t\tbyte[] source;\n\t\t\tint bytep = 0, bitp = 0;\n\t\t\tbyte currentByte = 0;\n\t\t\tBitInputBuffer(byte [] source) {\n\t\t\t\tthis.source = source;\n\t\t\t\tcurrentByte = source[0];// & 0xff;\n\t\t\t}\n\t\t\tint readBit() {\n\t\t\t\tint result = (currentByte >> 7) & 1;\n\t\t\t\tcurrentByte = (byte) (currentByte << 1); \n\t\t\t\tif (bitp++==7) {\n\t\t\t\t\tbytep++;\n\t\t\t\t\tif (bytep > source.length - 1) {\n\t\t\t\t\t\tcurrentByte = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tcurrentByte = source[bytep];\n\t\t\t\t\t\tbitp = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\t\n\t\tByteArrayOutputStream buf = new ByteArrayOutputStream();\n\t\t/* Initialise frequency table */\n\t\t\n\t\tint[] freq = new int[257];\n\t\tfor (int i=0; i<257; i++) freq[i] = 1;\n\t\tint total = 257;\n\t\tint current = 0;\n\t\tint value;\n\t\tint low = 0, high = HIGH;\n\t\tint mLow = low, mHigh = high, mStep = 0, mScale = 0, mBuffer = 0;\n\t\tBitInputBuffer inbuf = new BitInputBuffer(in);\n\t\t/*\tFill buffer with bits from the input stream */\n\n\t\tfor( int i=0; i<INITIAL_READ; i++ ) {\n\t\t\tmBuffer = 2 * mBuffer;\n\t\t\tmBuffer += inbuf.readBit();\n\t\t}\n\t\t\t\n\t\twhile(true) {\n\t\t\t/* 1. Retrieve current byte */\n\t\t\tmStep = ( mHigh - mLow + 1 ) / total;\n\t\t\tvalue = ( mBuffer - mLow ) / mStep;\n\t\t\tlow = 0;\n\t\t\tfor (current=0; current<256 && low + freq[current] <= value; current++)\n\t\t\t\tlow += freq[current];\n\t\t\t\n\t\t\tif (current==256) break;\n\t\t\t\n\t\t\tbuf.write(current);\n\t\t\thigh = low + freq[current];\n\t\t\t\n\t\t\t/* 2. Update the decoder */\n\t\t\tmHigh = mLow + mStep * high - 1; // interval open at the top => -1\n\t\t\t\n\t\t\t/* Update lower bound */\n\t\t\tmLow = mLow + mStep * low;\n\t\t\t\n\t\t\t/* e1/e2 mapping */\n\t\t\twhile( ( mHigh < HALF ) || ( mLow >= HALF ) )\n\t\t\t{\n\t\t\t\tif( mHigh < HALF )\n\t\t\t\t{\n\t\t\t\t\tmLow = mLow * 2;\n\t\t\t\t\tmHigh = ((mHigh * 2) + 1);\n\t\t\t\t\tmBuffer = (2 * mBuffer);\n\t\t\t\t}\n\t\t\t\telse if( mLow >= HALF )\n\t\t\t\t{\n\t\t\t\t\tmLow = 2 * ( mLow - HALF );\n\t\t\t\t\tmHigh = 2 * ( mHigh - HALF ) + 1;\n\t\t\t\t\tmBuffer = 2 * ( mBuffer - HALF );\n\t\t\t\t}\n\t\n\t\t\t\tmBuffer += inbuf.readBit();\n\t\t\t\tmScale = 0;\n\t\t\t}\n\t\t\t\n\t\t\t/* e3 mapping */\n\t\t\twhile( ( FIRST_QUARTER <= mLow ) && ( mHigh < THIRD_QUARTER ) )\n\t\t\t{\n\t\t\t\tmScale++;\n\t\t\t\tmLow = 2 * ( mLow - FIRST_QUARTER );\n\t\t\t\tmHigh = 2 * ( mHigh - FIRST_QUARTER ) + 1;\n\t\t\t\tmBuffer = 2 * ( mBuffer - FIRST_QUARTER ) ;\n\t\t\t\tmBuffer += inbuf.readBit();\n\t\t\t}\n\t\t\t\n\t\t\t/* 3. Update frequency table */\n\t\t\tfreq[current]+=1;\n\t\t\ttotal+=1;\n\t\t}\n\t\t\n\t\treturn buf.toByteArray();\n\t}\n}", "public class ImageUtils {\n\n public static double[][] imageRasterToDoubleArray(\n \t\tfinal BufferedImage source) {\n \n \tWritableRaster sourceRaster = source.getRaster();\n \n \tint width = sourceRaster.getWidth();\n \tint height = sourceRaster.getHeight();\n \tdouble[][] result = new double[height][width];\n \n \tfor (int y = 0; y < height; y++) {\n \t double[] row = result[y]; \n \t for (int x = 0; x < width; x++) {\n \t\t\trow[x] = sourceRaster.getSample(x, height-1-y, 0);\n \t\t}\n \t}\n \treturn result;\n }\n\n public static void doubleArrayToImageRaster(\n \t\tfinal BufferedImage destination, double[][] source) {\n \n \tWritableRaster destinationRaster = destination.getRaster();\n \tint height = source.length;\n \tfor (int x = 0; x < source[0].length; x++) {\n \t\tfor (int y = 0; y < height; y++) {\n \t\t\tdouble value = source[y][x]; \n \t\t\tif (value < 0) { value = 0; } \n \t\t\tif (value > 255) { value = 255; }\n \t\t\tdestinationRaster.setSample(x, height-1-y, 0, value);\n \t\t}\n \t}\n }\n\n}", "public class H2O {\n\n public final static double M1A = 1 - sqrt(2 / sqrt(3));\n public final static double M2B = sqrt(sqrt(3) / 2) - 1;\n public final static double M3C = sqrt(2 / sqrt(3)) - 1 - 1 / sqrt(3);\n\n /**\n * @author Aleksejs Truhans\n */\n public static enum Direction {\n O2H, H2O, TEST_O2H, TEST_H2O;\n }\n\n /**\n * Use it to convert from orthogonal to hexagonal lattice.\n * o2h doesn't change the passed raster.\n **/\n public static DoubleLattice o2h(double[][] raster) {\n H2ORunner h2o = new H2ORunner(SincRepeater.getFactory());\n h2o.setData(raster, Direction.O2H);\n return h2o.o2hBody();\n }\n\n /**\n * Use it to convert from hexagonal to orthogonal lattice.\n * o2h doesn't change the passed raster.\n **/\n public static DoubleLattice h2o(DoubleLattice source) {\n H2ORunner h2o = new H2ORunner(SincRepeater.getFactory());\n h2o.setData(source, Direction.H2O);\n return h2o.h2oBody();\n }\n\n /**\n * @author Aleksejs Truhans\n */\n public static class H2ORunner {\n\n private final Factory interpolatingArrayFactory;\n private double[][] data;\n private int minx;\n private int miny;\n private int maxx;\n private int maxy;\n private int ox;\n private int oy;\n private Direction direction;\n\n public H2ORunner(Factory interpolatingArrayFactory) {\n this.interpolatingArrayFactory = interpolatingArrayFactory;\n }\n\n public void setData(DoubleLattice source, Direction direction) {\n setData(source.getData(), direction);\n ox += source.ox;\n oy += source.oy;\n }\n\n public void setData(double[][] source, Direction adirection) {\n int w = source[0].length;\n int h = source.length;\n // Will use this workaround buffer until I find\n // better way to predict image expansion due to shearings\n int bufferZone = (h + w) / 10;\n int xd = (int) (-(M3C + M2B) * h + 1) + bufferZone;\n int ydup = (int) (-M2B * (h + w - 1) / sqrt(2) + 1) + bufferZone;\n int yddown = (int) (-M1A * w + 1) + bufferZone;\n\n if (adirection == Direction.TEST_O2H || adirection == Direction.TEST_H2O) {\n xd = w / 2 + 2;\n ydup = h / 4 + 2;\n yddown = h / 4 + 2;\n direction = (adirection == Direction.TEST_O2H) ? Direction.O2H : Direction.H2O;\n } else {\n direction = adirection;\n }\n\n int nw = w + xd;\n int nh = h + ydup + yddown;\n\n data = new double[nh][nw];\n\n ox = direction == Direction.O2H ? xd : 0;\n oy = direction == Direction.O2H ? yddown : ydup;\n minx = ox;\n miny = oy;\n maxx = minx + w - 1;\n maxy = miny + h - 1;\n\n for (int y = 0; y < nh; y++) {\n for (int x = 0; x < nw; x++) {\n if (y >= miny && x >= minx && y <= maxy && x <= maxx) {\n data[y][x] = source[y - oy][x - ox];\n } else {\n data[y][x] = Double.NaN;\n }\n\n }\n }\n }\n\n private DoubleLattice o2hBody() {\n shearRightM3(-H2O.M3C);\n shearDownRightM2(-H2O.M2B);\n shearUpM1(-H2O.M1A);\n return getResult();\n }\n\n private DoubleLattice h2oBody() {\n shearUpM1(H2O.M1A);\n shearDownRightM2(H2O.M2B);\n shearRightM3(H2O.M3C);\n return getResult();\n }\n\n public void shearRightM3(double shift) {\n for (int y = miny; y <= maxy; y++) {\n if (y - oy == 0)\n continue; // shift by 0 means no shift\n\n double[] currentRow = data[y];\n\n int x0 = minx;\n while (Double.isNaN(currentRow[x0]))\n x0++;\n\n int x1 = maxx;\n while (Double.isNaN(currentRow[x1]) && x1 >= x0)\n x1--;\n\n if (x1 < x0)\n continue; // Nothing to shift\n\n double[] oldRow = new double[x1 - x0 + 1];\n for (int x = x0; x <= x1; x++) {\n oldRow[x - x0] = currentRow[x];\n }\n InterpolatingArray sia = interpolatingArrayFactory.getInstance(oldRow);\n\n double rowShift = shift * (y - oy);\n int shiftInArray = (int) rowShift;\n rowShift -= shiftInArray;\n if (minx > (x0 - shiftInArray))\n minx = x0 - shiftInArray;\n if (maxx < (x1 - shiftInArray))\n maxx = x1 - shiftInArray;\n if (minx < 0 || maxx >= data[0].length) {\n throw new IllegalArgumentException(\"Shearing \" + direction + \" by \" + shift\n + \" wouldn't fit into the data lattice\");\n }\n\n for (int x = 0; x < oldRow.length; x++) {\n currentRow[x + x0 - shiftInArray] = sia.get(rowShift + x);\n }\n\n for (int x = 0; x < shiftInArray; x++) {\n currentRow[x1 - x] = Double.NaN;\n }\n\n for (int x = shiftInArray + 1; x <= 0; x++) {\n currentRow[x0 - x] = Double.NaN;\n }\n }\n\n squeezeMinMax();\n }\n\n public DoubleLattice getResult() {\n int w = maxx - minx + 1;\n int h = maxy - miny + 1;\n double[][] result = new double[h][w];\n for (int y = miny; y <= maxy; y++) {\n for (int x = minx; x <= maxx; x++) {\n result[y - miny][x - minx] = data[y][x];\n }\n }\n return new DoubleLattice(result, ox - minx, oy - miny);\n }\n\n public double[][] getRawData() {\n return data;\n }\n\n public void shearDownRightM2(double shift) {\n final int height = maxy - miny + 1;\n final int width = maxx - minx + 1;\n int ODiagonalNumber = ox - minx + oy - miny;\n int newmaxx = maxx;\n int newmaxy = maxy;\n int newminx = minx;\n int newminy = miny;\n\n for (int i = 0; i < (height + width - 1); i++) {\n int diagonalCoordinate = i - ODiagonalNumber;\n if (diagonalCoordinate == 0)\n continue; // shift by 0 means no shift\n\n DiagonalParameters dp = DiagonalParameters.getDiagonalParameters(width, height, i);\n\n int j0 = 0;\n while (j0 < dp.diagonalLength\n && Double.isNaN(data[dp.startY - j0 + miny][dp.startX + j0 + minx])) {\n j0++;\n }\n\n int j1 = dp.diagonalLength - 1;\n while (j1 >= j0 && Double.isNaN(data[dp.startY - j1 + miny][dp.startX + j1 + minx])) {\n j1--;\n }\n\n if (j1 < j0)\n continue; // Nothing to shift\n\n double[] oldDiagonal = new double[j1 - j0 + 1];\n\n for (int j = j0; j <= j1; j++) {\n oldDiagonal[j - j0] = data[dp.startY - j + miny][dp.startX + j + minx];\n }\n\n InterpolatingArray sia = interpolatingArrayFactory.getInstance(oldDiagonal);\n\n double diagonalShift = shift * diagonalCoordinate;\n int shiftInArray = (int) diagonalShift;\n diagonalShift -= shiftInArray;\n int j0new = j0 - shiftInArray;\n int j1new = j1 - shiftInArray;\n\n if (newmaxy < (dp.startY - j0new + miny))\n newmaxy = dp.startY - j0new + miny;\n if (newminy > (dp.startY - j1new + miny))\n newminy = dp.startY - j1new + miny;\n\n if (newminx > (dp.startX + j0new + minx))\n newminx = dp.startX + j0new + minx;\n if (newmaxx < (dp.startX + j1new + minx))\n newmaxx = dp.startX + j1new + minx;\n\n if (newminy < 0 || newmaxy >= data.length || newminx < 0\n || newmaxx >= data[0].length) {\n throw new IllegalArgumentException(\"Shearing \" + direction + \" by \" + shift\n + \" wouldn't fit into the data lattice\");\n }\n\n for (int j = 0; j < oldDiagonal.length; j++) {\n data[dp.startY - (j + j0 - shiftInArray) + miny][dp.startX\n + (j + j0 - shiftInArray) + minx] = sia.get(diagonalShift + j);\n }\n\n for (int j = 0; j < shiftInArray; j++) {\n data[dp.startY - (j1 - j) + miny][dp.startX + (j1 - j) + minx] = Double.NaN;\n }\n\n for (int j = shiftInArray + 1; j <= 0; j++) {\n data[dp.startY - (j0 - j) + miny][dp.startX + (j0 - j) + minx] = Double.NaN;\n }\n }\n\n maxx = newmaxx;\n maxy = newmaxy;\n miny = newminy;\n minx = newminx;\n\n squeezeMinMax();\n }\n\n private void squeezeMinMax() {\n minx = firstNonNaNHorizontal(minx, +1);\n maxx = firstNonNaNHorizontal(maxx, -1);\n miny = firstNonNaNVertical(miny, +1);\n maxy = firstNonNaNVertical(maxy, -1);\n }\n\n private int firstNonNaNVertical(int y0, int direction) {\n int y = y0;\n for (; y >= miny && y <= maxy; y += direction) {\n for (int x = minx; x <= maxx; x++) {\n if (!Double.isNaN(data[y][x]))\n return y;\n }\n }\n return y;\n }\n\n private int firstNonNaNHorizontal(int x0, int direction) {\n int x = x0;\n for (; x >= minx && x <= maxx; x += direction) {\n for (int y = miny; y <= maxy; y++) {\n if (!Double.isNaN(data[y][x]))\n return x;\n }\n }\n return x;\n }\n\n public void shearUpM1(double shift) {\n for (int x = minx; x <= maxx; x++) {\n if (x - ox == 0)\n continue; // shift by 0 means no shift\n\n int y0 = miny;\n while (Double.isNaN(data[y0][x]))\n y0++;\n\n int y1 = maxy;\n while (Double.isNaN(data[y1][x]) && y1 >= y0)\n y1--;\n\n if (y1 < y0)\n continue; // Nothing to shift\n\n double[] oldColumn = new double[y1 - y0 + 1];\n for (int y = y0; y <= y1; y++) {\n oldColumn[y - y0] = data[y][x];\n }\n InterpolatingArray sia = interpolatingArrayFactory.getInstance(oldColumn);\n\n double columnShift = shift * (x - ox);\n int shiftInArray = (int) columnShift;\n columnShift -= shiftInArray;\n if (miny > (y0 - shiftInArray))\n miny = y0 - shiftInArray;\n if (maxy < (y1 - shiftInArray))\n maxy = y1 - shiftInArray;\n if (miny < 0 || maxy >= data.length) {\n throw new IllegalArgumentException(\"Shearing \" + direction + \" by \" + shift\n + \" wouldn't fit into the data lattice\");\n }\n\n for (int y = 0; y < oldColumn.length; y++) {\n data[y + y0 - shiftInArray][x] = sia.get(columnShift + y);\n }\n\n for (int y = 0; y < shiftInArray; y++) {\n data[y1 - y][x] = Double.NaN;\n }\n\n for (int y = shiftInArray + 1; y <= 0; y++) {\n data[y0 - y][x] = Double.NaN;\n }\n }\n\n squeezeMinMax();\n }\n }\n}", "public class HexByteRavelet extends LongLattice implements HexRavelet {\n\n private byte[][][] remainderBits; // remainderBits[n] are the bits that\n // dropped out when encoding level n\n\n public void setRemainderBits(byte[][][] remainderBits) {\n this.remainderBits = remainderBits;\n }\n\n public byte[][][] getRemainderBits() {\n return remainderBits;\n }\n\n public HexByteRavelet(LongLattice lattice) {\n super(lattice);\n remainderBits = new byte[getMaxLevel() + 1][data.length][data[0].length];\n }\n\n @Override\n public void encode() {\n int maxLength = Math.max(data[0].length, data.length);\n int level = 0;\n int halfStep = 1 << level;\n while (halfStep < maxLength) {\n encodeLevel(level);\n level++;\n halfStep = 1 << level;\n }\n }\n\n public final int getMaxLevel() {\n int length = Math.max(data[0].length, data.length);\n int level = 0;\n while (length > 0) {\n level++;\n length >>= 1;\n }\n return level - 1;\n }\n\n @Override\n public void encodeLevel(int level) {\n Stage stage = Stage.ENCODE;\n processCenters(level, stage);\n processBetween(level, Direction.ROW, stage);\n processBetween(level, Direction.COLUMN, stage);\n processBetween(level, Direction.DIAGONAL, stage);\n }\n\n @Override\n public void decode() {\n int maxLength = Math.max(data[0].length, data.length);\n\n int level = 0;\n int halfStep = 1 << level;\n while (halfStep < maxLength) {\n level++;\n halfStep = 1 << level;\n }\n\n level--;\n halfStep = 1 << level;\n while (halfStep > 0) {\n decodeLevel(level);\n level--;\n halfStep = 1 << level;\n }\n\n }\n\n @Override\n public void decodeLevel(int level) {\n Stage stage = Stage.DECODE;\n processBetween(level, Direction.ROW, stage);\n processBetween(level, Direction.COLUMN, stage);\n processBetween(level, Direction.DIAGONAL, stage);\n processCenters(level, stage);\n }\n\n private void processBetween(int level, Direction direction, Stage stage) {\n int step = 2 << level;\n int halfStep = step / 2;\n final int[] plusMinusOne = new int[] { -1, +1 };\n\n for (int y = direction.y0 * halfStep; y < data.length; y += step) {\n long row[] = data[y];\n for (int x = direction.x0 * halfStep; x < row.length; x += step) {\n if (row[x] == NAN)\n continue;\n\n long sum = 0;\n int count = 0;\n for (int delta : plusMinusOne) {\n long a = safeGetDataXY(x + delta * direction.xdelta * halfStep, y + delta\n * direction.ydelta * halfStep);\n if (a != NAN) {\n sum += a;\n count++;\n }\n }\n if (count > 0) {\n row[x] += stage.averageCoef * (sum / count);\n if (row[x] < 0)\n row[x] += 256;\n if (row[x] > 255)\n row[x] -= 256;\n }\n }\n }\n }\n\n private void processCenters(int level, Stage stage) {\n int step = 2 << level;\n for (int y = 0; y < data.length; y += step) {\n long row[] = data[y];\n for (int x = 0; x < row.length; x += step) {\n long d = row[x];\n if (d == NAN)\n continue;\n if (stage == Stage.ENCODE) {\n d -= stage.averageCoef * (sumPetalsXY(x, y, step / 2) / 2);\n row[x] = d / 4;\n remainderBits[level][y][x] = (byte) (d % 4);\n } else {\n row[x] = d * 4 + remainderBits[level][y][x] - stage.averageCoef\n * (sumPetalsXY(x, y, step / 2) / 2);\n }\n\n }\n }\n }\n\n private long sumPetalsXY(int x, int y, int step) {\n long sumPetals = 0;\n int count = 0;\n for (int i = 0; i < HEXAGON_TRAVERSAL_XY.length; i++) {\n long d = safeGetDataXY(x + HEXAGON_TRAVERSAL_XY[i][0] * step, y\n + HEXAGON_TRAVERSAL_XY[i][1] * step);\n if (d != NAN) {\n sumPetals += d;\n count++;\n }\n }\n if (count > 0 && count < 6) {\n sumPetals = (sumPetals * 6) / count;\n }\n return sumPetals;\n }\n\n private long safeGetDataXY(int x, int y) {\n return (x >= 0 && x < data[0].length && y >= 0 && y < data.length) ? data[y][x] : NAN;\n }\n\n public int getPointLevelXY(int x, int y) {\n int level = 0;\n if (x == 0 && y == 0)\n return getMaxLevel();\n while ((x & 1) == 0 && (y & 1) == 0) {\n level++;\n x >>= 1;\n y >>= 1;\n }\n return level;\n }\n\n public byte[] getReminderBitStream() {\n ByteArrayOutputStream byteOut = new ByteArrayOutputStream();\n BitOutputStream bitOut = new BitOutputStream(byteOut);\n int step = 2;\n for (int y = 0; y < data.length; y += step) {\n long row[] = data[y];\n for (int x = 0; x < row.length; x += step) {\n int level = getPointLevelXY(x, y);\n for (int i = 1; i <= level; i++) {\n bitOut.write(2, remainderBits[i - 1][y][x]);\n }\n }\n }\n bitOut.flush();\n return byteOut.toByteArray();\n }\n\n public void loadRemainderBitStream(byte[] source) {\n try {\n ByteArrayInputStream byteIn = new ByteArrayInputStream(source);\n BitInputStream bitIn = new BitInputStream(byteIn);\n int step = 2;\n for (int y = 0; y < data.length; y += step) {\n long row[] = data[y];\n for (int x = 0; x < row.length; x += step) {\n int level = getPointLevelXY(x, y);\n for (int i = 1; i <= level; i++) {\n remainderBits[i - 1][y][x] = (byte) bitIn.read(2);\n }\n }\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public long[][] getHigherLevelLattice(int level) {\n int step = 1 << level;\n int sizey = (data.length - 1) / step + 1;\n int sizex = (data[0].length - 1) / step + 1;\n long[][] result = new long[sizey][sizex];\n for (int y = 0, resulty = 0; y < data.length; y += step, resulty++) {\n long row[] = data[y];\n for (int x = 0, resultx = 0; x < row.length; x += step, resultx++) {\n result[resulty][resultx] = row[x];\n }\n }\n return result;\n }\n}" ]
import util.ImageUtils; import filter.H2O; import filter.HexByteRavelet; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.util.LinkedList; import java.util.List; import lattice.DoubleLattice; import lattice.LongLattice; import lattice.LongLattice.Run; import rangecoder.Compressor;
package pipeline; /* * Copyright (C) 2012 Aleksejs Truhans * * 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/>. */ /** * Decodes byte stream into a lattice. @see Encoder for byte stream description. * * @see DecoderTest.testEncodeDecodeLena100() for usage example * * **/ public class Decoder { /** * Decodes byte stream into a hexagonal lattice. @see Encoder for byte * stream description. **/ public static LongLattice decodeToHexagonalLattice(byte[] source) { DecodeRunner decoder = new DecodeRunner(source); return decoder.decode(); } /** * Decodes byte stream into an orthogonal array. @see Encoder for byte * stream description. **/ public static double[][] decodeToImageInArray(byte[] encoded) { LongLattice lattice = decodeToHexagonalLattice(encoded); return hexagonalLatticeToImageInArray(lattice); } public static BufferedImage hexagonalLatticeToBufferedImage( LongLattice source) { double[][] imageInArray = hexagonalLatticeToImageInArray(source); BufferedImage image = new BufferedImage(imageInArray[0].length, imageInArray.length, BufferedImage.TYPE_BYTE_GRAY); ImageUtils.doubleArrayToImageRaster(image, imageInArray); return image; } public static double[][] hexagonalLatticeToImageInArray(LongLattice source) { DoubleLattice doubleLattice = H2O.h2o(source.getDequantizedLattice()); return doubleLattice.getData(); } /** * @author HP */ public static class DecodeRunner { /** * @uml.property name="lattice" * @uml.associationEnd */ private LongLattice lattice; private final ByteArrayInputStream byteIn; private final DataInputStream dataIn; /** * @uml.property name="ravelet" * @uml.associationEnd */
private HexByteRavelet ravelet;
6
RedMadRobot/Chronos
chronos/src/main/java/com/redmadrobot/chronos/gui/fragment/dialog/ChronosDialogFragment.java
[ "public final class ChronosConnector {\n\n private final static String KEY_CHRONOS_LISTENER_ID = \"chronos_listener_id\";\n\n private ChronosListener mChronosListener;\n\n private Object mGUIClient;\n\n /**\n * GUI client should call this method in its own onCreate() method.\n *\n * @param client a client that holds the helper\n * @param savedInstanceState parameter from the corresponding client method\n */\n public final void onCreate(@NonNull final Object client,\n @Nullable final Bundle savedInstanceState) {\n mGUIClient = client;\n if (savedInstanceState != null) {\n mChronosListener = ChronosListenerManager.getInstance()\n .getListener(savedInstanceState.getInt(KEY_CHRONOS_LISTENER_ID));\n } else {\n mChronosListener = ChronosListenerManager.getInstance()\n .createListener();\n }\n }\n\n /**\n * GUI client should call this method in its own onResume() method.\n */\n public final void onResume() {\n mChronosListener.onResume(mGUIClient);\n }\n\n /**\n * GUI client should call this method in its own onSaveInstanceState() method.\n *\n * @param outState parameter from the corresponding client method\n */\n public final void onSaveInstanceState(@Nullable final Bundle outState) {\n if (outState != null) {\n outState.putInt(KEY_CHRONOS_LISTENER_ID, mChronosListener.getId());\n }\n }\n\n /**\n * GUI client should call this method in its own onPause() method.\n */\n public final void onPause() {\n mChronosListener.onPause();\n }\n\n /**\n * Runs an operation in a background thread. Only one operation with the given tag may run in a\n * single moment of time. The result will be delivered to {@link Chronos#OWN_CALLBACK_METHOD_NAME}\n * method. If {@code broadcast} is {@code true} all other Chronos clients will receive the\n * result in {@link Chronos#BROADCAST_CALLBACK_METHOD_NAME} method. Both method must have only\n * one parameter of type {@link ChronosOperation#getResultClass()} to receive a result.\n *\n * @param operation an operation to be run in background\n * @param tag value which prohibits running new operations with the same tag while there\n * is a running one\n * @param broadcast {@code true} if any other Chronos clients should be able to receive a\n * result; {@code false} otherwise\n * @return a unique launch id, may be the same with the previous run with the same tag, if the\n * operation is still running\n * @see #runOperation(ChronosOperation, boolean)\n * @see #cancelOperation(int, boolean)\n * @see #cancelOperation(String, boolean)\n */\n public final int runOperation(@NonNull final ChronosOperation operation, @NonNull final String tag,\n final boolean broadcast) {\n return mChronosListener.invoke(operation, tag, broadcast);\n }\n\n /**\n * Runs an operation in a background thread. The result will be delivered to {@link\n * Chronos#OWN_CALLBACK_METHOD_NAME} method. If {@code broadcast} is {@code true} all other\n * Chronos clients will receive the result in {@link Chronos#BROADCAST_CALLBACK_METHOD_NAME}\n * method. Both method must have only one parameter of type {@link ChronosOperation#getResultClass()}\n * to receive a result.\n *\n * @param operation an operation to be run in background\n * @param broadcast {@code true} if any other Chronos clients should be able to receive a\n * result; {@code false} otherwise\n * @return a unique launch id\n * @see #runOperation(ChronosOperation, String, boolean)\n * @see #cancelOperation(int, boolean)\n */\n public final int runOperation(@NonNull final ChronosOperation operation, final boolean broadcast) {\n return mChronosListener.invoke(operation, broadcast);\n }\n\n /**\n * Cancels a running operation. It is not guaranteed that execution would be interrupted\n * immediately, however, no result would be delivered to the GUI client, or any other Chronos\n * clients, if it was a broadcast run.\n *\n * @param id id of launch, that needs to be cancelled\n * @param mayInterrupt {@code true} if threads executing operations task should be interrupted;\n * otherwise, in-progress tasks are allowed to complete\n * @return {@code false} if the task could not be cancelled, typically because it has already\n * completed normally; {@code true} otherwise\n * @see #runOperation(ChronosOperation, String, boolean)\n * @see #runOperation(ChronosOperation, boolean)\n * @see #cancelOperation(String, boolean)\n */\n public final boolean cancelOperation(final int id, final boolean mayInterrupt) {\n return mChronosListener.cancel(id, mayInterrupt);\n }\n\n /**\n * Cancels a running operation. It is not guaranteed that execution would be interrupted\n * immediately, however, no result would be delivered to the GUI client, or any other Chronos\n * clients, if it was a broadcast run.\n *\n * @param tag a tag with the operation was launched\n * @param mayInterrupt {@code true} if threads executing operations task should be interrupted;\n * otherwise, in-progress tasks are allowed to complete\n * @return {@code false} if the task could not be cancelled, typically because it has already\n * completed normally or there is no running operation with a given tag; {@code true} otherwise\n * @see #runOperation(ChronosOperation, String, boolean)\n * @see #runOperation(ChronosOperation, boolean)\n * @see #cancelOperation(int, boolean)\n */\n public final boolean cancelOperation(@NonNull final String tag, final boolean mayInterrupt) {\n return mChronosListener.cancel(tag, mayInterrupt);\n }\n\n /**\n * Checks if an operation with given launch id is running.\n *\n * @param id an id of the operation launch\n * @return {@code true} if the operation is running, {@code false} otherwise\n */\n public final boolean isOperationRunning(final int id) {\n return mChronosListener.isRunning(id);\n }\n\n /**\n * Checks if an operation with given launch tag is running.\n *\n * @param tag a pre-cache key of the operation launch\n * @return {@code true} if the operation is running, {@code false} if it is not running, or\n * there was no operation launch with the tag at all\n */\n public final boolean isOperationRunning(@NonNull final String tag) {\n return mChronosListener.isRunning(tag);\n }\n}", "public abstract class ChronosOperation<Output> {\n\n\n private final AtomicBoolean mIsCancelled = new AtomicBoolean(false);\n\n /**\n * The method for performing business-logic related work. Can contain time-consuming calls, but\n * should not perform any interaction with the UI, as it will be launched not in the Main\n * Thread.<br>\n * <p/>\n * All exceptions thrown in this method will be encapsulated in OperationResult object, so it\n * will not cause app crash.\n *\n * @return the result of the operation.\n */\n @Nullable\n public abstract Output run();\n\n /**\n * This method returns a subclass of OperationResult class, related to the particular Operation\n * subclass, so that Chronos clients can distinguish results from different operations.\n *\n * @return OperationResult subclass, that will be created after the operation is complete.\n */\n @NonNull\n @Contract(pure = true)\n public abstract Class<? extends ChronosOperationResult<Output>> getResultClass();\n\n /**\n * Checks if the operation was cancelled.\n *\n * @return {@code true} if the operation was cancelled, {@code false} otherwise\n * @see ChronosListener#cancel(int, boolean)\n * @see ChronosListener#cancel(String, boolean)\n * @see Chronos#cancelAll(boolean)\n */\n @Contract(pure = true)\n public final boolean isCancelled() {\n return mIsCancelled.get();\n }\n\n /**\n * Marks operation as cancelled.\n */\n final void cancel() {\n mIsCancelled.set(true);\n }\n}", "public interface ChronosConnectorWrapper {\n\n /**\n * Runs an operation in a background thread. Only one operation with the given tag may run in a\n * single moment of time. The result will be delivered to {@link Chronos#OWN_CALLBACK_METHOD_NAME}\n * method. This method must have only one parameter of type {@link ChronosOperation#getResultClass()}\n * to receive a result.\n *\n * @param operation an operation to be run in background\n * @param tag value which prohibits running new operations with the same tag while there\n * is a running one\n * @return a unique launch id, may be the same with the previous run with the same tag, if the\n * operation is still running\n * @see #runOperation(ChronosOperation)\n * @see #runOperationBroadcast(ChronosOperation, String)\n * @see #cancelOperation(int)\n * @see #cancelOperation(String)\n */\n int runOperation(@NonNull final ChronosOperation operation,\n @NonNull final String tag);\n\n /**\n * Runs an operation in a background thread. The result will be delivered to {@link\n * Chronos#OWN_CALLBACK_METHOD_NAME} method. This method must have only one parameter of type\n * {@link ChronosOperation#getResultClass()} to receive a result.\n *\n * @param operation an operation to be run in background\n * @return a unique launch id\n * @see #runOperation(ChronosOperation, String)\n * @see #runOperationBroadcast(ChronosOperation)\n * @see #cancelOperation(int)\n */\n int runOperation(@NonNull final ChronosOperation operation);\n\n /**\n * Runs an operation in a background thread, and broadcast it result when finished. Only one\n * operation with the given tag may run in a single moment of time. The result will be delivered\n * to {@link Chronos#OWN_CALLBACK_METHOD_NAME} method. All other Chronos clients will receive\n * the result in {@link Chronos#BROADCAST_CALLBACK_METHOD_NAME} method. Both method must have\n * only one parameter of type {@link ChronosOperation#getResultClass()} to receive a result.\n *\n * @param operation an operation to be run in background\n * @param tag value which prohibits running new operations with the same tag while there\n * is a running one\n * @return a unique launch id, may be the same with the previous run with the same tag, if the\n * operation is still running\n * @see #runOperationBroadcast(ChronosOperation)\n * @see #runOperation(ChronosOperation, String)\n * @see #cancelOperation(int)\n * @see #cancelOperation(String)\n */\n int runOperationBroadcast(@NonNull final ChronosOperation operation,\n @NonNull final String tag);\n\n /**\n * Runs an operation in a background thread, and broadcast it result when finished. The result\n * will be delivered to {@link Chronos#OWN_CALLBACK_METHOD_NAME} method. All other Chronos\n * clients will receive the result in {@link Chronos#BROADCAST_CALLBACK_METHOD_NAME} method.\n * Both method must have only one parameter of type {@link ChronosOperation#getResultClass()} to\n * receive a result.\n *\n * @param operation an operation to be run in background\n * @return a unique launch id\n * @see #runOperation(ChronosOperation)\n * @see #runOperationBroadcast(ChronosOperation, String)\n * @see #cancelOperation(int)\n */\n int runOperationBroadcast(@NonNull final ChronosOperation operation);\n\n /**\n * Cancels a running operation by its launch id. It is not guaranteed that execution would be\n * interrupted immediately, however, no result would be delivered to the activity, or any other\n * Chronos clients, if it was a broadcast run.\n *\n * @param id id of launch, that needs to be cancelled\n * @return {@code false} if the task could not be cancelled, typically because it has already\n * completed normally; {@code true} otherwise\n * @see #cancelOperation(String)\n * @see #runOperation(ChronosOperation)\n * @see #runOperation(ChronosOperation, String)\n * @see #runOperationBroadcast(ChronosOperation)\n * @see #runOperationBroadcast(ChronosOperation, String)\n */\n boolean cancelOperation(final int id);\n\n /**\n * Cancels a running operation by its tag. It is not guaranteed that execution would be\n * interrupted immediately, however, no result would be delivered to the activity, or any other\n * Chronos clients, if it was a broadcast run.\n *\n * @param tag a tag with the operation was launched\n * @return {@code false} if the task could not be cancelled, typically because it has already\n * completed normally or there is no running operation with a given tag; {@code true} otherwise\n * @see #cancelOperation(int)\n * @see #runOperation(ChronosOperation)\n * @see #runOperation(ChronosOperation, String)\n * @see #runOperationBroadcast(ChronosOperation)\n * @see #runOperationBroadcast(ChronosOperation, String)\n */\n boolean cancelOperation(@NonNull final String tag);\n\n /**\n * Checks if an operation with given launch id is running.\n *\n * @param id an id of the operation launch\n * @return {@code true} if the operation is running, {@code false} otherwise\n */\n @Contract(pure = true)\n boolean isOperationRunning(final int id);\n\n /**\n * Checks if an operation with given launch tag is running.\n *\n * @param tag a pre-cache key of the operation launch\n * @return {@code true} if the operation is running, {@code false} if it is not running, or\n * there was no operation launch with the tag at all\n */\n @Contract(pure = true)\n boolean isOperationRunning(@NonNull final String tag);\n}", "@SuppressWarnings(\"unused\")\n@TargetApi(Build.VERSION_CODES.HONEYCOMB)\npublic abstract class ChronosFragment extends Fragment implements\n ChronosConnectorWrapper {\n\n private final ChronosConnector mConnector = new ChronosConnector();\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n mConnector.onCreate(this, savedInstanceState);\n }\n\n @Override\n public void onResume() {\n super.onResume();\n mConnector.onResume();\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n mConnector.onSaveInstanceState(outState);\n }\n\n @Override\n public void onPause() {\n mConnector.onPause();\n super.onPause();\n }\n\n @Override\n public final int runOperation(@NonNull final ChronosOperation operation,\n @NonNull final String tag) {\n return mConnector.runOperation(operation, tag, false);\n }\n\n @Override\n public final int runOperation(@NonNull final ChronosOperation operation) {\n return mConnector.runOperation(operation, false);\n }\n\n @Override\n public final int runOperationBroadcast(@NonNull final ChronosOperation operation,\n @NonNull final String tag) {\n return mConnector.runOperation(operation, tag, true);\n }\n\n @Override\n public final int runOperationBroadcast(@NonNull final ChronosOperation operation) {\n return mConnector.runOperation(operation, true);\n }\n\n @Override\n public final boolean cancelOperation(final int id) {\n return mConnector.cancelOperation(id, true);\n }\n\n @Override\n public final boolean cancelOperation(@NonNull final String tag) {\n return mConnector.cancelOperation(tag, true);\n }\n\n @Override\n @Contract(pure = true)\n public final boolean isOperationRunning(final int id) {\n return mConnector.isOperationRunning(id);\n }\n\n @Override\n @Contract(pure = true)\n public final boolean isOperationRunning(@NonNull final String tag) {\n return mConnector.isOperationRunning(tag);\n }\n}", "@SuppressWarnings(\"unused\")\npublic abstract class ChronosSupportFragment extends Fragment implements\n ChronosConnectorWrapper {\n\n private final ChronosConnector mConnector = new ChronosConnector();\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n mConnector.onCreate(this, savedInstanceState);\n }\n\n @Override\n public void onResume() {\n super.onResume();\n mConnector.onResume();\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n mConnector.onSaveInstanceState(outState);\n }\n\n @Override\n public void onPause() {\n mConnector.onPause();\n super.onPause();\n }\n\n @Override\n public final int runOperation(@NonNull final ChronosOperation operation,\n @NonNull final String tag) {\n return mConnector.runOperation(operation, tag, false);\n }\n\n @Override\n public final int runOperation(@NonNull final ChronosOperation operation) {\n return mConnector.runOperation(operation, false);\n }\n\n @Override\n public final int runOperationBroadcast(@NonNull final ChronosOperation operation,\n @NonNull final String tag) {\n return mConnector.runOperation(operation, tag, true);\n }\n\n @Override\n public final int runOperationBroadcast(@NonNull final ChronosOperation operation) {\n return mConnector.runOperation(operation, true);\n }\n\n @Override\n public final boolean cancelOperation(final int id) {\n return mConnector.cancelOperation(id, true);\n }\n\n @Override\n public final boolean cancelOperation(@NonNull final String tag) {\n return mConnector.cancelOperation(tag, true);\n }\n\n @Override\n @Contract(pure = true)\n public final boolean isOperationRunning(final int id) {\n return mConnector.isOperationRunning(id);\n }\n\n @Override\n @Contract(pure = true)\n public final boolean isOperationRunning(@NonNull final String tag) {\n return mConnector.isOperationRunning(tag);\n }\n}" ]
import com.redmadrobot.chronos.ChronosConnector; import com.redmadrobot.chronos.ChronosOperation; import com.redmadrobot.chronos.gui.ChronosConnectorWrapper; import com.redmadrobot.chronos.gui.fragment.ChronosFragment; import com.redmadrobot.chronos.gui.fragment.ChronosSupportFragment; import org.jetbrains.annotations.Contract; import android.annotation.TargetApi; import android.app.DialogFragment; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull;
package com.redmadrobot.chronos.gui.fragment.dialog; /** * A DialogFragment that is connected to Chronos. * * @author maximefimov * @see ChronosFragment * @see ChronosSupportDialogFragment * @see ChronosSupportFragment */ @SuppressWarnings("unused") @TargetApi(Build.VERSION_CODES.HONEYCOMB) public abstract class ChronosDialogFragment extends DialogFragment implements
ChronosConnectorWrapper {
2
MinecraftForge/ForgeGradle
src/userdev/java/net/minecraftforge/gradle/userdev/util/Deobfuscator.java
[ "public enum HashFunction {\n MD5(\"md5\", 32),\n SHA1(\"SHA-1\", 40),\n SHA256(\"SHA-256\", 64),\n SHA512(\"SHA-512\", 128);\n\n private final String algo;\n private final String pad;\n\n HashFunction(String algo, int length) {\n this.algo = algo;\n this.pad = String.format(Locale.ROOT, \"%0\" + length + \"d\", 0);\n }\n\n public String getExtension() {\n return this.name().toLowerCase(Locale.ROOT);\n }\n\n public MessageDigest get() {\n try {\n return MessageDigest.getInstance(algo);\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e); // Never happens\n }\n }\n\n public String hash(File file) throws IOException {\n return hash(file.toPath());\n }\n\n public String hash(Path file) throws IOException {\n return hash(Files.readAllBytes(file));\n }\n\n public String hash(Iterable<File> files) throws IOException {\n MessageDigest hash = get();\n\n for (File file : files) {\n if (!file.exists())\n continue;\n hash.update(Files.readAllBytes(file.toPath()));\n }\n return pad(new BigInteger(1, hash.digest()).toString(16));\n }\n\n public String hash(@Nullable String data) {\n return hash(data == null ? new byte[0] : data.getBytes(StandardCharsets.UTF_8));\n }\n\n public String hash(InputStream stream) throws IOException {\n return hash(IOUtils.toByteArray(stream));\n }\n\n public String hash(byte[] data) {\n return pad(new BigInteger(1, get().digest(data)).toString(16));\n }\n\n public String pad(String hash) {\n return (pad + hash).substring(hash.length());\n }\n}", "public class HashStore {\n private final boolean INVALIDATE_CACHE = System.getProperty(\"FG_INVALIDATE_CACHE\", \"false\").equals(\"true\");\n private final int RAND_CACHE = new Random().nextInt();\n\n private final String root;\n private final Map<String, String> oldHashes = new HashMap<>();\n private final Map<String, String> newHashes = new HashMap<>();\n private File target;\n\n public HashStore() {\n this.root = \"\";\n }\n public HashStore(Project project) {\n this.root = project.getRootDir().getAbsolutePath();\n }\n public HashStore(File root) {\n this.root = root.getAbsolutePath();\n }\n\n public boolean areSame(File... files) {\n for(File file : files) {\n if(!isSame(file)) return false;\n }\n return true;\n }\n\n public boolean areSame(Iterable<File> files) {\n for(File file : files) {\n if(!isSame(file)) return false;\n }\n return true;\n }\n\n public boolean isSame(File file) {\n try {\n String path = getPath(file);\n String hash = oldHashes.get(path);\n if (hash == null) {\n if (file.exists()) {\n newHashes.put(path, HashFunction.SHA1.hash(file));\n return false;\n }\n return true;\n }\n String fileHash = HashFunction.SHA1.hash(file);\n newHashes.put(path, fileHash);\n return fileHash.equals(hash);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public HashStore load(File file) throws IOException {\n this.target = file;\n oldHashes.clear();\n if(!file.exists()) return this;\n for (String line : FileUtils.readLines(file, StandardCharsets.UTF_8)) {\n String[] split = line.split(\"=\");\n oldHashes.put(split[0], split[1]);\n }\n return this;\n }\n\n public boolean exists() {\n return this.target != null && this.target.exists();\n }\n\n public HashStore bust(int version) {\n newHashes.put(\"CACHE_BUSTER\", Integer.toString(version));\n return this;\n }\n\n public HashStore add(String key, String data) {\n newHashes.put(key, HashFunction.SHA1.hash(data));\n return this;\n }\n\n public HashStore add(String key, byte[] data) {\n newHashes.put(key, HashFunction.SHA1.hash(data));\n return this;\n }\n\n public HashStore add(@Nullable String key, File file) {\n try {\n newHashes.put(key == null ? getPath(file) : key, HashFunction.SHA1.hash(file));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return this;\n }\n\n public HashStore add(File... files) {\n for (File file : files) {\n add(null, file);\n }\n return this;\n }\n public HashStore add(Iterable<File> files) {\n for (File file : files) {\n add(null, file);\n }\n return this;\n }\n public HashStore add(File file) {\n add(null, file);\n return this;\n }\n\n public boolean isSame() {\n if (INVALIDATE_CACHE)\n add(\"invalidate\", \"\" + RAND_CACHE);\n return oldHashes.equals(newHashes);\n }\n\n public void save() throws IOException {\n if (target == null) {\n throw new RuntimeException(\"HashStore.save() called without load(File) so we dont know where to save it! Use load(File) or save(File)\");\n }\n save(target);\n }\n public void save(File file) throws IOException {\n FileUtils.writeByteArrayToFile(file, newHashes.entrySet().stream().map(e -> e.getKey() + \"=\" + e.getValue()).collect(Collectors.joining(\"\\n\")).getBytes());\n }\n\n private String getPath(File file) {\n String path = file.getAbsolutePath();\n if (path.startsWith(root)) {\n return path.substring(root.length()).replace('\\\\', '/');\n } else {\n return path.replace('\\\\', '/');\n }\n }\n\n}", "public class MavenArtifactDownloader {\n /**\n * This tracks downloads that are <b>currently</b> active. As soon as a download has finished it will be removed\n * from this map.\n */\n private static final Map<DownloadKey, Future<File>> ACTIVE_DOWNLOADS = new HashMap<>();\n\n private static final Cache<String, File> CACHE = CacheBuilder.newBuilder()\n .expireAfterWrite(5, TimeUnit.MINUTES)\n .build();\n private static final Map<Project, Integer> COUNTER = new HashMap<>();\n\n private static final Map<String, String> VERSIONS = new HashMap<>();\n\n @Nullable\n public static File download(Project project, String artifact, boolean changing) {\n return _download(project, artifact, changing, true, true, true);\n }\n\n public static String getVersion(Project project, String artifact) {\n Artifact art = Artifact.from(artifact);\n if (!art.getVersion().endsWith(\"+\") && !art.isSnapshot())\n return art.getVersion();\n _download(project, artifact, true, false, true, true);\n return VERSIONS.get(artifact);\n }\n\n @Nullable\n public static File gradle(Project project, String artifact, boolean changing) {\n return _download(project, artifact, changing, false, true, true);\n }\n\n @Nullable\n public static File generate(Project project, String artifact, boolean changing) {\n return _download(project, artifact, changing, true, false, true);\n }\n\n @Nullable\n public static File manual(Project project, String artifact, boolean changing) {\n return _download(project, artifact, changing, false, false, true);\n }\n\n @Nullable\n private static File _download(Project project, String artifact, boolean changing, boolean generated, boolean gradle, boolean manual) {\n /*\n * This somewhat convoluted code is necessary to avoid race-conditions when two Gradle worker threads simultaneously\n * try to download the same artifact.\n * The first thread registers a future that other threads can wait on.\n * Once it finishes, the future will be removed and subsequent calls will use the CACHE instead.\n * We use all parameters of the function as the key here to prevent subtle bugs where the same artifact\n * is looked up simultaneously with different resolver-options, leading only to one attempt being made.\n */\n DownloadKey downloadKey = new DownloadKey(project, artifact, changing, generated, gradle, manual);\n CompletableFuture<File> future;\n synchronized (ACTIVE_DOWNLOADS) {\n Future<File> activeDownload = ACTIVE_DOWNLOADS.get(downloadKey);\n if (activeDownload != null) {\n // Some other thread is already working downloading this exact artifact, wait for it to finish\n try {\n project.getLogger().info(\"Waiting for download of {} on other thread\", artifact);\n return activeDownload.get();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n } catch (ExecutionException e) {\n if (e.getCause() instanceof RuntimeException) {\n throw (RuntimeException) e.getCause();\n } else {\n throw new RuntimeException(e.getCause());\n }\n }\n } else {\n project.getLogger().info(\"Downloading {}\", artifact);\n // We're the first thread to download the artifact, make sure concurrent downloads just wait for us\n future = new CompletableFuture<>();\n ACTIVE_DOWNLOADS.put(downloadKey, future);\n }\n }\n\n File ret = null;\n try {\n Artifact art = Artifact.from(artifact);\n\n ret = CACHE.getIfPresent(artifact);\n if (ret != null && !ret.exists()) {\n CACHE.invalidate(artifact);\n ret = null;\n }\n\n List<MavenArtifactRepository> mavens = new ArrayList<>();\n List<GradleRepositoryAdapter> fakes = new ArrayList<>();\n List<ArtifactRepository> others = new ArrayList<>();\n\n project.getRepositories().forEach( repo -> {\n if (repo instanceof MavenArtifactRepository)\n mavens.add((MavenArtifactRepository)repo);\n else if (repo instanceof GradleRepositoryAdapter)\n fakes.add((GradleRepositoryAdapter)repo);\n else\n others.add(repo);\n });\n\n if (ret == null && generated) {\n ret = _generate(fakes, art);\n }\n\n if (ret == null && manual) {\n ret = _manual(project, mavens, art, changing);\n }\n\n if (ret == null && gradle) {\n ret = _gradle(project, others, art, changing);\n }\n\n if (ret != null)\n CACHE.put(artifact, ret);\n\n future.complete(ret);\n } catch (RuntimeException | IOException | URISyntaxException e) {\n future.completeExceptionally(e);\n e.printStackTrace();\n } finally {\n synchronized (ACTIVE_DOWNLOADS) {\n ACTIVE_DOWNLOADS.remove(downloadKey);\n }\n }\n return ret;\n }\n\n @Nullable\n private static File _generate(List<GradleRepositoryAdapter> repos, Artifact artifact) {\n for (GradleRepositoryAdapter repo : repos) {\n File ret = repo.getArtifact(artifact);\n if (ret != null && ret.exists())\n return ret;\n }\n return null;\n }\n\n @Nullable\n private static File _manual(Project project, List<MavenArtifactRepository> repos, Artifact artifact, boolean changing) throws IOException, URISyntaxException {\n if (!artifact.getVersion().endsWith(\"+\") && !artifact.isSnapshot()) {\n for (MavenArtifactRepository repo : repos) {\n Pair<Artifact, File> pair = _manualMaven(project, repo.getUrl(), artifact, changing);\n if (pair != null && pair.getValue().exists())\n return pair.getValue();\n }\n return null;\n }\n\n List<Pair<Artifact, File>> versions = new ArrayList<>();\n\n // Gather list of all versions from all repos.\n for (MavenArtifactRepository repo : repos) {\n Pair<Artifact, File> pair = _manualMaven(project, repo.getUrl(), artifact, changing);\n if (pair != null && pair.getValue().exists())\n versions.add(pair);\n }\n\n Artifact version = null;\n File ret = null;\n for (Pair<Artifact, File> ver : versions) {\n //Select highest version\n if (version == null || version.compareTo(ver.getKey()) < 0) {\n version = ver.getKey();\n ret = ver.getValue();\n }\n }\n\n if (ret == null)\n return null;\n\n VERSIONS.put(artifact.getDescriptor(), version.getVersion());\n return ret;\n }\n\n @SuppressWarnings(\"unchecked\")\n @Nullable\n private static Pair<Artifact, File> _manualMaven(Project project, URI maven, Artifact artifact, boolean changing) throws IOException, URISyntaxException {\n if (artifact.getVersion().endsWith(\"+\")) {\n //I THINK +'s are only valid in the end version, So 1.+ and not 1.+.4 as that'd make no sense.\n //It also appears you can't do something like 1.5+ to NOT get 1.4/1.3. So.. mimic that.\n File meta = _downloadWithCache(project, maven, artifact.getGroup().replace('.', '/') + '/' + artifact.getName() + \"/maven-metadata.xml\", true, true);\n if (meta == null)\n return null; //Don't error, other repos might have it.\n try {\n Node xml = new XmlParser().parse(meta);\n Node versioning = getPath(xml, \"versioning/versions\");\n List<Node> versions = versioning == null ? null : (List<Node>)versioning.get(\"version\");\n if (versions == null) {\n meta.delete();\n throw new IOException(\"Invalid maven-metadata.xml file, missing version list\");\n }\n String prefix = artifact.getVersion().substring(0, artifact.getVersion().length() - 1); // Trim +\n ArtifactVersion minVersion = (!prefix.endsWith(\".\") && prefix.length() > 0) ? new DefaultArtifactVersion(prefix) : null;\n if (minVersion != null) { //Support min version like 1.5+ by saving it, and moving the prefix\n //minVersion = new DefaultArtifactVersion(prefix);\n int idx = prefix.lastIndexOf('.');\n prefix = idx == -1 ? \"\" : prefix.substring(0, idx + 1);\n }\n final String prefix_ = prefix;\n ArtifactVersion highest = versions.stream().map(Node::text)\n .filter(s -> s.startsWith(prefix_))\n .map(DefaultArtifactVersion::new)\n .filter(v -> minVersion == null || minVersion.compareTo(v) <= 0)\n .sorted()\n .reduce((first, second) -> second).orElse(null);\n if (highest == null)\n return null; //We have no versions that match what we want, so move on to next repo.\n artifact = Artifact.from(artifact.getGroup(), artifact.getName(), highest.toString(), artifact.getClassifier(), artifact.getExtension());\n } catch (SAXException | ParserConfigurationException e) {\n meta.delete();\n throw new IOException(\"Invalid maven-metadata.xml file\", e);\n }\n } else if (artifact.getVersion().contains(\"-SNAPSHOT\")) {\n return null; //TODO\n //throw new IllegalArgumentException(\"Snapshot versions are not supported, yet... \" + artifact.getDescriptor());\n }\n\n File ret = _downloadWithCache(project, maven, artifact.getPath(), changing, false);\n return ret == null ? null : ImmutablePair.of(artifact, ret);\n }\n\n //I'm sure there is a better way but not sure at the moment\n @SuppressWarnings(\"unchecked\")\n @Nullable\n private static Node getPath(Node node, String path) {\n Node tmp = node;\n for (String pt : path.split(\"/\")) {\n tmp = ((List<Node>)tmp.get(pt)).stream().findFirst().orElse(null);\n if (tmp == null)\n return null;\n }\n return tmp;\n }\n\n @Nullable\n private static File _gradle(Project project, List<ArtifactRepository> repos, Artifact mine, boolean changing) {\n String name = \"mavenDownloader_\" + mine.getDescriptor().replace(':', '_');\n synchronized(project) {\n int count = COUNTER.getOrDefault(project, 1);\n name += \"_\" + count++;\n COUNTER.put(project, count);\n }\n\n //Remove old repos, and only use the ones we're told to.\n List<ArtifactRepository> old = new ArrayList<>(project.getRepositories());\n project.getRepositories().clear();\n project.getRepositories().addAll(repos);\n\n Configuration cfg = project.getConfigurations().create(name);\n ExternalModuleDependency dependency = (ExternalModuleDependency)project.getDependencies().create(mine.getDescriptor());\n dependency.setChanging(changing);\n cfg.getDependencies().add(dependency);\n cfg.resolutionStrategy(strat -> {\n strat.cacheChangingModulesFor(5, TimeUnit.MINUTES);\n strat.cacheDynamicVersionsFor(5, TimeUnit.MINUTES);\n });\n Set<File> files;\n try {\n files = cfg.resolve();\n } catch (NullPointerException npe) {\n // This happens for unknown reasons deep in Gradle code... so we SHOULD find a way to fix it, but\n //honestly i'd rather deprecate this whole system and replace it with downloading things ourselves.\n project.getLogger().error(\"Failed to download \" + mine.getDescriptor() + \" gradle exploded\");\n return null;\n }\n File ret = files.iterator().next(); //We only want the first, not transitive\n\n cfg.getResolvedConfiguration().getResolvedArtifacts().forEach(art -> {\n ModuleVersionIdentifier resolved = art.getModuleVersion().getId();\n if (resolved.getGroup().equals(mine.getGroup()) && resolved.getName().equals(mine.getName())) {\n if ((mine.getClassifier() == null && art.getClassifier() == null) || mine.getClassifier().equals(art.getClassifier()))\n VERSIONS.put(mine.getDescriptor(), resolved.getVersion());\n }\n });\n\n project.getConfigurations().remove(cfg);\n\n project.getRepositories().clear(); //Clear the repos so we can re-add in the correct oder.\n project.getRepositories().addAll(old); //Readd all the normal repos.\n return ret;\n }\n\n @Nullable\n private static File _downloadWithCache(Project project, URI maven, String path, boolean changing, boolean bypassLocal) throws IOException, URISyntaxException {\n URL url = new URIBuilder(maven)\n .setPath(maven.getPath() + '/' + path)\n .build()\n .normalize()\n .toURL();\n File target = Utils.getCache(project, \"maven_downloader\", path);\n return DownloadUtils.downloadWithCache(url, target, changing, bypassLocal);\n }\n\n /**\n * Key used to track active downloads and avoid downloading the same file in two threads concurrently,\n * leading to corrupted files on disk.\n */\n private static class DownloadKey {\n private final Project project;\n private final String artifact;\n private final boolean changing;\n private final boolean generated;\n private final boolean gradle;\n private final boolean manual;\n\n DownloadKey(Project project, String artifact, boolean changing, boolean generated, boolean gradle, boolean manual) {\n this.project = project;\n this.artifact = artifact;\n this.changing = changing;\n this.generated = generated;\n this.gradle = gradle;\n this.manual = manual;\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 DownloadKey that = (DownloadKey) o;\n return changing == that.changing && generated == that.generated && gradle == that.gradle && manual == that.manual && project.equals(that.project) && artifact.equals(that.artifact);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(project, artifact, changing, generated, gradle, manual);\n }\n\n }\n\n}", "public class McpNames {\n private static final String NEWLINE = System.getProperty(\"line.separator\");\n private static final Pattern SRG_FINDER = Pattern.compile(\"[fF]unc_\\\\d+_[a-zA-Z_]+|m_\\\\d+_|[fF]ield_\\\\d+_[a-zA-Z_]+|f_\\\\d+_|p_\\\\w+_\\\\d+_|p_\\\\d+_\");\n private static final Pattern CONSTRUCTOR_JAVADOC_PATTERN = Pattern.compile(\"^(?<indent>(?: {3})+|\\\\t+)(public |private|protected |)(?<generic><[\\\\w\\\\W]*>\\\\s+)?(?<name>[\\\\w.]+)\\\\((?<parameters>.*)\\\\)\\\\s+(?:throws[\\\\w.,\\\\s]+)?\\\\{\");\n private static final Pattern METHOD_JAVADOC_PATTERN = Pattern.compile(\"^(?<indent>(?: {3})+|\\\\t+)(?!return)(?:\\\\w+\\\\s+)*(?<generic><[\\\\w\\\\W]*>\\\\s+)?(?<return>\\\\w+[\\\\w$.]*(?:<[\\\\w\\\\W]*>)?[\\\\[\\\\]]*)\\\\s+(?<name>(?:func_|m_)[0-9]+_[a-zA-Z_]*)\\\\(\");\n private static final Pattern FIELD_JAVADOC_PATTERN = Pattern.compile(\"^(?<indent>(?: {3})+|\\\\t+)(?!return)(?:\\\\w+\\\\s+)*\\\\w+[\\\\w$.]*(?:<[\\\\w\\\\W]*>)?[\\\\[\\\\]]*\\\\s+(?<name>(?:field_|f_)[0-9]+_[a-zA-Z_]*) *[=;]\");\n private static final Pattern CLASS_JAVADOC_PATTERN = Pattern.compile(\"^(?<indent> *|\\\\t*)([\\\\w|@]*\\\\s)*(class|interface|@interface|enum) (?<name>[\\\\w]+)\");\n private static final Pattern CLOSING_CURLY_BRACE = Pattern.compile(\"^(?<indent> *|\\\\t*)}\");\n private static final Pattern PACKAGE_DECL = Pattern.compile(\"^[\\\\s]*package(\\\\s)*(?<name>[\\\\w|.]+);$\");\n private static final Pattern LAMBDA_DECL = Pattern.compile(\"\\\\((?<args>(?:(?:, ){0,1}p_[\\\\w]+_\\\\d+_\\\\b)+)\\\\) ->\");\n\n public static McpNames load(File data) throws IOException {\n Map<String, String> names = new HashMap<>();\n Map<String, String> docs = new HashMap<>();\n try (ZipFile zip = new ZipFile(data)) {\n List<ZipEntry> entries = zip.stream().filter(e -> e.getName().endsWith(\".csv\")).collect(Collectors.toList());\n for (ZipEntry entry : entries) {\n try (NamedCsvReader reader = NamedCsvReader.builder().build(new InputStreamReader(zip.getInputStream(entry)))) {\n String obf = reader.getHeader().contains(\"searge\") ? \"searge\" : \"param\";\n boolean hasDesc = reader.getHeader().contains(\"desc\");\n reader.forEach(row -> {\n String searge = row.getField(obf);\n names.put(searge, row.getField(\"name\"));\n if (hasDesc) {\n String desc = row.getField(\"desc\");\n if (!desc.isEmpty())\n docs.put(searge, desc);\n }\n });\n }\n }\n }\n\n return new McpNames(HashFunction.SHA1.hash(data), names, docs);\n }\n\n private final Map<String, String> names;\n private final Map<String, String> docs;\n public final String hash;\n\n private McpNames(String hash, Map<String, String> names, Map<String, String> docs) {\n this.hash = hash;\n this.names = names;\n this.docs = docs;\n }\n\n public String rename(InputStream stream, boolean javadocs) throws IOException {\n return rename(stream, javadocs, true, StandardCharsets.UTF_8);\n }\n\n public String rename(InputStream stream, boolean javadocs, boolean lambdas) throws IOException {\n return rename(stream, javadocs, lambdas, StandardCharsets.UTF_8);\n }\n\n public String rename(InputStream stream, boolean javadocs, boolean lambdas, Charset sourceFileCharset)\n throws IOException {\n\n String data = IOUtils.toString(stream, sourceFileCharset);\n List<String> input = IOUtils.readLines(new StringReader(data));\n\n // Return early on emtpy files\n if (data.isEmpty())\n return \"\";\n\n //Reader doesn't give us the empty line if the file ends with a newline.. so add one.\n if (data.charAt(data.length() - 1) == '\\r' || data.charAt(data.length() - 1) == '\\n')\n input.add(\"\");\n\n List<String> lines = new ArrayList<>();\n Deque<Pair<String, Integer>> innerClasses = new LinkedList<>(); //pair of inner class name & indentation\n String _package = \"\"; //default package\n Set<String> blacklist = null;\n\n if (!lambdas) {\n blacklist = new HashSet<>();\n for (String line : input) {\n Matcher m = LAMBDA_DECL.matcher(line);\n if (!m.find())\n continue;\n blacklist.addAll(Arrays.asList(m.group(\"args\").split(\", \")));\n }\n }\n\n for (String line : input) {\n Matcher m = PACKAGE_DECL.matcher(line);\n if(m.find())\n _package = m.group(\"name\") + \".\";\n\n if (javadocs) {\n if (!injectJavadoc(lines, line, _package, innerClasses))\n javadocs = false;\n }\n lines.add(replaceInLine(line, blacklist));\n }\n return String.join(NEWLINE, lines);\n }\n\n public String rename(String entry) {\n return names.getOrDefault(entry, entry);\n }\n\n /**\n * Injects a javadoc into the given list of lines, if the given line is a\n * method or field declaration.\n * @param lines The current file content (to be modified by this method)\n * @param line The line that was just read (will not be in the list)\n * @param _package the name of the package this file is declared to be in, in com.example format;\n * @param innerClasses current position in inner class\n */\n private boolean injectJavadoc(List<String> lines, String line, String _package, Deque<Pair<String, Integer>> innerClasses) {\n // constructors\n Matcher matcher = CONSTRUCTOR_JAVADOC_PATTERN.matcher(line);\n boolean isConstructor = matcher.find() && !innerClasses.isEmpty() && innerClasses.peek().getLeft().contains(matcher.group(\"name\"));\n // methods\n if (!isConstructor)\n matcher = METHOD_JAVADOC_PATTERN.matcher(line);\n\n if (isConstructor || matcher.find()) {\n String name = isConstructor ? \"<init>\" : matcher.group(\"name\");\n String javadoc = docs.get(name);\n if (javadoc == null && !innerClasses.isEmpty() && !name.startsWith(\"func_\") && !name.startsWith(\"m_\")) {\n String currentClass = innerClasses.peek().getLeft();\n javadoc = docs.get(currentClass + '#' + name);\n }\n if (javadoc != null)\n insertAboveAnnotations(lines, JavadocAdder.buildJavadoc(matcher.group(\"indent\"), javadoc, true));\n\n // worked, so return and don't try the fields.\n return true;\n }\n\n // fields\n matcher = FIELD_JAVADOC_PATTERN.matcher(line);\n if (matcher.find()) {\n String name = matcher.group(\"name\");\n String javadoc = docs.get(name);\n if (javadoc == null && !innerClasses.isEmpty() && !name.startsWith(\"field_\") && !name.startsWith(\"f_\")) {\n String currentClass = innerClasses.peek().getLeft();\n javadoc = docs.get(currentClass + '#' + name);\n }\n if (javadoc != null)\n insertAboveAnnotations(lines, JavadocAdder.buildJavadoc(matcher.group(\"indent\"), javadoc, false));\n\n return true;\n }\n\n //classes\n matcher = CLASS_JAVADOC_PATTERN.matcher(line);\n if(matcher.find()) {\n //we maintain a stack of the current (inner) class in com.example.ClassName$Inner format (along with indentation)\n //if the stack is not empty we are entering a new inner class\n String currentClass = (innerClasses.isEmpty() ? _package : innerClasses.peek().getLeft() + \"$\") + matcher.group(\"name\");\n innerClasses.push(Pair.of(currentClass, matcher.group(\"indent\").length()));\n String javadoc = docs.get(currentClass);\n if (javadoc != null) {\n insertAboveAnnotations(lines, JavadocAdder.buildJavadoc(matcher.group(\"indent\"), javadoc, true));\n }\n\n return true;\n }\n\n //detect curly braces for inner class stacking/end identification\n matcher = CLOSING_CURLY_BRACE.matcher(line);\n if(matcher.find()){\n if(!innerClasses.isEmpty()) {\n int len = matcher.group(\"indent\").length();\n if (len == innerClasses.peek().getRight()) {\n innerClasses.pop();\n } else if (len < innerClasses.peek().getRight()) {\n System.err.println(\"Failed to properly track class blocks around class \" + innerClasses.peek().getLeft() + \":\" + (lines.size() + 1));\n return false;\n }\n }\n }\n\n return true;\n }\n\n /** Inserts the given javadoc line into the list of lines before any annotations */\n private static void insertAboveAnnotations(List<String> list, String line) {\n int back = 0;\n while (list.get(list.size() - 1 - back).trim().startsWith(\"@\"))\n back++;\n list.add(list.size() - back, line);\n }\n\n /*\n * There are certain times, such as Mixin Accessors that we wish to have the name of this method with the first character upper case.\n */\n private String getMapped(String srg, @Nullable Set<String> blacklist) {\n if (blacklist != null && blacklist.contains(srg))\n return srg;\n\n boolean cap = srg.charAt(0) == 'F';\n if (cap)\n srg = 'f' + srg.substring(1);\n\n String ret = names.getOrDefault(srg, srg);\n if (cap)\n ret = ret.substring(0, 1).toUpperCase(Locale.ENGLISH) + ret.substring(1);\n return ret;\n }\n\n private String replaceInLine(String line, @Nullable Set<String> blacklist) {\n StringBuffer buf = new StringBuffer();\n Matcher matcher = SRG_FINDER.matcher(line);\n while (matcher.find()) {\n // Since '$' is a valid character in identifiers, but we need to NOT treat this as a regex group, escape any occurrences\n matcher.appendReplacement(buf, Matcher.quoteReplacement(getMapped(matcher.group(), blacklist)));\n }\n matcher.appendTail(buf);\n return buf.toString();\n }\n}", "public class Utils {\n private static final boolean ENABLE_FILTER_REPOS = Boolean.parseBoolean(System.getProperty(\"net.minecraftforge.gradle.filter_repos\", \"true\"));\n\n public static final Gson GSON = new GsonBuilder()\n .registerTypeAdapter(MCPConfigV1.Step.class, new MCPConfigV1.Step.Deserializer())\n .registerTypeAdapter(VersionJson.Argument.class, new VersionJson.Argument.Deserializer())\n .setPrettyPrinting().create();\n static final int CACHE_TIMEOUT = 1000 * 60 * 60; //1 hour, Timeout used for version_manifest.json so we dont ping their server every request.\n //manifest doesn't include sha1's so we use this for the per-version json as well.\n public static final String FORGE_MAVEN = \"https://maven.minecraftforge.net/\";\n public static final String MOJANG_MAVEN = \"https://libraries.minecraft.net/\";\n public static final String BINPATCHER = \"net.minecraftforge:binarypatcher:1.+:fatjar\";\n public static final String ACCESSTRANSFORMER = \"net.minecraftforge:accesstransformers:8.0.+:fatjar\";\n public static final String SPECIALSOURCE = \"net.md-5:SpecialSource:1.10.0:shaded\";\n public static final String FART = \"net.minecraftforge:ForgeAutoRenamingTool:0.1.+:all\";\n public static final String SRG2SOURCE = \"net.minecraftforge:Srg2Source:8.+:fatjar\";\n public static final String SIDESTRIPPER = \"net.minecraftforge:mergetool:1.1.3:fatjar\";\n public static final String INSTALLERTOOLS = \"net.minecraftforge:installertools:1.2.8:fatjar\";\n public static final long ZIPTIME = 628041600000L;\n public static final TimeZone GMT = TimeZone.getTimeZone(\"GMT\");\n\n public static void extractFile(ZipFile zip, String name, File output) throws IOException {\n extractFile(zip, zip.getEntry(name), output);\n }\n\n public static void extractFile(ZipFile zip, ZipEntry entry, File output) throws IOException {\n File parent = output.getParentFile();\n if (!parent.exists())\n parent.mkdirs();\n\n try (InputStream stream = zip.getInputStream(entry)) {\n Files.copy(stream, output.toPath(), StandardCopyOption.REPLACE_EXISTING);\n }\n }\n\n public static void extractDirectory(Function<String, File> fileLocator, ZipFile zip, String directory) throws IOException {\n Enumeration<? extends ZipEntry> entries = zip.entries();\n while (entries.hasMoreElements()) {\n ZipEntry e = entries.nextElement();\n if (e.isDirectory()) continue;\n if (!e.getName().startsWith(directory)) continue;\n extractFile(zip, e, fileLocator.apply(e.getName()));\n }\n }\n\n public static Set<String> copyZipEntries(ZipOutputStream zout, ZipInputStream zin, Predicate<String> filter) throws IOException {\n Set<String> added = new HashSet<>();\n ZipEntry entry;\n while ((entry = zin.getNextEntry()) != null) {\n if (!filter.test(entry.getName())) continue;\n ZipEntry _new = new ZipEntry(entry.getName());\n _new.setTime(0); //SHOULD be the same time as the main entry, but NOOOO _new.setTime(entry.getTime()) throws DateTimeException, so you get 0, screw you!\n zout.putNextEntry(_new);\n IOUtils.copy(zin, zout);\n added.add(entry.getName());\n }\n return added;\n }\n\n public static byte[] base64DecodeStringList(List<String> strings) throws IOException {\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n for (String string : strings) {\n bos.write(Base64.getDecoder().decode(string));\n }\n return bos.toByteArray();\n }\n\n public static File delete(File file) {\n if (!file.getParentFile().exists()) file.getParentFile().mkdirs();\n if (file.exists()) file.delete();\n return file;\n }\n\n public static File createEmpty(File file) throws IOException {\n delete(file);\n file.createNewFile();\n return file;\n }\n\n public static Path getCacheBase(Project project) {\n File gradleUserHomeDir = project.getGradle().getGradleUserHomeDir();\n return Paths.get(gradleUserHomeDir.getPath(), \"caches\", \"forge_gradle\");\n }\n\n public static File getCache(Project project, String... tail) {\n return Paths.get(getCacheBase(project).toString(), tail).toFile();\n }\n\n public static void extractZip(File source, File target, boolean overwrite) throws IOException {\n extractZip(source, target, overwrite, false);\n }\n\n public static void extractZip(File source, File target, boolean overwrite, boolean deleteExtras) throws IOException {\n Set<File> extra = deleteExtras ? Files.walk(target.toPath()).filter(Files::isRegularFile).map(Path::toFile).collect(Collectors.toSet()) : new HashSet<>();\n\n try (ZipFile zip = new ZipFile(source)) {\n Enumeration<? extends ZipEntry> enu = zip.entries();\n while (enu.hasMoreElements()) {\n ZipEntry e = enu.nextElement();\n if (e.isDirectory()) continue;\n File out = new File(target, e.getName());\n File parent = out.getParentFile();\n if (!parent.exists()) {\n parent.mkdirs();\n }\n extra.remove(out);\n\n if (out.exists()) {\n if (!overwrite)\n continue;\n\n //Reading is fast, and prevents Disc wear, so check if it's equals before writing.\n try (FileInputStream fis = new FileInputStream(out)){\n if (IOUtils.contentEquals(zip.getInputStream(e), fis))\n continue;\n }\n }\n\n try (FileOutputStream fos = new FileOutputStream(out)) {\n IOUtils.copy(zip.getInputStream(e), fos);\n }\n }\n }\n\n if (deleteExtras) {\n extra.forEach(File::delete);\n\n //Delete empty directories\n Files.walk(target.toPath())\n .filter(Files::isDirectory)\n .sorted(Comparator.reverseOrder())\n .map(Path::toFile)\n .filter(f -> f.list().length == 0)\n .forEach(File::delete);\n }\n }\n\n public static File updateDownload(Project project, File target, Download dl) throws IOException {\n if (!target.exists() || !HashFunction.SHA1.hash(target).equals(dl.sha1)) {\n project.getLogger().lifecycle(\"Downloading: \" + dl.url);\n\n if (!target.getParentFile().exists()) {\n target.getParentFile().mkdirs();\n }\n\n FileUtils.copyURLToFile(dl.url, target);\n }\n return target;\n }\n\n public static <T> T loadJson(File target, Class<T> clz) throws IOException {\n try (InputStream in = new FileInputStream(target)) {\n return GSON.fromJson(new InputStreamReader(in), clz);\n }\n }\n public static <T> T loadJson(InputStream in, Class<T> clz) {\n return GSON.fromJson(new InputStreamReader(in), clz);\n }\n\n public static void updateHash(File target) throws IOException {\n updateHash(target, HashFunction.values());\n }\n public static void updateHash(File target, HashFunction... functions) throws IOException {\n for (HashFunction function : functions) {\n File cache = new File(target.getAbsolutePath() + \".\" + function.getExtension());\n if (target.exists()) {\n String hash = function.hash(target);\n Files.write(cache.toPath(), hash.getBytes());\n } else if (cache.exists()) {\n cache.delete();\n }\n }\n }\n\n public static void forZip(ZipFile zip, IOConsumer<ZipEntry> consumer) throws IOException {\n for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {\n consumer.accept(entries.nextElement());\n }\n }\n @FunctionalInterface\n public interface IOConsumer<T> {\n void accept(T value) throws IOException;\n }\n\n /**\n * Resolves the supplied object to a string.\n * If the input is null, this will return null.\n * Closures and Callables are called with no arguments.\n * Arrays use Arrays.toString().\n * File objects return their absolute paths.\n * All other objects have their toString run.\n * @param obj Object to resolve\n * @return resolved string\n */\n @SuppressWarnings(\"rawtypes\")\n @Nullable\n public static String resolveString(@Nullable Object obj) {\n if (obj == null)\n return null;\n else if (obj instanceof String) // stop early if its the right type. no need to do more expensive checks\n return (String)obj;\n else if (obj instanceof Closure)\n return resolveString(((Closure)obj).call());// yes recursive.\n else if (obj instanceof Callable) {\n try {\n return resolveString(((Callable)obj).call());\n } catch (Exception e) {\n return null;\n }\n } else if (obj instanceof File)\n return ((File) obj).getAbsolutePath();\n else if (obj.getClass().isArray()) { // arrays\n if (obj instanceof Object[])\n return Arrays.toString(((Object[]) obj));\n else if (obj instanceof byte[])\n return Arrays.toString(((byte[]) obj));\n else if (obj instanceof char[])\n return Arrays.toString(((char[]) obj));\n else if (obj instanceof int[])\n return Arrays.toString(((int[]) obj));\n else if (obj instanceof float[])\n return Arrays.toString(((float[]) obj));\n else if (obj instanceof double[])\n return Arrays.toString(((double[]) obj));\n else if (obj instanceof long[])\n return Arrays.toString(((long[]) obj));\n else\n return obj.getClass().getSimpleName();\n }\n return obj.toString();\n }\n\n public static <T> T[] toArray(JsonArray array, Function<JsonElement, T> adapter, IntFunction<T[]> arrayFactory) {\n return StreamSupport.stream(array.spliterator(), false).map(adapter).toArray(arrayFactory);\n }\n\n public static byte[] getZipData(File file, String name) throws IOException {\n try (ZipFile zip = new ZipFile(file)) {\n ZipEntry entry = zip.getEntry(name);\n if (entry == null)\n throw new IOException(\"Zip Missing Entry: \" + name + \" File: \" + file);\n\n return IOUtils.toByteArray(zip.getInputStream(entry));\n }\n }\n\n\n public static <T> T fromJson(InputStream stream, Class<T> classOfT) throws JsonSyntaxException, JsonIOException {\n return GSON.fromJson(new InputStreamReader(stream), classOfT);\n }\n public static <T> T fromJson(byte[] data, Class<T> classOfT) throws JsonSyntaxException, JsonIOException {\n return GSON.fromJson(new InputStreamReader(new ByteArrayInputStream(data)), classOfT);\n }\n\n @Nonnull\n public static String capitalize(@Nonnull final String toCapitalize) {\n return toCapitalize.length() > 1 ? toCapitalize.substring(0, 1).toUpperCase() + toCapitalize.substring(1) : toCapitalize;\n }\n\n public static Stream<String> lines(InputStream input) {\n BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));\n return reader.lines().onClose(() -> {\n try {\n reader.close();\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n });\n }\n\n public static ZipEntry getStableEntry(String name) {\n return getStableEntry(name, Utils.ZIPTIME);\n }\n\n public static ZipEntry getStableEntry(String name, long time) {\n TimeZone _default = TimeZone.getDefault();\n TimeZone.setDefault(GMT);\n ZipEntry ret = new ZipEntry(name);\n ret.setTime(time);\n TimeZone.setDefault(_default);\n return ret;\n }\n\n public static void createRunConfigTasks(final MinecraftExtension extension, final TaskProvider<ExtractNatives> extractNatives, final TaskProvider<?>... setupTasks) {\n List<TaskProvider<?>> setupTasksLst = new ArrayList<>(Arrays.asList(setupTasks));\n\n final TaskProvider<Task> prepareRuns = extension.getProject().getTasks().register(\"prepareRuns\", Task.class, task -> {\n task.setGroup(RunConfig.RUNS_GROUP);\n task.dependsOn(extractNatives, setupTasksLst);\n });\n\n final TaskProvider<Task> makeSrcDirs = extension.getProject().getTasks().register(\"makeSrcDirs\", Task.class, task ->\n task.doFirst(t -> {\n final JavaPluginExtension java = task.getProject().getExtensions().getByType(JavaPluginExtension.class);\n\n java.getSourceSets().forEach(s -> s.getAllSource()\n .getSrcDirs().stream().filter(f -> !f.exists()).forEach(File::mkdirs));\n }));\n setupTasksLst.add(makeSrcDirs);\n\n extension.getRuns().forEach(RunConfig::mergeParents);\n\n // Create run configurations _AFTER_ all projects have evaluated so that _ALL_ run configs exist and have been configured\n extension.getProject().getGradle().projectsEvaluated(gradle -> {\n VersionJson json = null;\n\n try {\n json = Utils.loadJson(extractNatives.get().getMeta().get().getAsFile(), VersionJson.class);\n } catch (IOException ignored) {\n }\n\n List<String> additionalClientArgs = json != null ? json.getPlatformJvmArgs() : Collections.emptyList();\n\n extension.getRuns().forEach(RunConfig::mergeChildren);\n extension.getRuns().forEach(run -> RunConfigGenerator.createRunTask(run, extension.getProject(), prepareRuns, additionalClientArgs));\n\n EclipseHacks.doEclipseFixes(extension, extractNatives, setupTasksLst);\n\n RunConfigGenerator.createIDEGenRunsTasks(extension, prepareRuns, makeSrcDirs, additionalClientArgs);\n });\n }\n\n public static void addRepoFilters(Project project) {\n if (!ENABLE_FILTER_REPOS) return;\n\n if (project.getGradle().getStartParameter().getTaskNames().stream().anyMatch(t -> t.endsWith(\"DownloadSources\"))) {\n // Only modify repos already present to fix issues with IntelliJ's download sources\n project.getRepositories().forEach(Utils::addMappedFilter);\n } else {\n // Modify Repos already present and when they get added\n project.getRepositories().all(Utils::addMappedFilter);\n }\n }\n\n private static void addMappedFilter(ArtifactRepository repository) {\n // Skip our \"Fake\" Repos that actually do provide the de-obfuscated Artifacts\n if (repository instanceof GradleRepositoryAdapter) return;\n\n // Exclude Artifacts that are being de-obfuscated via ForgeGradle (_mapped_ in version)\n repository.content(rcd -> rcd.excludeVersionByRegex(\".*\", \".*\", \".*_mapped_.*\"));\n }\n\n public static File getMCDir()\n {\n switch (VersionJson.OS.getCurrent()) {\n case OSX:\n return new File(System.getProperty(\"user.home\") + \"/Library/Application Support/minecraft\");\n case WINDOWS:\n return new File(System.getenv(\"APPDATA\") + \"\\\\.minecraft\");\n case LINUX:\n default:\n return new File(System.getProperty(\"user.home\") + \"/.minecraft\");\n }\n }\n\n public static String replaceTokens(Map<String, ?> tokens, String value) {\n StringBuilder buf = new StringBuilder();\n\n for (int x = 0; x < value.length(); x++) {\n char c = value.charAt(x);\n if (c == '\\\\') {\n if (x == value.length() - 1)\n throw new IllegalArgumentException(\"Illegal pattern (Bad escape): \" + value);\n buf.append(value.charAt(++x));\n } else if (c == '{' || c == '\\'') {\n StringBuilder key = new StringBuilder();\n for (int y = x + 1; y <= value.length(); y++) {\n if (y == value.length())\n throw new IllegalArgumentException(\"Illegal pattern (Unclosed \" + c + \"): \" + value);\n char d = value.charAt(y);\n if (d == '\\\\') {\n if (y == value.length() - 1)\n throw new IllegalArgumentException(\"Illegal pattern (Bad escape): \" + value);\n key.append(value.charAt(++y));\n } else if (c == '{' && d == '}') {\n x = y;\n break;\n } else if (c == '\\'' && d == '\\'') {\n x = y;\n break;\n } else\n key.append(d);\n }\n if (c == '\\'')\n buf.append(key);\n else {\n Object v = tokens.get(key.toString());\n if (v instanceof Supplier)\n v = ((Supplier<?>) v).get();\n\n buf.append(v == null ? \"{\" + key + \"}\" : v);\n }\n } else {\n buf.append(c);\n }\n }\n\n return buf.toString();\n }\n}", "public class MCPRepo extends BaseRepo {\n private static MCPRepo INSTANCE = null;\n private static final String GROUP_MINECRAFT = \"net.minecraft\";\n private static final String NAMES_MINECRAFT = \"^(client|server|joined|mappings_[a-z_]+)$\";\n private static final String GROUP_MCP = \"de.oceanlabs.mcp\";\n private static final String NAMES_MCP = \"^(mcp_config)$\";\n private static final String STEP_MERGE = \"merge\"; //TODO: Design better way to get steps output, for now hardcode\n private static final String STEP_RENAME = \"rename\";\n\n //This is the artifact we expose that is a zip containing SRG->Official fields and methods.\n public static final String MAPPING_DEP = \"net.minecraft:mappings_{CHANNEL}:{VERSION}@zip\";\n public static String getMappingDep(String channel, String version) {\n return MAPPING_DEP.replace(\"{CHANNEL}\", channel).replace(\"{VERSION}\", version);\n }\n\n private final Project project;\n private final Repository repo;\n private final Map<String, MCPWrapper> wrappers = Maps.newHashMap();\n private final Map<String, McpNames> mapCache = new HashMap<>();\n\n private MCPRepo(Project project, File cache, Logger log) {\n super(cache, log);\n this.project = project;\n this.repo = SimpleRepository.of(ArtifactProviderBuilder.begin(ArtifactIdentifier.class)\n .provide(this)\n );\n }\n\n private static MCPRepo getInstance(Project project) {\n if (INSTANCE == null)\n INSTANCE = new MCPRepo(project, Utils.getCache(project, \"mcp_repo\"), project.getLogger());\n return INSTANCE;\n }\n public static void attach(Project project) {\n MCPRepo instance = getInstance(project);\n GradleRepositoryAdapter.add(project.getRepositories(), \"MCP_DYNAMIC\", instance.getCacheRoot(), instance.repo);\n }\n\n public static ArtifactProvider<ArtifactIdentifier> create(Project project) {\n return getInstance(project);\n }\n\n @Override\n protected File cache(String... path) {\n return super.cache(path);\n }\n\n File cacheMC(String side, String version, @Nullable String classifier, String ext) {\n if (classifier != null)\n return cache(\"net\", \"minecraft\", side, version, side + '-' + version + '-' + classifier + '.' + ext);\n return cache(\"net\", \"minecraft\", side, version, side + '-' + version + '.' + ext);\n }\n\n private File cacheMCP(String version, @Nullable String classifier, String ext) {\n if (classifier != null)\n return cache(\"de\", \"oceanlabs\", \"mcp\", \"mcp_config\", version, \"mcp_config-\" + version + '-' + classifier + '.' + ext);\n return cache(\"de\", \"oceanlabs\", \"mcp\", \"mcp_config\", version, \"mcp_config-\" + version + '.' + ext);\n }\n private File cacheMCP(String version) {\n return cache(\"de\", \"oceanlabs\", \"mcp\", \"mcp_config\", version);\n }\n\n @Override\n public File findFile(ArtifactIdentifier artifact) throws IOException {\n String name = artifact.getName();\n String group = artifact.getGroup();\n\n if (group.equals(GROUP_MCP)) {\n if (!name.matches(NAMES_MCP))\n return null;\n } else if (group.equals(GROUP_MINECRAFT)) {\n if (!name.matches(NAMES_MINECRAFT))\n return null;\n } else\n return null;\n\n String version = artifact.getVersion();\n String classifier = artifact.getClassifier() == null ? \"\" : artifact.getClassifier();\n String ext = artifact.getExtension();\n\n debug(\" \" + REPO_NAME + \" Request: \" + artifact.getGroup() + \":\" + name + \":\" + version + \":\" + classifier + \"@\" + ext);\n\n if (group.equals(GROUP_MINECRAFT)) {\n if (name.startsWith(\"mappings_\")) {\n if (\"zip\".equals(ext)) {\n return findNames(name.substring(9) + '_' + version);\n } else if (\"pom\".equals(ext)) {\n return findEmptyPom(name, version);\n }\n } else if (\"pom\".equals(ext)) {\n return findPom(name, version);\n } else if (\"jar\".equals(ext)) {\n switch (classifier) {\n case \"\": return findRaw(name, version);\n case \"srg\": return findSrg(name, version);\n case \"extra\": return findExtra(name, version);\n }\n }\n } else if (group.equals(GROUP_MCP)) {\n /* Gradle fucks up caching for anything that isnt a zip or a jar, this is fucking annoying we can't do this.\n MappingFile.Format format = MappingFile.Format.get(ext);\n if (format != null) {\n classifier = classifier.replace('!', '.'); //We hack around finding the extension by using a invalid path character\n switch (classifier) {\n case \"obf-to-srg\": return findRenames(classifier, format, version, false);\n case \"srg-to-obf\": return findRenames(classifier, format, version, true);\n }\n if (classifier.startsWith(\"obf-to-\")) return findRenames(classifier, format, version, classifier.substring(7), true, false);\n if (classifier.startsWith(\"srg-to-\")) return findRenames(classifier, format, version, classifier.substring(7), false, false);\n if (classifier.endsWith (\"-to-obf\")) return findRenames(classifier, format, version, classifier.substring(0, classifier.length() - 7), true, true);\n if (classifier.endsWith (\"-to-srg\")) return findRenames(classifier, format, version, classifier.substring(0, classifier.length() - 7), false, true);\n }\n */\n }\n return null;\n }\n\n HashStore commonHash(File mcp) {\n return new HashStore(this.getCacheRoot())\n .add(\"mcp\", mcp);\n }\n\n @Nullable\n File getMCP(String version) {\n return MavenArtifactDownloader.manual(project, \"de.oceanlabs.mcp:mcp_config:\" + version + \"@zip\", false);\n }\n\n @Nullable\n private File findVersion(String version) throws IOException {\n File manifest = cache(\"versions\", \"manifest.json\");\n if (!DownloadUtils.downloadEtag(new URL(MinecraftRepo.MANIFEST_URL), manifest, project.getGradle().getStartParameter().isOffline()))\n return null;\n Utils.updateHash(manifest);\n File json = cache(\"versions\", version, \"version.json\");\n\n URL url = Utils.loadJson(manifest, ManifestJson.class).getUrl(version);\n if (url == null)\n throw new RuntimeException(\"Missing version from manifest: \" + version);\n\n if (!DownloadUtils.downloadEtag(url, json, project.getGradle().getStartParameter().isOffline()))\n return null;\n Utils.updateHash(json);\n return json;\n }\n\n @Nullable\n private File findPom(String side, String version) throws IOException {\n File mcp = getMCP(version);\n if (mcp == null)\n return null;\n\n File pom = cacheMC(side, version, null, \"pom\");\n debug(\" Finding pom: \" + pom);\n HashStore cache = commonHash(mcp).load(cacheMC(side, version, null, \"pom.input\"));\n File json = null;\n if (!\"server\".equals(side)) {\n json = findVersion(MinecraftRepo.getMCVersion(version));\n if (json == null) {\n project.getLogger().lifecycle(\"Could not make Minecraft POM. Missing version json\");\n return null;\n }\n cache.add(\"json\", json);\n }\n\n if (!cache.isSame() || !pom.exists()) {\n POMBuilder builder = new POMBuilder(GROUP_MINECRAFT, side, version);\n if (!\"server\".equals(side)) {\n VersionJson meta = Utils.loadJson(json, VersionJson.class);\n for (VersionJson.Library lib : meta.libraries) {\n if (lib.isAllowed()) {\n if (lib.downloads.artifact != null)\n builder.dependencies().add(lib.name, \"compile\");\n if (lib.downloads.classifiers != null) {\n if (lib.downloads.classifiers.containsKey(\"test\")) {\n builder.dependencies().add(lib.name, \"test\").withClassifier(\"test\");\n }\n if (lib.natives != null && lib.natives.containsKey(MinecraftRepo.CURRENT_OS) && !lib.getArtifact().getName().contains(\"java-objc-bridge\")) {\n builder.dependencies().add(lib.name, \"runtime\").withClassifier(lib.natives.get(MinecraftRepo.CURRENT_OS));\n }\n }\n }\n }\n builder.dependencies().add(\"net.minecraft:client:\" + version, \"compile\").withClassifier(\"extra\");\n //builder.dependencies().add(\"net.minecraft:client:\" + getMCVersion(version), \"compile\").withClassifier(\"data\");\n } else {\n builder.dependencies().add(\"net.minecraft:server:\" + version, \"compile\").withClassifier(\"extra\");\n //builder.dependencies().add(\"net.minecraft:server:\" + getMCVersion(version), \"compile\").withClassifier(\"data\");\n }\n\n MCPWrapper wrapper = getWrapper(version, mcp);\n wrapper.getConfig().getLibraries(side).forEach(e -> builder.dependencies().add(e, \"compile\"));\n\n String ret = builder.tryBuild();\n if (ret == null)\n return null;\n FileUtils.writeByteArrayToFile(pom, ret.getBytes());\n cache.save();\n Utils.updateHash(pom, HashFunction.SHA1);\n }\n\n return pom;\n }\n\n @Nullable\n private File findRaw(String side, String version) throws IOException {\n if (!\"joined\".equals(side))\n return null; //MinecraftRepo provides these\n\n return findStepOutput(side, version, null, \"jar\", STEP_MERGE);\n }\n\n @Nullable\n private File findSrg(String side, String version) throws IOException {\n return findStepOutput(side, version, \"srg\", \"jar\", STEP_RENAME);\n }\n\n @Nullable\n private File findStepOutput(String side, String version, @Nullable String classifier, String ext, String step) throws IOException {\n File mcp = getMCP(version);\n if (mcp == null)\n return null;\n File raw = cacheMC(side, version, classifier, ext);\n debug(\" Finding \" + step + \": \" + raw);\n HashStore cache = commonHash(mcp).load(cacheMC(side, version, classifier, ext + \".input\"));\n\n if (!cache.isSame() || !raw.exists()) {\n MCPWrapper wrapper = getWrapper(version, mcp);\n MCPRuntime runtime = wrapper.getRuntime(project, side);\n try {\n File output = runtime.execute(log, step);\n FileUtils.copyFile(output, raw);\n cache.save();\n Utils.updateHash(raw, HashFunction.SHA1);\n } catch (IOException e) {\n throw e;\n } catch (Exception e) {\n e.printStackTrace();\n log.lifecycle(e.getMessage());\n if (e instanceof RuntimeException) throw (RuntimeException)e;\n throw new RuntimeException(e);\n }\n }\n return raw;\n }\n\n private synchronized MCPWrapper getWrapper(String version, File data) throws IOException {\n String hash = HashFunction.SHA1.hash(data);\n MCPWrapper ret = wrappers.get(version);\n if (ret == null || !hash.equals(ret.getHash())) {\n ret = new MCPWrapper(hash, data, cacheMCP(version));\n wrappers.put(version, ret);\n }\n return ret;\n }\n\n @Nullable\n File findRenames(String classifier, IMappingFile.Format format, String version, boolean toObf) throws IOException {\n String ext = format.name().toLowerCase();\n //File names = findNames(version));\n File mcp = getMCP(version);\n if (mcp == null)\n return null;\n\n File file = cacheMCP(version, classifier, ext);\n debug(\" Finding Renames: \" + file);\n HashStore cache = commonHash(mcp).load(cacheMCP(version, classifier, ext + \".input\"));\n\n if (!cache.isSame() || !file.exists()) {\n MCPWrapper wrapper = getWrapper(version, mcp);\n byte[] data = wrapper.getData(\"mappings\");\n IMappingFile obf_to_srg = IMappingFile.load(new ByteArrayInputStream(data));\n obf_to_srg.write(file.toPath(), format, toObf);\n cache.save();\n Utils.updateHash(file, HashFunction.SHA1);\n }\n\n return file;\n }\n\n @Nullable\n private File findNames(String mapping) throws IOException {\n int idx = mapping.lastIndexOf('_');\n if (idx == -1) return null; //Invalid format\n String channel = mapping.substring(0, idx);\n String version = mapping.substring(idx + 1);\n\n ChannelProvidersExtension channelProviders = project.getExtensions().getByType(ChannelProvidersExtension.class);\n ChannelProvider provider = channelProviders.getProvider(channel);\n if (provider == null)\n throw new IllegalArgumentException(\"Unknown mapping provider: \" + mapping + \", currently loaded: \" + channelProviders.getProviderMap().keySet());\n return provider.getMappingsFile(this, project, channel, version);\n }\n\n private McpNames loadMCPNames(String name, File data) throws IOException {\n McpNames map = mapCache.get(name);\n String hash = HashFunction.SHA1.hash(data);\n if (map == null || !hash.equals(map.hash)) {\n map = McpNames.load(data);\n mapCache.put(name, map);\n }\n return map;\n }\n\n @SuppressWarnings(\"unused\")\n @Nullable\n private File findRenames(String classifier, IMappingFile.Format format, String version, String mapping, boolean obf, boolean reverse) throws IOException {\n String ext = format.name().toLowerCase();\n File names = findNames(version);\n File mcp = getMCP(version);\n if (mcp == null || names == null)\n return null;\n\n File file = cacheMCP(version, classifier, ext);\n debug(\" Finding Renames: \" + file);\n HashStore cache = commonHash(mcp).load(cacheMCP(version, classifier, ext + \".input\"));\n\n if (!cache.isSame() || !file.exists()) {\n MCPWrapper wrapper = getWrapper(version, mcp);\n byte[] data = wrapper.getData(\"mappings\");\n IMappingFile input = IMappingFile.load(new ByteArrayInputStream(data)); //SRG->OBF\n if (!obf)\n input = input.reverse().chain(input); //SRG->OBF + OBF->SRG = SRG->SRG\n\n McpNames map = loadMCPNames(mapping, names);\n IMappingFile ret = input.rename(new IRenamer() {\n @Override\n public String rename(IField value) {\n return map.rename(value.getMapped());\n }\n\n @Override\n public String rename(IMethod value) {\n return map.rename(value.getMapped());\n }\n });\n\n ret.write(file.toPath(), format, reverse);\n cache.save();\n Utils.updateHash(file, HashFunction.SHA1);\n }\n\n return file;\n }\n\n @Nullable\n private File findExtra(String side, String version) throws IOException {\n File raw = findRaw(side, version);\n File mcp = getMCP(version);\n if (raw == null || mcp == null)\n return null;\n\n File extra = cacheMC(side, version, \"extra\", \"jar\");\n HashStore cache = commonHash(mcp).load(cacheMC(side, version, \"extra\", \"jar.input\"))\n .add(\"raw\", raw)\n .add(\"mcp\", mcp)\n .add(\"codever\", \"1\");\n\n if (!cache.isSame() || !extra.exists()) {\n MCPWrapper wrapper = getWrapper(version, mcp);\n byte[] data = wrapper.getData(\"mappings\");\n MinecraftRepo.splitJar(raw, new ByteArrayInputStream(data), extra, false, true);\n cache.save();\n }\n\n return extra;\n }\n\n protected static void writeCsv(String name, List<String[]> mappings, ZipOutputStream out) throws IOException {\n if (mappings.size() <= 1)\n return;\n out.putNextEntry(Utils.getStableEntry(name));\n try (CsvWriter writer = CsvWriter.builder().lineDelimiter(LineDelimiter.LF).build(new UncloseableOutputStreamWriter(out))) {\n mappings.forEach(writer::writeRow);\n }\n out.closeEntry();\n }\n\n private static class UncloseableOutputStreamWriter extends OutputStreamWriter {\n private UncloseableOutputStreamWriter(OutputStream out) {\n super(out);\n }\n\n @Override\n public void close() throws IOException {\n super.flush();\n }\n }\n\n @Nullable\n private File findEmptyPom(String side, String version) throws IOException {\n File pom = cacheMC(side, version, null, \"pom\");\n debug(\" Finding pom: \" + pom);\n HashStore cache = new HashStore(this.getCacheRoot()).load(cacheMC(side, version, null, \"pom.input\"));\n\n if (!cache.isSame() || !pom.exists()) {\n String ret = new POMBuilder(GROUP_MINECRAFT, side, version).tryBuild();\n if (ret == null)\n return null;\n FileUtils.writeByteArrayToFile(pom, ret.getBytes());\n cache.save();\n Utils.updateHash(pom, HashFunction.SHA1);\n }\n\n return pom;\n }\n\n @Override\n protected void debug(String message) {\n super.debug(message);\n }\n}", "public abstract class RenameJarSrg2Mcp extends JarExec {\n private boolean signatureRemoval = false;\n\n public RenameJarSrg2Mcp() {\n getTool().set(Utils.INSTALLERTOOLS);\n getArgs().addAll(\"--task\", \"SRG_TO_MCP\", \"--input\", \"{input}\", \"--output\", \"{output}\", \"--mcp\", \"{mappings}\", \"{strip}\");\n }\n\n @Override\n protected List<String> filterArgs(List<String> args) {\n return replaceArgs(args, ImmutableMap.of(\n \"{input}\", getInput().get().getAsFile(),\n \"{output}\", getOutput().get().getAsFile(),\n \"{mappings}\", getMappings().get().getAsFile(),\n \"{strip}\", signatureRemoval ? \"--strip-signatures\" : \"\"), null);\n }\n\n @Input\n public boolean getSignatureRemoval() {\n return this.signatureRemoval;\n }\n\n public void setSignatureRemoval(boolean value) {\n this.signatureRemoval = value;\n }\n\n @InputFile\n public abstract RegularFileProperty getMappings();\n\n @InputFile\n public abstract RegularFileProperty getInput();\n\n @OutputFile\n public abstract RegularFileProperty getOutput();\n}" ]
import net.minecraftforge.gradle.common.util.HashFunction; import net.minecraftforge.gradle.common.util.HashStore; import net.minecraftforge.gradle.common.util.MavenArtifactDownloader; import net.minecraftforge.gradle.common.util.McpNames; import net.minecraftforge.gradle.common.util.Utils; import net.minecraftforge.gradle.mcp.MCPRepo; import net.minecraftforge.gradle.userdev.tasks.RenameJarSrg2Mcp; import org.apache.commons.io.IOUtils; import org.gradle.api.Project; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Random; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.annotation.Nullable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory;
/* * ForgeGradle * Copyright (C) 2018 Forge Development LLC * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package net.minecraftforge.gradle.userdev.util; public class Deobfuscator { private final Project project; private final File cacheRoot; private final DocumentBuilder xmlParser; private final XPath xPath; private final Transformer xmlTransformer; public Deobfuscator(Project project, File cacheRoot) { this.project = project; this.cacheRoot = cacheRoot; try { xPath = XPathFactory.newInstance().newXPath(); xmlParser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); xmlTransformer = TransformerFactory.newInstance().newTransformer(); } catch (ParserConfigurationException | TransformerConfigurationException e) { throw new RuntimeException("Error configuring XML parsers", e); } } public File deobfPom(File original, String mappings, String... cachePath) throws IOException { project.getLogger().debug("Updating POM file {} with mappings {}", original.getName(), mappings); File output = getCacheFile(cachePath); File input = new File(output.getParent(), output.getName() + ".input"); HashStore cache = new HashStore() .load(input) .add("mappings", mappings) .add("orig", original); if (!cache.isSame() || !output.exists()) { try { Document pom = xmlParser.parse(original); NodeList versionNodes = (NodeList) xPath.compile("/*[local-name()=\"project\"]/*[local-name()=\"version\"]").evaluate(pom, XPathConstants.NODESET); if (versionNodes.getLength() > 0) { versionNodes.item(0).setTextContent(versionNodes.item(0).getTextContent() + "_mapped_" + mappings); } xmlTransformer.transform(new DOMSource(pom), new StreamResult(output)); } catch (IOException | SAXException | XPathExpressionException | TransformerException e) { project.getLogger().error("Error attempting to modify pom file " + original.getName(), e); return original; } Utils.updateHash(output, HashFunction.SHA1); cache.save(); } return output; } @Nullable public File deobfBinary(File original, @Nullable String mappings, String... cachePath) throws IOException { project.getLogger().debug("Deobfuscating binary file {} with mappings {}", original.getName(), mappings); File names = findMapping(mappings); if (names == null || !names.exists()) { return null; } File output = getCacheFile(cachePath); File input = new File(output.getParent(), output.getName() + ".input"); HashStore cache = new HashStore() .load(input) .add("names", names) .add("orig", original); if (!cache.isSame() || !output.exists()) { RenameJarSrg2Mcp rename = project.getTasks().create("_RenameSrg2Mcp_" + new Random().nextInt(), RenameJarSrg2Mcp.class); rename.getInput().set(original); rename.getOutput().set(output); rename.getMappings().set(names); rename.setSignatureRemoval(true); rename.apply(); rename.setEnabled(false); Utils.updateHash(output, HashFunction.SHA1); cache.save(); } return output; } @Nullable public File deobfSources(File original, @Nullable String mappings, String... cachePath) throws IOException { project.getLogger().debug("Deobfuscating sources file {} with mappings {}", original.getName(), mappings); File names = findMapping(mappings); if (names == null || !names.exists()) { return null; } File output = getCacheFile(cachePath); File input = new File(output.getParent(), output.getName() + ".input"); HashStore cache = new HashStore() .load(input) .add("names", names) .add("orig", original); if (!cache.isSame() || !output.exists()) { McpNames map = McpNames.load(names); try (ZipInputStream zin = new ZipInputStream(new FileInputStream(original)); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(output))) { ZipEntry _old; while ((_old = zin.getNextEntry()) != null) { zout.putNextEntry(Utils.getStableEntry(_old.getName())); if (_old.getName().endsWith(".java")) { String mapped = map.rename(zin, false); IOUtils.write(mapped, zout, StandardCharsets.UTF_8); } else { IOUtils.copy(zin, zout); } } } Utils.updateHash(output, HashFunction.SHA1); cache.save(); } return output; } private File getCacheFile(String... cachePath) { File cacheFile = new File(cacheRoot, String.join(File.separator, cachePath)); cacheFile.getParentFile().mkdirs(); return cacheFile; } @Nullable private File findMapping(@Nullable String mapping) { if (mapping == null) return null; int idx = mapping.lastIndexOf('_'); String channel = mapping.substring(0, idx); String version = mapping.substring(idx + 1); String desc = MCPRepo.getMappingDep(channel, version);
return MavenArtifactDownloader.generate(project, desc, false);
2
graywolf336/Jail
src/main/java/com/graywolf336/jail/command/subcommands/JailStatusCommand.java
[ "public class JailManager {\n private JailMain plugin;\n private HashMap<String, Jail> jails;\n private HashMap<String, CreationPlayer> jailCreators;\n private HashMap<String, CreationPlayer> cellCreators;\n private HashMap<String, ConfirmPlayer> confirms;\n private HashMap<UUID, CachePrisoner> cache;\n private JailCreationSteps jcs;\n private CellCreationSteps ccs;\n\n protected JailManager(JailMain plugin) {\n this.plugin = plugin;\n this.jails = new HashMap<String, Jail>();\n this.jailCreators = new HashMap<String, CreationPlayer>();\n this.cellCreators = new HashMap<String, CreationPlayer>();\n this.confirms = new HashMap<String, ConfirmPlayer>();\n this.cache = new HashMap<UUID, CachePrisoner>();\n this.jcs = new JailCreationSteps();\n this.ccs = new CellCreationSteps();\n }\n\n /**\n * Returns the instance of the plugin main class.\n * \n * @return {@link JailMain} instance\n */\n public JailMain getPlugin() {\n return this.plugin;\n }\n\n /**\n * Returns a HashSet of all the jails.\n * \n * @return HashSet of all the jail instances.\n */\n public HashSet<Jail> getJails() {\n return new HashSet<Jail>(jails.values());\n }\n\n /**\n * Returns an array of all the names of the jails.\n * \n * @return Array of the jail names\n */\n public String[] getJailNames() {\n String[] toReturn = new String[jails.size()];\n \n int count = 0;\n for(Jail j : this.jails.values()) {\n toReturn[count] = j.getName();\n count++;\n }\n \n return toReturn;\n }\n \n /**\n * Gets a list of Jail names that start with the provided prefix.\n * \n * <p>\n * \n * If the provided prefix is empty, then we add all of the jails.\n * \n * @param prefix The start of the jails to get\n * @return List of jails that matched the prefix\n */\n public List<String> getJailsByPrefix(String prefix) {\n List<String> results = new ArrayList<String>();\n \n for(Jail j : this.jails.values())\n if(prefix.isEmpty() || StringUtil.startsWithIgnoreCase(j.getName(), prefix))\n results.add(j.getName());\n \n Collections.sort(results);\n \n return results;\n }\n\n /**\n * Adds a jail to the collection of them.\n * \n * @param jail The jail to add\n * @param n True if this is a new jail, false if it isn't.\n */\n public void addJail(Jail jail, boolean n) {\n this.jails.put(jail.getName().toLowerCase(), jail);\n if(n) plugin.getJailIO().saveJail(jail);\n }\n\n /**\n * Removes a {@link Jail}.\n * \n * @param name of the jail to remove\n */\n public void removeJail(String name) {\n plugin.getJailIO().removeJail(this.jails.get(name.toLowerCase()));\n this.jails.remove(name.toLowerCase());\n }\n\n /**\n * Gets a jail by the given name.\n * \n * @param name The name of the jail to get.\n * @return The {@link Jail} with the given name, if no jail found this <strong>will</strong> return null.\n */\n public Jail getJail(String name) {\n if(name.isEmpty() && jails.isEmpty())\n return null;\n else\n return name.isEmpty() ? this.jails.values().iterator().next() : this.jails.get(name.toLowerCase());\n }\n\n /**\n * Gets the nearest {@link Jail} to the player, if the sender is a player or else it will get the first jail defined.\n * \n * @param sender The sender who we are looking around.\n * @return The nearest {@link Jail} to the sender if it is a player or else the first jail defined.\n */\n public Jail getNearestJail(CommandSender sender) {\n if(jails.isEmpty()) return null;\n \n if(sender instanceof Player) {\n Location loc = ((Player) sender).getLocation();\n\n Jail j = null;\n double len = -1;\n\n for(Jail jail : jails.values()) {\n double clen = jail.getDistance(loc);\n\n if (clen < len || len == -1) {\n len = clen;\n j = jail;\n }\n }\n\n return (j == null ? jails.values().iterator().next() : j);\n }else {\n return jails.values().iterator().next();\n }\n }\n\n /**\n * Gets the jail which this location is in, will return null if none exist.\n * \n * @param loc to get the jail from\n * @return The jail this block is in, null if no jail found.\n */\n public Jail getJailFromLocation(Location loc) {\n for(Jail j : jails.values()) {\n if(Util.isInsideAB(loc.toVector(), j.getMinPoint().toVector(), j.getMaxPoint().toVector())) {\n return j;\n }\n }\n\n return null;\n }\n\n /**\n * Gets whether the location is inside of a Jail.\n * \n * @param l to determine if is in a jail\n * @return whether it is inside a jail or not\n */\n public boolean isLocationAJail(Location l) {\n for(Jail j : jails.values()) {\n if(Util.isInsideAB(l.toVector(), j.getMinPoint().toVector(), j.getMaxPoint().toVector())) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Checks to see if the given name for a {@link Jail} is valid, returns true if it is a valid jail.\n * \n * @param name The name of the jail to check.\n * @return True if a valid jail was found, false if no jail was found.\n */\n public boolean isValidJail(String name) {\n return this.jails.containsKey(name.toLowerCase());\n }\n\n /**\n * Gets all the {@link Cell cells} in the jail system, best for system wide count of the cells or touching each cell.\n * \n * @return HashSet of all the Cells.\n */\n public HashSet<Cell> getAllCells() {\n HashSet<Cell> cells = new HashSet<Cell>();\n\n for(Jail j : jails.values())\n cells.addAll(j.getCells());\n\n return cells;\n }\n\n /**\n * Adds a prisoner to the cache.\n * \n * @param cache object to store\n * @return The same object given\n */\n public CachePrisoner addCacheObject(CachePrisoner cache) {\n plugin.debug(\"Adding \" + cache.getPrisoner().getUUID().toString() + \" to the cache.\");\n this.cache.put(cache.getPrisoner().getUUID(), cache);\n return this.cache.get(cache.getPrisoner().getUUID());\n }\n\n /**\n * Checks if the given uuid is in the cache.\n * \n * @param uuid of the player\n * @return true if in cache, false if not\n */\n public boolean inCache(UUID uuid) {\n return this.cache.containsKey(uuid);\n }\n\n /**\n * Gets a cached prisoner object.\n * \n * @param uuid of the prisoner to get\n * @return the cahced prisoner object, will be null if it doesn't exist\n */\n public CachePrisoner getCacheObject(UUID uuid) {\n return this.cache.get(uuid);\n }\n\n /**\n * Removes the cache object stored for this uuid.\n * \n * @param uuid of the prisoner to remove\n */\n public void removeCacheObject(UUID uuid) {\n plugin.debug(\"Removing \" + uuid.toString() + \" from the cache.\");\n this.cache.remove(uuid);\n }\n\n /**\n * Gets all the prisoners in the system, best for a system wide count of the prisoners or accessing all the prisoners at once.\n * \n * @return HashSet of Prisoners.\n */\n public HashMap<UUID, Prisoner> getAllPrisoners() {\n HashMap<UUID, Prisoner> prisoners = new HashMap<UUID, Prisoner>();\n\n for(Jail j : jails.values())\n prisoners.putAll(j.getAllPrisoners());\n\n return prisoners;\n }\n\n /**\n * Gets the {@link Jail jail} the given prisoner is in.\n * \n * @param prisoner The prisoner data for the prisoner we are checking\n * @return The jail the player is in, <strong>CAN BE NULL</strong>.\n */\n public Jail getJailPrisonerIsIn(Prisoner prisoner) {\n if(prisoner == null) return null;\n else return getJailPlayerIsIn(prisoner.getUUID());\n }\n\n /**\n * Gets the {@link Jail jail} the given player is in.\n * \n * <p>\n * \n * Checks the cache first.\n * \n * @param uuid The uuid of the player who's jail we are getting.\n * @return The jail the player is in, <strong>CAN BE NULL</strong>.\n */\n public Jail getJailPlayerIsIn(UUID uuid) {\n if(this.cache.containsKey(uuid)) {\n plugin.debug(uuid.toString() + \" is in the cache (getJailPlayerIsIn).\");\n return this.cache.get(uuid).getJail();\n }\n\n for(Jail j : jails.values())\n if(j.isPlayerJailed(uuid))\n return j;\n\n return null;\n }\n\n /**\n * Gets if the given uuid of a player is jailed or not, in all the jails and cells.\n * \n * @param uuid The uuid of the player to check.\n * @return true if they are jailed, false if not.\n */\n public boolean isPlayerJailed(UUID uuid) {\n return getJailPlayerIsIn(uuid) != null;\n }\n\n /**\n * Gets the {@link Prisoner} data from for this user, if they are jailed.\n * \n * @param uuid The uuid of prisoner who's data to get\n * @return {@link Prisoner prisoner} data.\n */\n public Prisoner getPrisoner(UUID uuid) {\n Jail j = getJailPlayerIsIn(uuid);\n\n return j == null ? null : j.getPrisoner(uuid);\n }\n\n /**\n * Gets the {@link Jail} the player is in from their last known username, null if not jailed.\n * \n * @param username Last known username to search by\n * @return {@link Jail jail} player is in\n */\n public Jail getJailPlayerIsInByLastKnownName(String username) {\n for(Jail j : jails.values())\n for(Prisoner p : j.getAllPrisoners().values())\n if(p.getLastKnownName().equalsIgnoreCase(username))\n return j;\n\n return null;\n }\n\n /**\n * Gets the {@link Prisoner}'s data from the last known username, returning null if no prisoner has that name.\n * \n * @param username Last known username to go by\n * @return {@link Prisoner prisoner} data\n */\n public Prisoner getPrisonerByLastKnownName(String username) {\n for(Prisoner p : this.getAllPrisoners().values())\n if(p.getLastKnownName().equalsIgnoreCase(username))\n return p;\n\n return null;\n }\n\n /**\n * Checks if the provided username is jailed, using last known username.\n * \n * @param username Last known username to go by\n * @return true if they are jailed, false if not\n */\n public boolean isPlayerJailedByLastKnownUsername(String username) {\n return this.getPrisonerByLastKnownName(username) != null;\n }\n\n /**\n * Clears a {@link Jail} of all its prisoners if the jail is provided, otherwise it releases all the prisoners in all the jails.\n * \n * @param jail The name of the jail to release the prisoners in, null if wanting to clear all.\n * @return The resulting message to be sent to the caller of this method.\n */\n public String clearJailOfPrisoners(String jail) {\n //If they don't pass in a jail name, clear all the jails\n if(jail != null) {\n Jail j = getJail(jail);\n\n if(j != null) {\n for(Prisoner p : j.getAllPrisoners().values()) {\n getPlugin().getPrisonerManager().schedulePrisonerRelease(p);\n }\n\n return Lang.PRISONERSCLEARED.get(j.getName());\n }else {\n return Lang.NOJAIL.get(jail);\n }\n }else {\n return clearAllJailsOfAllPrisoners();\n }\n }\n\n /**\n * Clears all the {@link Jail jails} of prisoners by releasing them.\n * \n * @return The resulting message to be sent to the caller of this method.\n */\n public String clearAllJailsOfAllPrisoners() {\n //No name of a jail has been passed, so release all of the prisoners in all the jails\n if(getJails().size() == 0) {\n return Lang.NOJAILS.get();\n }else {\n for(Jail j : getJails()) {\n for(Prisoner p : j.getAllPrisoners().values()) {\n getPlugin().getPrisonerManager().schedulePrisonerRelease(p);\n }\n }\n\n return Lang.PRISONERSCLEARED.get(Lang.ALLJAILS);\n }\n }\n\n /**\n * Forcefully clears all the jails if name provided is null.\n * \n * <p>\n * \n * This method just clears them from the storage, doesn't release them.\n * \n * @param name of the jail to clear, null if all of them.\n * @return The resulting message to be sent to the caller of this method.\n */\n public String forcefullyClearJailOrJails(String name) {\n if(name == null) {\n if(getJails().size() == 0) {\n return Lang.NOJAILS.get();\n }else {\n for(Jail j : getJails()) {\n j.clearPrisoners();\n }\n\n return Lang.PRISONERSCLEARED.get(Lang.ALLJAILS);\n }\n }else {\n Jail j = getJail(name);\n\n if(j != null) {\n j.clearPrisoners();\n return Lang.PRISONERSCLEARED.get(j.getName());\n }else {\n return Lang.NOJAIL.get(name);\n }\n }\n }\n\n /**\n * Deletes a jail's cell, checking everything is setup right for it to be deleted.\n * \n * @param jail Name of the jail to delete a cell in.\n * @param cell Name of the cell to delete.\n * @return The resulting message to be sent to the caller of this method.\n */\n public String deleteJailCell(String jail, String cell) {\n //Check if the jail name provided is a valid jail\n if(isValidJail(jail)) {\n Jail j = getJail(jail);\n\n //check if the cell is a valid cell\n if(j.isValidCell(cell)) {\n if(j.getCell(cell).hasPrisoner()) {\n //The cell has a prisoner, so tell them to first transfer the prisoner\n //or release the prisoner\n return Lang.CELLREMOVALUNSUCCESSFUL.get(new String[] { cell, jail });\n }else {\n j.removeCell(cell);\n return Lang.CELLREMOVED.get(new String[] { cell, jail });\n }\n }else {\n //No cell found by the provided name in the stated jail\n return Lang.NOCELL.get(new String[] { cell, jail });\n }\n }else {\n //No jail found by the provided name\n return Lang.NOJAIL.get(jail);\n }\n }\n\n /**\n * Deletes all the cells in a jail, returns a list of Strings.\n * \n * @param jail The name of the jail to delete all the jails in.\n * @return An array of strings of messages to send.\n */\n public String[] deleteAllJailCells(String jail) {\n LinkedList<String> msgs = new LinkedList<String>();\n\n //Check if the jail name provided is a valid jail\n if(isValidJail(jail)) {\n Jail j = getJail(jail);\n\n if(j.getCellCount() == 0) {\n //There are no cells in this jail, thus we can't delete them.\n msgs.add(Lang.NOCELLS.get(j.getName()));\n }else {\n //Keep a local copy of the hashset so that we don't get any CMEs.\n HashSet<Cell> cells = new HashSet<Cell>(j.getCells());\n\n for(Cell c : cells) {\n if(c.hasPrisoner()) {\n //The cell has a prisoner, so tell them to first transfer the prisoner\n //or release the prisoner\n msgs.add(Lang.CELLREMOVALUNSUCCESSFUL.get(new String[] { c.getName(), j.getName() }));\n }else {\n j.removeCell(c.getName());\n msgs.add(Lang.CELLREMOVED.get(new String[] { c.getName(), j.getName() }));\n }\n }\n }\n }else {\n //No jail found by the provided name\n msgs.add(Lang.NOJAIL.get(jail));\n }\n\n return msgs.toArray(new String[msgs.size()]);\n }\n\n /**\n * Deletes a jail while doing some checks to verify it can be deleted.\n * \n * @param jail The name of the jail to delete.\n * @return The resulting message to be sent to the caller of this method.\n */\n public String deleteJail(String jail) {\n //Check if the jail name provided is a valid jail\n if(isValidJail(jail)) {\n //check if the jail doesn't contain prisoners\n if(getJail(jail).getAllPrisoners().size() == 0) {\n //There are no prisoners, so we can delete it\n removeJail(jail);\n return Lang.JAILREMOVED.get(jail);\n }else {\n //The jail has prisoners, they need to release them first\n return Lang.JAILREMOVALUNSUCCESSFUL.get(jail);\n }\n }else {\n //No jail found by the provided name\n return Lang.NOJAIL.get(jail);\n }\n }\n\n /**\n * Returns whether or not the player is creating a jail or a cell.\n * \n * <p>\n * \n * If you want to check to see if they're just creating a jail then use {@link #isCreatingAJail(String) isCreatingAJail} or if you want to see if they're creating a cell then use {@link #isCreatingACell(String) isCreatingACell}.\n * \n * @param name The name of the player, in any case as we convert it to lowercase.\n * @return True if the player is creating a jail or cell, false if they're not creating anything.\n */\n public boolean isCreatingSomething(String name) {\n return this.jailCreators.containsKey(name.toLowerCase()) || this.cellCreators.containsKey(name.toLowerCase());\n }\n\n /**\n * Returns a message used for telling them what they're creating and what step they're on.\n * \n * @param player the name of the player to check\n * @return The details for the step they're on\n */\n public String getStepMessage(String player) {\n String message = \"\";\n\n if(isCreatingACell(player)) {//Check whether it is a jail cell\n CreationPlayer cp = this.getCellCreationPlayer(player);\n message = \"You're already creating a Cell with the name '\" + cp.getCellName() + \"' and you still need to \";\n\n switch(cp.getStep()) {\n case 1:\n message += \"set the teleport in location.\";\n break;\n case 2:\n message += \"select all the signs.\";\n break;\n case 3:\n message += \"set the double chest location.\";\n break;\n }\n\n }else if(isCreatingAJail(player)) {//If not a cell, then check if a jail.\n CreationPlayer cp = this.getJailCreationPlayer(player);\n message = \"You're already creating a Jail with the name '\" + cp.getJailName() + \"' and you still need to \";\n\n switch(cp.getStep()) {\n case 1:\n message += \"select the first point.\";\n break;\n case 2:\n message += \"select the second point.\";\n break;\n case 3:\n message += \"set the teleport in location.\";\n break;\n case 4:\n message += \"set the release location.\";\n break;\n }\n }\n\n return message;\n }\n\n /**\n * Returns whether or not someone is creating a <strong>Jail</strong>.\n * \n * @param name the player's name to check\n * @return Whether they are creating a jail or not.\n */\n public boolean isCreatingAJail(String name) {\n return this.jailCreators.containsKey(name.toLowerCase());\n }\n\n /**\n * Method for setting a player to be creating a Jail, returns whether or not they were added successfully.\n * \n * @param player The player who is creating a jail.\n * @param jailName The name of the jail we are creating.\n * @return True if they were added successfully, false if they are already creating a Jail.\n */\n public boolean addCreatingJail(String player, String jailName) {\n if(isCreatingAJail(player)) {\n return false;\n }else {\n this.jailCreators.put(player.toLowerCase(), new CreationPlayer(jailName));\n return true;\n }\n }\n\n /**\n * Returns the instance of the CreationPlayer for this player, null if there was none found.\n * \n * @param name the player's name\n * @return gets the player's {@link CreationPlayer} instance\n */\n public CreationPlayer getJailCreationPlayer(String name) {\n return this.jailCreators.get(name.toLowerCase());\n }\n\n /**\n * Removes a CreationPlayer with the given name from the jail creators.\n * \n * @param name player's name to remove\n */\n public void removeJailCreationPlayer(String name) {\n this.jailCreators.remove(name.toLowerCase());\n }\n\n /**\n * Returns whether or not someone is creating a <strong>Cell</strong>.\n * \n * @param name the player's name to check\n * @return Whether they are creating a jail cell or not.\n */\n public boolean isCreatingACell(String name) {\n return this.cellCreators.containsKey(name.toLowerCase());\n }\n\n /**\n * Method for setting a player to be creating a Cell, returns whether or not they were added successfully.\n * \n * @param player The player who is creating a jail.\n * @param jailName The name of the jail this cell is going.\n * @param cellName The name of the cell we are creating.\n * @return True if they were added successfully, false if they are already creating a Jail.\n */\n public boolean addCreatingCell(String player, String jailName, String cellName) {\n if(isCreatingACell(player)) {\n return false;\n }else {\n this.cellCreators.put(player.toLowerCase(), new CreationPlayer(jailName, cellName));\n return true;\n }\n }\n\n /**\n * Returns the instance of the CreationPlayer for this player, null if there was none found.\n * \n * @param name the player's name to get\n * @return The player's {@link CreationPlayer} instance.\n */\n public CreationPlayer getCellCreationPlayer(String name) {\n return this.cellCreators.get(name.toLowerCase());\n }\n\n /**\n * Removes a CreationPlayer with the given name from the cell creators.\n * \n * @param name player's name to remove\n */\n public void removeCellCreationPlayer(String name) {\n this.cellCreators.remove(name.toLowerCase());\n }\n\n /**\n * Gets the instance of the {@link JailCreationSteps}.\n * \n * @return {@link JailCreationSteps} instance\n */\n public JailCreationSteps getJailCreationSteps() {\n return this.jcs;\n }\n\n /**\n * Gets the instance of the {@link CellCreationSteps}.\n * \n * @return the {@link CellCreationSteps} instance\n */\n public CellCreationSteps getCellCreationSteps() {\n return this.ccs;\n }\n\n /**\n * Adds something to the confirming list.\n * \n * @param name who to add\n * @param confirmer {@link ConfirmPlayer} of what they're confirming\n */\n public void addConfirming(String name, ConfirmPlayer confirmer) {\n getPlugin().debug(\"Adding a confirming for \" + name + \" to confirm \" + confirmer.getConfirming().toString().toLowerCase());\n this.confirms.put(name, confirmer);\n }\n\n /**\n * Removes a name from the confirming list.\n * \n * @param name who to remove\n */\n public void removeConfirming(String name) {\n this.confirms.remove(name);\n }\n\n /**\n * Checks if the given name is confirming something.\n * \n * @param name the player's name\n * @return Whether they are confirming something or not\n */\n public boolean isConfirming(String name) {\n return this.confirms.containsKey(name);\n }\n\n /**\n * Returns true if the confirmation has expired, false if it is still valid.\n * \n * @param name the player's name\n * @return Whether their confirmation has expired or not.\n */\n public boolean confirmingHasExpired(String name) {\n //If the expiry time is LESS than the current time, it has expired\n return this.confirms.get(name).getExpiryTime() < System.currentTimeMillis();\n }\n\n /**\n * Returns the original arguments for what we are confirming.\n * \n * @param name the player's name\n * @return an array of strings which is their original arguments\n */\n public String[] getOriginalArgs(String name) {\n return this.confirms.get(name).getArguments();\n }\n\n /**\n * Returns what the given name is confirming.\n * \n * @param name the player's name\n * @return What they are confirming\n */\n public Confirmation getWhatIsConfirming(String name) {\n return this.confirms.get(name).getConfirming();\n }\n}", "public class Util {\n private final static Pattern DURATION_PATTERN = Pattern.compile(\"^(\\\\d+)\\\\s*(m(?:inute)?s?|h(?:ours?)?|d(?:ays?)?|s(?:econd)?s?)?$\", Pattern.CASE_INSENSITIVE);\n private static String[] signLines = new String[] { \"\", \"\", \"\", \"\" };\n private final static int inventoryMultipule = 9;\n\n /**\n * Checks if the first {@link Vector} is inside this region.\n *\n * @param point The point to check\n * @param first point of the region\n * @param second second point of the region\n * @return True if all the coords of the first vector are in the entire region.\n */\n public static boolean isInsideAB(Vector point, Vector first, Vector second) {\n boolean x = isInside(point.getBlockX(), first.getBlockX(), second.getBlockX());\n boolean y = isInside(point.getBlockY(), first.getBlockY(), second.getBlockY());\n boolean z = isInside(point.getBlockZ(), first.getBlockZ(), second.getBlockZ());\n\n return x && y && z;\n }\n\n /**\n * Checks if two numbers are inside a point, or something.\n *\n * <p>\n *\n * @param loc The location.\n * @param first The first point\n * @param second The second point\n * @return true if they are inside, false if not.\n */\n private static boolean isInside(int loc, int first, int second) {\n int point1 = 0;\n int point2 = 0;\n if (first < second) {\n point1 = first;\n point2 = second;\n } else {\n point2 = first;\n point1 = second;\n }\n\n return point1 <= loc && loc <= point2;\n }\n\n /**\n * Checks if the given string is inside the array, ignoring the casing.\n *\n * <p />\n *\n * @param value to check\n * @param array of strings to check\n * @return true if the array contains the provided value, false if it doesn't\n */\n public static boolean isStringInsideArray(String value, String... array) {\n for(String s : array)\n if(s.equalsIgnoreCase(value))\n return true;\n\n return false;\n }\n\n /**\n * Checks if the given string is inside the list, ignoring the casing.\n *\n * <p />\n *\n * @param value to check\n * @param list of strings to check\n * @return true if the list contains the provided value, false if it doesn't\n */\n public static boolean isStringInsideList(String value, List<String> list) {\n for(String s : list)\n if(s.equalsIgnoreCase(value))\n return true;\n\n return false;\n }\n\n /**\n * Gets a single string from an array of strings, separated by the separator.\n *\n * @param separator The item to separate the items\n * @param array The array of strings to combine\n * @return the resulting combined string\n */\n public static String getStringFromArray(String separator, String... array) {\n StringBuilder result = new StringBuilder();\n\n for(String s : array) {\n if(result.length() != 0) result.append(separator);\n result.append(s);\n }\n\n return result.toString();\n }\n\n /**\n * Gets a single string from a list of strings, separated by the separator.\n *\n * @param separator The item to separate the items\n * @param list The list of strings to combine\n * @return the resulting combined string\n */\n public static String getStringFromList(String separator, List<String> list) {\n StringBuilder result = new StringBuilder();\n\n for(String s : list) {\n if(result.length() != 0) result.append(separator);\n result.append(s);\n }\n\n return result.toString();\n }\n\n /**\n * Returns a colorful message from the color codes.\n * \n * @param message the message to colorize\n * @return the colorized message\n */\n public static String getColorfulMessage(String message) {\n return ChatColor.translateAlternateColorCodes('&', message);\n }\n\n /**\n * Returns a message with all the possible variables replaced.\n * \n * @param p the {@link Prisoner} data\n * @param msg the message to replace everything in\n * @return The message with everything replaced and colorized.\n */\n public static String replaceAllVariables(Prisoner p, String msg) {\n msg = msg.replace(\"%player%\", p.getLastKnownName())\n .replace(\"%uuid%\", p.getUUID().toString())\n .replace(\"%reason%\", p.getReason())\n .replace(\"%jailer%\", p.getJailer())\n .replace(\"%afktime%\", Util.getDurationBreakdown(p.getAFKTime()));\n\n if(p.getRemainingTime() >= 0) {\n msg = msg.replace(\"%timeinminutes%\", String.valueOf(p.getRemainingTimeInMinutes()));\n msg = msg.replace(\"%prettytime%\", Util.getDurationBreakdown(p.getRemainingTime()));\n }else {\n msg = msg.replace(\"%timeinminutes%\", String.valueOf(-1));\n msg = msg.replace(\"%prettytime%\", Lang.JAILEDFOREVERSIGN.get());\n }\n\n return getColorfulMessage(msg);\n }\n\n /**\n * Replaces all the variables in the messages with their possible values.\n * \n * @param p the {@link Prisoner} data.\n * @param msgs the messages\n * @return the messages but variables replaced and colorized\n */\n public static String[] replaceAllVariables(Prisoner p, String... msgs) {\n String[] results = new String[msgs.length];\n \n for(int i = 0; i < msgs.length; i++)\n results[i] = replaceAllVariables(p, msgs[i]);\n\n return results;\n }\n\n /**\n * Returns the wand used throughout the different creation steps.\n * \n * @return The {@link ItemStack} to use for creation\n */\n public static ItemStack getWand() {\n ItemStack wand = new ItemStack(Material.BRICK);\n ItemMeta meta = wand.getItemMeta();\n meta.setDisplayName(ChatColor.AQUA + \"Jail Wand\");\n LinkedList<String> lore = new LinkedList<String>();\n lore.add(ChatColor.BLUE + \"The wand for creating\");\n lore.add(ChatColor.BLUE + \"a jail or cell.\");\n meta.setLore(lore);\n wand.setItemMeta(meta);\n\n return wand;\n }\n\n /**\n * Converts a string like '20minutes' into the appropriate amount of the given unit.\n *\n * @param time in a string to convert.\n * @param unit which to convert to.\n * @return The time in the unit given that is converted.\n * @throws Exception if there are no matches\n */\n public static Long getTime(String time, TimeUnit unit) throws Exception {\n return unit.convert(getTime(time), TimeUnit.MILLISECONDS);\n }\n\n /**\n * Converts a string like '20minutes' into the appropriate amount of milliseconds.\n *\n * @param time in a string to convert.\n * @return The time in milliseconds that is converted.\n * @throws Exception if there are no matches\n */\n public static Long getTime(String time) throws Exception {\n if(time.equalsIgnoreCase(\"-1\")) return -1L;\n\n Long t = 10L;\n Matcher match = DURATION_PATTERN.matcher(time);\n\n if (match.matches()) {\n String units = match.group(2);\n if (\"seconds\".equals(units) || \"second\".equals(units) || \"s\".equals(units))\n t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.SECONDS);\n else if (\"minutes\".equals(units) || \"minute\".equals(units) || \"mins\".equals(units) || \"min\".equals(units) || \"m\".equals(units))\n t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.MINUTES);\n else if (\"hours\".equals(units) || \"hour\".equals(units) || \"h\".equals(units))\n t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.HOURS);\n else if (\"days\".equals(units) || \"day\".equals(units) || \"d\".equals(units))\n t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.DAYS);\n else {\n try {\n t = TimeUnit.MILLISECONDS.convert(Long.parseLong(time), TimeUnit.MINUTES);\n }catch(NumberFormatException e) {\n throw new Exception(\"Invalid format.\");\n }\n }\n }else {\n throw new Exception(\"Invalid format.\");\n }\n\n return t;\n }\n\n /**\n * Convert a millisecond duration to a string format\n *\n * @param millis A duration to convert to a string form\n * @return A string of the form \"XdYhZAs\".\n */\n public static String getDurationBreakdown(long millis) {\n if(millis < 0) {\n return Lang.JAILEDFOREVERSIGN.get();\n }\n\n long days = TimeUnit.MILLISECONDS.toDays(millis);\n millis -= TimeUnit.DAYS.toMillis(days);\n long hours = TimeUnit.MILLISECONDS.toHours(millis);\n millis -= TimeUnit.HOURS.toMillis(hours);\n long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);\n millis -= TimeUnit.MINUTES.toMillis(minutes);\n long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);\n\n StringBuilder sb = new StringBuilder(64);\n if(days > 0) {\n sb.append(days);\n sb.append(\"d\");\n }\n\n if(days > 0 || hours > 0) {\n sb.append(hours);\n sb.append(\"h\");\n }\n\n if(days > 0 || hours > 0 || minutes > 0) {\n sb.append(minutes);\n sb.append(\"m\");\n }\n\n sb.append(seconds);\n sb.append(\"s\");\n\n return sb.toString();\n }\n\n /**\n * Updates the local cache of the lines which go on signs.\n *\n * @param lines array of string which go on signs, must contain exactly four.\n * @throws Exception Throws an exception if there aren't exactly four lines.\n */\n public static void updateSignLinesCache(String[] lines) throws Exception {\n if(lines.length != 4) throw new Exception(\"Exactly four lines are required for the signs.\");\n signLines = lines;\n }\n\n /**\n * Gets all the lines which go on the cell signs.\n * \n * @return the strings for the signs\n */\n public static String[] getSignLines() {\n return signLines;\n }\n \n public static List<String> getUnusedItems(List<String> items, String[] args, boolean useP) {\n List<String> used = new ArrayList<String>();\n for(String s : args)\n if(s.contains(\"-\"))\n used.add(s.replace(\"-\", \"\"));\n \n List<String> unused = new ArrayList<String>();\n for(String t : items)\n if(!used.contains(t)) //don't add it if it is already used\n if(!t.equalsIgnoreCase(\"p\") || (useP && t.equalsIgnoreCase(\"p\")))//don't add -p unless otherwise stated\n unused.add(\"-\" + t);\n \n Collections.sort(unused);\n \n return unused;\n }\n\n /**\n *\n * A method to serialize an {@link ItemStack} array to Base64 String.\n *\n * <p>\n *\n * Based off of {@link #toBase64(Inventory)}.\n *\n * @param items to turn into a Base64 String.\n * @return Base64 string of the items.\n * @throws IllegalStateException if any of the {@link ItemStack}s couldn't be parsed\n */\n public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException {\n try {\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);\n\n // Write the size of the inventory\n dataOutput.writeInt(items.length);\n\n // Save every element in the list\n for (ItemStack item : items) {\n dataOutput.writeObject(item);\n }\n\n // Serialize that array\n dataOutput.close();\n return Base64Coder.encodeLines(outputStream.toByteArray());\n } catch (Exception e) {\n throw new IllegalStateException(\"Unable to save item stacks.\", e);\n }\n }\n\n /**\n * A method to serialize an inventory to Base64 string.\n *\n * <p>\n *\n * Special thanks to Comphenix in the Bukkit forums or also known\n * as aadnk on GitHub. <a href=\"https://gist.github.com/aadnk/8138186\">Original Source</a>\n *\n * @param inventory to serialize\n * @return Base64 string of the provided inventory\n * @throws IllegalStateException if any of the {@link ItemStack}s couldn't be parsed\n */\n public static String toBase64(Inventory inventory) throws IllegalStateException {\n try {\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);\n\n // Write the size of the inventory\n dataOutput.writeInt(inventory.getSize());\n\n // Save every element in the list\n for (int i = 0; i < inventory.getSize(); i++) {\n dataOutput.writeObject(inventory.getItem(i));\n }\n\n // Serialize that array\n dataOutput.close();\n return Base64Coder.encodeLines(outputStream.toByteArray());\n } catch (Exception e) {\n throw new IllegalStateException(\"Unable to save item stacks.\", e);\n }\n }\n\n /**\n *\n * A method to get an {@link Inventory} from an encoded, Base64, string.\n *\n * <p>\n *\n * Special thanks to Comphenix in the Bukkit forums or also known\n * as aadnk on GitHub.\n *\n * <a href=\"https://gist.github.com/aadnk/8138186\">Original Source</a>\n *\n * @param data Base64 string of data containing an inventory.\n * @return Inventory created from the Base64 string.\n * @throws IOException if we were unable to parse the base64 string\n */\n public static Inventory fromBase64(String data) throws IOException {\n if(data.isEmpty()) return Bukkit.getServer().createInventory(null, 0);\n\n try {\n ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));\n BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);\n int size = dataInput.readInt();\n Inventory inventory = Bukkit.getServer().createInventory(null, (int)Math.ceil((double)size / inventoryMultipule) * inventoryMultipule);\n\n // Read the serialized inventory\n for (int i = 0; i < size; i++) {\n inventory.setItem(i, (ItemStack) dataInput.readObject());\n }\n\n dataInput.close();\n inputStream.close();\n return inventory;\n } catch (ClassNotFoundException e) {\n throw new IOException(\"Unable to decode class type.\", e);\n }\n }\n\n /**\n * Gets an array of ItemStacks from Base64 string.\n *\n * <p>\n *\n * Base off of {@link #fromBase64(String)}.\n *\n * @param data Base64 string to convert to ItemStack array.\n * @return ItemStack array created from the Base64 string.\n * @throws IOException if we was unable to parse the base64 string\n */\n public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException {\n if(data.isEmpty()) return new ItemStack[] {};\n\n try {\n ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));\n BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);\n ItemStack[] items = new ItemStack[dataInput.readInt()];\n\n // Read the serialized inventory\n for (int i = 0; i < items.length; i++) {\n items[i] = (ItemStack) dataInput.readObject();\n }\n\n dataInput.close();\n return items;\n } catch (ClassNotFoundException e) {\n throw new IOException(\"Unable to decode class type.\", e);\n }\n }\n\n public static void restoreInventory(Player player, Prisoner prisoner) {\n try {\n Inventory content = Util.fromBase64(prisoner.getInventory());\n ItemStack[] armor = Util.itemStackArrayFromBase64(prisoner.getArmor());\n\n for(ItemStack item : armor) {\n if(item == null)\n continue;\n else if(item.getType().toString().toLowerCase().contains(\"helmet\"))\n player.getInventory().setHelmet(item);\n else if(item.getType().toString().toLowerCase().contains(\"chestplate\"))\n player.getInventory().setChestplate(item);\n else if(item.getType().toString().toLowerCase().contains(\"leg\"))\n player.getInventory().setLeggings(item);\n else if(item.getType().toString().toLowerCase().contains(\"boots\"))\n player.getInventory().setBoots(item);\n else if (player.getInventory().firstEmpty() == -1)\n player.getWorld().dropItem(player.getLocation(), item);\n else\n player.getInventory().addItem(item);\n }\n\n for(ItemStack item : content.getContents()) {\n if(item == null) continue;\n else if(player.getInventory().firstEmpty() == -1)\n player.getWorld().dropItem(player.getLocation(), item);\n else\n player.getInventory().addItem(item);\n }\n } catch (IOException e) {\n e.printStackTrace();\n Bukkit.getLogger().severe(\"Unable to restore \" + player.getName() + \"'s inventory.\");\n }\n }\n\n /**\n * Checks if the provided class has the provided method.\n *\n * @param c The {@link Class} to check on.\n * @param method The name of the method to check for\n * @return whether the method exists or not.\n */\n public static boolean doesClassHaveThisMethod(Class<?> c, String method) {\n try {\n c.getMethod(method);\n return true;\n } catch (NoSuchMethodException e) {\n return true;\n } catch (SecurityException e) {\n return false;\n }\n }\n}", "public class Prisoner {\n private String uuid, name, jailer, reason, inventory, armor;\n private boolean muted = true, offlinePending = false, teleporting = false, toBeTransferred = false, changed = false;\n private long time = -1L, afk = 0L;\n private Location previousPosition;\n private GameMode previousGameMode;\n\n /**\n * Creates the prisoner instance with the lot of data provided.\n *\n * @param uuid The uuid of the prisoner\n * @param name The name of the prisoner\n * @param muted Whether the prisoner is muted or not\n * @param time The amount of remaining time the prisoner has\n * @param jailer The name of the person who jailed this prisoner\n * @param reason The reason why this prisoner is in jail\n */\n public Prisoner(String uuid, String name, boolean muted, long time, String jailer, String reason) {\n this.uuid = uuid;\n this.name = name;\n this.muted = muted;\n this.time = time;\n this.jailer = jailer;\n this.reason = reason;\n finishSetup();\n }\n\n /**\n * Creates the prisoner instance with the lot of data provided.\n *\n * @param uuid The uuid of the prisoner\n * @param name The name of the prisoner\n * @param time The amount of remaining time the prisoner has\n * @param jailer The name of the person who jailed this prisoner\n * @param reason The reason why this prisoner is in jail\n */\n public Prisoner(String uuid, String name, long time, String jailer, String reason) {\n this.uuid = uuid;\n this.name = name;\n this.time = time;\n this.jailer = jailer;\n this.reason = reason;\n finishSetup();\n }\n\n /**\n * Creates the prisoner instance with the lot of data provided.\n *\n * @param uuid The uuid of the prisoner\n * @param name The name of the prisoner\n * @param time The amount of remaining time the prisoner has\n * @param reason The reason why this prisoner is in jail\n */\n public Prisoner(String uuid, String name, long time, String reason) {\n this.uuid = uuid;\n this.name = name;\n this.time = time;\n this.reason = reason;\n finishSetup();\n }\n\n /**\n * Creates the prisoner instance with the lot of data provided.\n *\n * @param uuid The uuid of the prisoner\n * @param name The name of the prisoner\n * @param time The amount of remaining time the prisoner has\n */\n public Prisoner(String uuid, String name, long time) {\n this.uuid = uuid;\n this.name = name;\n this.time = time;\n finishSetup();\n }\n\n /**\n * Creates the prisoner instance with the data provided.\n *\n * @param player The instance of the player who is to be jailed\n * @param muted Whether the prisoner is muted or not\n * @param time The amount of remaining time the prisoner has\n * @param jailer The jailer who jailed the prisoner\n * @param reason The reason why this prisoner is in jail\n */\n public Prisoner(Player player, boolean muted, long time, String jailer, String reason) {\n this.uuid = player.getUniqueId().toString();\n this.name = player.getName();\n this.muted = muted;\n this.time = time;\n this.jailer = jailer;\n this.reason = reason;\n finishSetup();\n }\n\n /**\n * Creates the prisoner instance with the data provided.\n *\n * @param player The instance of the player who is to be jailed\n * @param time The amount of remaining time the prisoner has\n * @param jailer The jailer who jailed the prisoner\n * @param reason The reason why this prisoner is in jail\n */\n public Prisoner(Player player, long time, String jailer, String reason) {\n this.uuid = player.getUniqueId().toString();\n this.name = player.getName();\n this.time = time;\n this.jailer = jailer;\n this.reason = reason;\n finishSetup();\n }\n\n /**\n * The most basic prisoner instance creation via providing the player, time, and reason.\n *\n * @param player The instance of the player who is to be jailed\n * @param time The amount of remaining time the prisoner has\n * @param reason The reason why this prisoner is in jail\n */\n public Prisoner(Player player, long time, String reason) {\n this.uuid = player.getUniqueId().toString();\n this.name = player.getName();\n this.time = time;\n this.reason = reason;\n finishSetup();\n }\n\n /**\n * The most basic prisoner instance creation via providing the player and time.\n *\n * @param player The instance of the player who is to be jailed\n * @param time The amount of remaining time the prisoner has\n */\n public Prisoner(Player player, long time) {\n this.uuid = player.getUniqueId().toString();\n this.name = player.getName();\n this.time = time;\n finishSetup();\n }\n\n /** Finishes the setup of the prisoner data, set to defaults. */\n private void finishSetup() {\n if(jailer == null)\n jailer = Lang.DEFAULTJAILER.get();\n if(reason == null)\n Lang.DEFAULTJAILEDREASON.get();\n if(inventory == null)\n inventory = \"\";\n if(armor == null)\n armor = \"\";\n if(previousGameMode == null)\n previousGameMode = GameMode.SURVIVAL;\n previousPosition = null;\n }\n\n /** Returns the UUID of the prisoner. */\n public UUID getUUID() {\n return UUID.fromString(this.uuid);\n }\n\n /** Gets the name of this prisoner. */\n public String getLastKnownName() {\n return this.name;\n }\n\n /** Sets the name of this prisoner. */\n public String setLastKnownName(String username) {\n this.name = username;\n this.changed = true;\n return this.name;\n }\n\n /** Gets the reason this player was jailed for. */\n public String getReason() {\n return this.reason;\n }\n\n /**\n * Sets the reason this player was jailed for.\n *\n * @param reason the player was jailed.\n * @return the reason the player was jailed, what we have stored about them.\n */\n public String setReason(String reason) {\n this.reason = reason;\n this.changed = true;\n return this.reason;\n }\n\n /** Gets the person who jailed this prisoner. */\n public String getJailer() {\n return this.jailer;\n }\n\n /** Sets the person who jailed this prisoner. */\n public void setJailer(String jailer) {\n this.jailer = jailer;\n this.changed = true;\n }\n\n /** Gets whether the prisoner is muted or not. */\n public boolean isMuted() {\n return this.muted;\n }\n\n /** Sets whether the prisoner is muted or not. */\n public void setMuted(boolean muted) {\n this.muted = muted;\n this.changed = true;\n }\n \n /** Gets whether the prisoner is jailed forever or not. */\n public boolean isJailedForever() {\n return this.time == -1;\n }\n\n /** Gets the remaining time the prisoner has. */\n public long getRemainingTime() {\n return this.time;\n }\n\n /** Gets the remaining time the prisoner has in minutes. */\n public long getRemainingTimeInMinutes() {\n return TimeUnit.MINUTES.convert(time, TimeUnit.MILLISECONDS);\n }\n\n /** Gets the remaining time the prison has in minutes except only in int format. */\n public int getRemainingTimeInMinutesInt() {\n return (int) this.getRemainingTimeInMinutes();\n }\n\n /**\n * Sets the remaining time the prisoner has left.\n *\n * @param time The amount of time left, in milliseconds.\n */\n public void setRemainingTime(long time) {\n this.time = time;\n this.changed = true;\n }\n\n /**\n * Adds the given time to the remaining time the prisoner has left, unless they're jailed forever.\n *\n * @param time to add to the prisoner's remaining time.\n * @return the new remaining time the prisoner has\n */\n public long addTime(long time) {\n if(this.time != -1L) {\n this.time += time;\n this.changed = true;\n }\n\n return this.time;\n }\n\n /**\n * Subtracts the given time from the remaining time the prisoner has left, unless they're jailed forever.\n *\n * @param time to subtract from the prisoner's remaining time.\n * @return the new remaining time the prisoner has\n */\n public long subtractTime(long time) {\n if(this.time != -1L) {\n this.time -= time;\n this.changed = true;\n }\n\n return this.time;\n }\n\n /** Gets whether the player is offline or not. */\n public boolean isOfflinePending() {\n return this.offlinePending;\n }\n\n /** Sets whether the player is offline or not. */\n public void setOfflinePending(boolean offline) {\n this.offlinePending = offline;\n this.changed = true;\n }\n\n /** Gets whether the player is being teleported or not. */\n public boolean isTeleporting() {\n return this.teleporting;\n }\n\n /** Sets whether the player is being teleported or not. */\n public void setTeleporting(boolean teleport) {\n this.teleporting = teleport;\n }\n\n /** Gets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */\n public boolean isToBeTransferred() {\n return this.toBeTransferred;\n }\n\n /** Sets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */\n public void setToBeTransferred(boolean transferred) {\n this.toBeTransferred = transferred;\n this.changed = true;\n }\n\n /** Gets the previous location of this player, can be null. */\n public Location getPreviousLocation() {\n return this.previousPosition;\n }\n\n /** Gets the previous location of this player, separated by a comma. */\n public String getPreviousLocationString() {\n if(previousPosition == null) return \"\";\n else if(previousPosition.getWorld() == null) return \"\";\n else return previousPosition.getWorld().getName() + \",\" +\n previousPosition.getX() + \",\" +\n previousPosition.getY() + \",\" +\n previousPosition.getZ() + \",\" +\n previousPosition.getYaw() + \",\" +\n previousPosition.getPitch();\n }\n\n /** Sets the previous location of this player. */\n public void setPreviousPosition(Location location) {\n this.previousPosition = location;\n }\n\n /** Sets the previous location of this player from a comma separated string. */\n public void setPreviousPosition(String location) {\n if(location == null) return;\n if(location.isEmpty()) return;\n\n this.changed = true;\n String[] s = location.split(\",\");\n this.previousPosition = new Location(Bukkit.getWorld(s[0]),\n Double.valueOf(s[1]),\n Double.valueOf(s[2]),\n Double.valueOf(s[3]),\n Float.valueOf(s[4]),\n Float.valueOf(s[5]));\n }\n\n /** Gets the previous gamemode of this player. */\n public GameMode getPreviousGameMode() {\n return this.previousGameMode;\n }\n\n /** Sets the previous gamemode of this player. */\n public void setPreviousGameMode(GameMode previous) {\n this.previousGameMode = previous;\n this.changed = true;\n }\n\n /** Sets the previous gamemode of this player based upon the provided string. */\n public void setPreviousGameMode(String previous) {\n if(previous == null) return;\n else if(previous.isEmpty()) return;\n else this.previousGameMode = GameMode.valueOf(previous);\n this.changed = true;\n }\n\n /** Gets the inventory string for this player, it is encoded in Base64 string. */\n public String getInventory() {\n return this.inventory;\n }\n\n /** Sets the inventory Base64 string. */\n public void setInventory(String inventory) {\n this.inventory = inventory;\n this.changed = true;\n }\n\n /** Gets the armor content, encoded in Base64 string. */\n public String getArmor() {\n return this.armor;\n }\n\n /** Sets the armor inventory Base64 string. */\n public void setArmor(String armor) {\n this.armor = armor;\n this.changed = true;\n }\n\n /** Gets the time, in milliseconds, this prisoner has been afk. */\n public long getAFKTime() {\n return this.afk;\n }\n\n /** Sets the time, in milliseconds, this prisoner has been afk. */\n public void setAFKTime(long time) {\n this.afk = time;\n }\n\n /** Checks if the prisoner was changed or not. */\n public boolean wasChanged() {\n return this.changed;\n }\n\n /** Sets whether the prisoner was changed or not. */\n public boolean setChanged(boolean change) {\n this.changed = change;\n return this.changed;\n }\n}", "public interface Command {\n /**\n * Execute the command given the arguments, returning whether the command handled it or not.\n * \n * <p>\n * \n * When the method returns false, the usage message is printed to the sender. If the method\n * handles the command in any way, such as sending a message to the sender or actually doing\n * something, then it should return true so that the sender of the command doesn't get the\n * usage message.\n * \n * @param jm An instance of the {@link JailManager}\n * @param sender The {@link CommandSender sender} of the command\n * @param args The args, in an array\n * @return True if the method handled it in any way, false if we should send the usage message.\n */\n public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception;\n \n public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception;\n}", "public enum Lang {\n // actions section\n /** Section for when they break a block. */\n BLOCKBREAKING(\"actions\"),\n /** Section for when they place a block. */\n BLOCKPLACING(\"actions\"),\n /** Section for when they try to do a command that isn't whitelisted. */\n COMMAND(\"actions\"),\n /** Section for when a player tramples a crop and protection is enabled. */\n CROPTRAMPLING(\"actions\"),\n /** Section for when a player interacts with a block that is blacklisted. */\n INTERACTIONBLOCKS(\"actions\"),\n /** Section for when a player interacts with an item that is blacklisted. */\n INTERACTIONITEMS(\"actions\"),\n /** Section for when a player moves outside of the jail. */\n MOVING(\"actions\"),\n\n // Jailing section\n /** The message displayed when players are kicked for being afk. */\n AFKKICKMESSAGE(\"jailing\"),\n /** The message sent when jailing someone that is already jailed. */\n ALREADYJAILED(\"jailing\"),\n /** The message sent when we broadcast/log the message for time below -1. */\n BROADCASTMESSAGEFOREVER(\"jailing\"),\n /** The message sent when we broadcast/log the message for any time above -1. */\n BROADCASTMESSAGEFORMINUTES(\"jailing\"),\n /** The message sent to the broadcast/log the unjailing of someone. */\n BROADCASTUNJAILING(\"jailing\"),\n /** The message sent to the sender when trying to jail someone and a plugin cancels it but doesn't leave a message why. */\n CANCELLEDBYANOTHERPLUGIN(\"jailing\"),\n /** The message sent when trying to jail someone who can't be jailed by permission. */\n CANTBEJAILED(\"jailing\"),\n /** The message sent to the sender when they are trying to jail into a cell which is not empty. */\n CELLNOTEMPTY(\"jailing\"),\n /** The jailer set whenever a jailer is not provided. */\n DEFAULTJAILER(\"jailing\"),\n /** The message sent when someone is jailed without a reason. */\n DEFAULTJAILEDREASON(\"jailing\"),\n /** The message sent when someone is unjailed yet they never came online and so they were forcefully unjailed. */\n FORCEUNJAILED(\"jailing\"),\n /** The message sent when players are jailed without a reason. */\n JAILED(\"jailing\"),\n /** The message sent when players are jailed with a reason. */\n JAILEDWITHREASON(\"jailing\"),\n /** The message sent when players are jailed and they try to talk. */\n MUTED(\"jailing\"),\n /** The message sent when the sender tries to jail someone in a cell and there aren't any cells to suggest. */\n NOEMPTYCELLS(\"jailing\"),\n /** The message sent to the sender when they list all the prisoners in a jail which has no prisoners. */\n NOPRISONERS(\"jailing\"),\n /** The message sent when a player is not jailed and the sender is trying to see/do something about it. */\n NOTJAILED(\"jailing\"),\n /** The message sent to the sender when they mute a prisoner. */\n NOWMUTED(\"jailing\"),\n /** The message sent to the sender when they unmute a prisoner. */\n NOWUNMUTED(\"jailing\"),\n /** The message sent to the jailer when they jail someone offline. */\n OFFLINEJAIL(\"jailing\"),\n /** The message sent to the jailer when they jail someone who is online. */\n ONLINEJAIL(\"jailing\"),\n /** The message sent to the jailer when they jail someone who has never played before. */\n PLAYERHASNEVERPLAYEDBEFORE(\"jailing\"),\n /** The message sent when finding out how much time a prisoner has. */\n PRISONERSTIME(\"jailing\"),\n /** The message sent to the prisoner when they try to do something but it is protected. */\n PROTECTIONMESSAGE(\"jailing\"),\n /** The message sent to the prisoner when they try to do something and it is protected, but no penalty. */\n PROTECTIONMESSAGENOPENALTY(\"jailing\"),\n /** The message sent to the sender when they need to provide a player. */\n PROVIDEAPLAYER(\"jailing\"),\n /** The message sent to the sender when they need to provide a jail. */\n PROVIDEAJAIL(\"jailing\"),\n /** The message sent to someone trying to jail someone else with a jail stick that requires health below a certain amount. */\n RESISTEDARRESTJAILER(\"jailing\"),\n /** The message sent to the person someone else is trying to jail that requires their health below a certain amount. */\n RESISTEDARRESTPLAYER(\"jailing\"),\n /** The message sent when to a prisoner about their status in jail. */\n STATUS(\"jailing\"),\n /** The message sent to the sender of a command when suggesting a cell. */\n SUGGESTEDCELL(\"jailing\"),\n /** The message sent to the sender when they teleport someone to a jail's teleport in location. */\n TELEIN(\"jailing\"),\n /** The message sent to the sender when they teleport someone to a jail's teleport out location. */\n TELEOUT(\"jailing\"),\n /** The message sent to the sender when they transfer all a jail's prisoners to another jail. */\n TRANSFERALLCOMPLETE(\"jailing\"),\n /** The message sent when another plugin cancels the transferring but doesn't provide a reason why. */\n TRANSFERCANCELLEDBYANOTHERPLUGIN(\"jailing\"),\n /** The message sent to the sender when they transfer someone to a jail and a cell. */\n TRANSFERCOMPLETECELL(\"jailing\"),\n /** The message sent to the sender when they transfer someone to a jail. */\n TRANSFERCOMPLETENOCELL(\"jailing\"),\n /** The message sent to the player when they get transferred to a new jail. */\n TRANSFERRED(\"jailing\"),\n /** The message sent when players are released from jail. */\n UNJAILED(\"jailing\"),\n /** The message sent to the person who released a prisoner from jail. */\n UNJAILSUCCESS(\"jailing\"),\n /** The message sent when you jailing offline players is not allowed. */\n UNALLOWEDTOJAILOFFLINE(\"jailing\"),\n /** The message went when an offline player is unjailed. */\n WILLBEUNJAILED(\"jailing\"),\n /** The message sent when trying to jail a player in an unloaded world. */\n WORLDUNLOADED(\"jailing\"),\n /** The message sent when a player joins and is jailed in a world that is unloaded. */\n WORLDUNLOADEDKICK(\"jailing\"),\n /** The message sent to the sender when they check their jail status and they aren't jailed. */\n YOUARENOTJAILED(\"jailing\"),\n\n // Handcuffing section\n /** The message sent to the sender when trying to handcuff someone who can't be. */\n CANTBEHANDCUFFED(\"handcuffing\"),\n /** The message sent to the sender whenever they try to handcuff someone who is in jail. */\n CURRENTLYJAILEDHANDCUFF(\"handcuffing\", \"currentlyjailed\"),\n /** The message sent to the sender when the player doesn't have any handcuffs. */\n NOTHANDCUFFED(\"handcuffing\"),\n /** The message sent to the handcuff on a successful handcuffing. */\n HANDCUFFSON(\"handcuffing\"),\n /** The message sent when players are handcuffed. */\n HANDCUFFED(\"handcuffing\"),\n /** The message sent to the player who has release handcuffs. */\n HANDCUFFSRELEASED(\"handcuffing\"),\n /** The message sent when the player has his/her handcuffs removed. */\n UNHANDCUFFED(\"handcuffing\"),\n\n // General section, used by different parts\n /** Part message of any messages which require 'all the jails' or such. */\n ALLJAILS(\"general\"),\n /** The one line on signs when the cell is empty. */\n CELLEMPTYSIGN(\"general\"),\n /** The message sent to the sender whenever they try to remove a cell but was unsuccessful due to a prisoner. */\n CELLREMOVALUNSUCCESSFUL(\"general\"),\n /** The message sent whenever a cell is successfully removed. */\n CELLREMOVED(\"general\"),\n /** The message sent when cleaning our cell signs. */\n CLEANEDSIGNS(\"general\"),\n /** The message sent when seeing what signs are invalid. */\n INVALIDSIGNS(\"general\"),\n /** The line on a cell's sign when the prisoner is jailed forever. */\n JAILEDFOREVERSIGN(\"general\"),\n /** The simple word jailing to be put in other parts. */\n JAILING(\"general\"),\n /** The message sent to the sender when they try to remove a jail but there are still prisoners in there. */\n JAILREMOVALUNSUCCESSFUL(\"general\"),\n /** The message sent whenever a jail is successfully removed. */\n JAILREMOVED(\"general\"),\n /** The message sent whenever a player toggles using jail stick to disabled. */\n JAILSTICKDISABLED(\"general\"),\n /** The message sent whenever a player toggles using jail stick to enabled. */\n JAILSTICKENABLED(\"general\"),\n /** The message sent whenever a player tries to toggle using jail stick but the config has it disabled. */\n JAILSTICKUSAGEDISABLED(\"general\"),\n /** Message sent when doing something that requires a cell but the given name of a cell doesn't exist. */\n NOCELL(\"general\"),\n /** Message sent when needing a cell or something and there are no cells. */\n NOCELLS(\"general\"),\n /** Message sent when no invalid signs were found. */\n NOINVALIDSIGNS(\"general\"),\n /** The message sent whenever the sender does something which the jail does not found. */\n NOJAIL(\"general\"),\n /** The message sent whenever the sender does something and there are no jails. */\n NOJAILS(\"general\"),\n /** The message sent whenever the sender/player doesn't have permission. */\n NOPERMISSION(\"general\"),\n /** The message sent whenever the sender/player supplies a number format that is incorrect. */\n NUMBERFORMATINCORRECT(\"general\"),\n /** The message sent whenever something is done that needs a player but doesn't have it. */\n PLAYERCONTEXTREQUIRED(\"general\"),\n /** The message sent whenever an online player is required but not found. */\n PLAYERNOTONLINE(\"general\"),\n /** The message sent to the sender when the plugin data has been reloaded. */\n PLUGINRELOADED(\"general\"),\n /** The message sent to the sender of a command when the plugin didn't start correct. */\n PLUGINNOTLOADED(\"general\"),\n /** The message sent whenever the prisoners are cleared from jail(s). */\n PRISONERSCLEARED(\"general\"),\n /** The format we should use when entering a record into flatfile or showing it. */\n RECORDENTRY(\"general\"),\n /** The message format sent saying how many times a user has been jailed. */\n RECORDTIMESJAILED(\"general\"),\n /** The simple word: sign. */\n SIGN(\"general\"),\n /** The message sent when the signs are refreshed. */\n SIGNSREFRESHED(\"general\"),\n /** The format of the time entry we should use for the record entries. */\n TIMEFORMAT(\"general\"),\n /** The simple word transferring to be put in other parts. */\n TRANSFERRING(\"general\"),\n /** The message sent whenever someone does a command we don't know. */\n UNKNOWNCOMMAND(\"general\"),\n\n // Jail pay\n /** The message sent when the jail pay portion is not enabled. */\n PAYNOTENABLED(\"jailpay\", \"notenabled\"),\n /** The message sent when finding out how much it costs. */\n PAYCOST(\"jailpay\", \"cost\"),\n /** The message sent when finding out how much it costs and they are jailed forever. */\n PAYCOSTINFINITE(\"jailpay\", \"costinfinite\"),\n /** The message sent when someone tries to pay a negative amount. */\n PAYNONEGATIVEAMOUNTS(\"jailpay\", \"nonegativeamounts\"),\n /** The message sent when someone is jailed and tries to pay for someone else. */\n PAYCANTPAYWHILEJAILED(\"jailpay\", \"cantpayforotherswhilejailed\"),\n /** The message sent whenever someone tries to pay an amount they don't have. */\n PAYNOTENOUGHMONEY(\"jailpay\", \"notenoughmoney\"),\n /** The message sent when they try to pay an amount but it isn't enough for the jailing sentence. */\n PAYNOTENOUGHMONEYPROVIDED(\"jailpay\", \"notenoughmoneyprovided\"),\n /** The message sent when they pay and get released. */\n PAYPAIDRELEASED(\"jailpay\", \"paidreleased\"),\n /** The message sent when they pay for someone else and release them. */\n PAYPAIDRELEASEDELSE(\"jailpay\", \"paidreleasedelse\"),\n /** The message sent when they pay and lower their time. */\n PAYPAIDLOWEREDTIME(\"jailpay\", \"paidloweredtime\"),\n /** The message sent when they pay and lower someone else's time. */\n PAYPAIDLOWEREDTIMEELSE(\"jailpay\", \"paidloweredtimeelse\"),\n\n // Jail vote\n /** The header sent when broadcasting a new jail vote. */\n VOTEBROADCASTHEADER(\"jailvote.broadcast\", \"header\"),\n /** The footer sent when broadcasting a new jail vote. */\n VOTEBROADCASTFOOTER(\"jailvote.broadcast\", \"footer\"),\n /** Line1 of the broadcast message sent when a new jail vote is happening. */\n VOTEBROADCASTLINE1(\"jailvote.broadcast\", \"line1\"),\n /** Line2 of the broadcast message sent when a new jail vote is happening. */\n VOTEBROADCASTLINE2(\"jailvote.broadcast\", \"line2\"),\n /** Line3 of the broadcast message sent when a new jail vote is happening. */\n VOTEBROADCASTLINE3(\"jailvote.broadcast\", \"line3\"),\n /** Line4 of the broadcast message sent when a new jail vote is happening. */\n VOTEBROADCASTLINE4(\"jailvote.broadcast\", \"line4\"),\n /** The message sent when someone tries to vote for a player when a vote isn't running. */\n VOTENOVOTEFORTHATPLAYER(\"jailvote\", \"novotegoingforthatplayer\"),\n /** The message sent to a player who tries to start a vote to jail someone and doesn't have permission. */\n VOTENOPERMISSIONTOSTART(\"jailvote\", \"nopermissiontostartvote\"),\n /** The message sent when jail vote is not enabled. */\n VOTENOTENABLED(\"jailvote\", \"notenabled\"),\n /** The message sent whenever someone's vote is not successful. */\n VOTEUNSUCCESSFUL(\"jailvote\", \"voteunsuccessful\"),\n /** The message sent whenever a player successfully votes no. */\n VOTENOSUCCESS(\"jailvote\", \"votenosuccessful\"),\n /** The message sent whenever a player successfully votes yes. */\n VOTEYESSUCCESS(\"jailvote\", \"voteyessuccessful\"),\n /** The message broadcasted whenever a vote is tied. */\n VOTESTIED(\"jailvote\", \"votestied\"),\n /** The message broadcasted whenever there are more no votes. */\n VOTESSAIDNO(\"jailvote\", \"morenovotes\"),\n /** The message broadcasted whenever there aren't the minimum yes votes. */\n VOTESNOTENOUGHYES(\"jailvote\", \"notenoughyes\"),\n /** The message broadcasted whenever the player the vote is for is no longer online. */\n VOTEPLAYERNOLONGERONLINE(\"jailvote\", \"playernolongeronline\"),\n /** The message sent when a player tries to vote again for someone. */\n VOTEALREADYVOTEDFOR(\"jailvote\", \"alreadyvotedfor\"),\n\n // Confirming action messages.\n /** The message sent when the sender is already confirming something. */\n ALREADY(\"confirm\"),\n /** The message sent when their confirmation has expired. */\n EXPIRED(\"confirm\"),\n /** The message sent to the sender when they tried to confirm something but don't have anything to confirm. */\n NOTHING(\"confirm\"),\n /** The message sent to the sender when they type something and need to confirm it. */\n START(\"confirm\");\n\n private String section, name, path;\n private static YamlConfiguration lang;\n\n Lang(String section) {\n this.section = section;\n this.name = toString().toLowerCase();\n this.path = \"language.\" + this.section + \".\" + this.name;\n }\n\n Lang(String section, String name) {\n this.section = section;\n this.name = name;\n this.path = \"language.\" + this.section + \".\" + this.name;\n }\n\n /**\n * Sets the {@link YamlConfiguration} instance to use.\n *\n * @param file\n * of the language to use.\n */\n public static void setFile(YamlConfiguration file) {\n lang = file;\n }\n\n /** Gets the {@link YamlConfiguration} instance. */\n public static YamlConfiguration getFile() {\n return lang;\n }\n\n /** Writes any new language settings to the language file in storage. */\n public static boolean writeNewLanguage(YamlConfiguration newLang) {\n boolean anything = false;\n\n for(Lang l : values()) {\n if(!lang.contains(l.path)) {\n lang.set(l.path, newLang.getString(l.path));\n anything = true;\n }\n }\n\n return anything;\n }\n\n /** Returns the message in the language, no variables are replaced. */\n public String get() {\n return get(new String[] {});\n }\n\n /** Returns the message in the language, no variables are replaced. */\n public String get(Lang langString) {\n return get(new String[] { langString.get() });\n }\n\n /**\n * Returns the message in the language, with the provided variables being replaced.\n *\n * @param variables\n * All the variables to replace, in order from 0 to however many.\n * @return The message as a colorful message or an empty message if that\n * isn't defined in the language file.\n */\n public String get(String... variables) {\n String message = lang.getString(path);\n\n if (message == null) return \"\";\n\n for (int i = 0; i < variables.length; i++) {\n message = message.replaceAll(\"%\" + i + \"%\", variables[i]);\n }\n\n return ChatColor.translateAlternateColorCodes('&', message);\n }\n}" ]
import java.util.Collections; import java.util.List; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.graywolf336.jail.JailManager; import com.graywolf336.jail.Util; import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang;
package com.graywolf336.jail.command.subcommands; @CommandInfo( maxArgs = 0, minimumArgs = 0, needsPlayer = true, pattern = "status|s", permission = "jail.usercmd.jailstatus", usage = "/jail status" )
public class JailStatusCommand implements Command{
3
gomathi/merkle-tree
test/org/hashtrees/test/HashTreesStoreTest.java
[ "@ThreadSafe\npublic class HashTreesMemStore extends HashTreesBaseStore {\n\n\tprivate final ConcurrentMap<Long, HashTreeMemStore> treeIdAndIndHashTree = new ConcurrentHashMap<>();\n\n\tprivate static class HashTreeMemStore {\n\t\tprivate final ConcurrentMap<Integer, ByteBuffer> segmentHashes = new ConcurrentSkipListMap<Integer, ByteBuffer>();\n\t\tprivate final ConcurrentSkipListMap<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>> segDataBlocks = new ConcurrentSkipListMap<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>>();\n\t\tprivate final AtomicLong lastRebuiltTS = new AtomicLong(0);\n\t\tprivate final AtomicBitSet markedSegments = new AtomicBitSet();\n\t}\n\n\tprivate HashTreeMemStore getIndHTree(long treeId) {\n\t\tif (!treeIdAndIndHashTree.containsKey(treeId))\n\t\t\ttreeIdAndIndHashTree.putIfAbsent(treeId, new HashTreeMemStore());\n\t\treturn treeIdAndIndHashTree.get(treeId);\n\t}\n\n\t@Override\n\tpublic SegmentData getSegmentData(long treeId, int segId, ByteBuffer key) {\n\t\tConcurrentSkipListMap<ByteBuffer, ByteBuffer> segDataBlock = getIndHTree(treeId).segDataBlocks\n\t\t\t\t.get(segId);\n\t\tif (segDataBlock != null) {\n\t\t\tByteBuffer value = segDataBlock.get(key);\n\t\t\tif (value != null) {\n\t\t\t\tByteBuffer intKey = ByteBuffer.wrap(key.array());\n\t\t\t\treturn new SegmentData(segId, intKey, value);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void putSegmentData(long treeId, int segId, ByteBuffer key,\n\t\t\tByteBuffer digest) {\n\t\tHashTreeMemStore hTreeStore = getIndHTree(treeId);\n\t\tif (!hTreeStore.segDataBlocks.containsKey(segId))\n\t\t\thTreeStore.segDataBlocks.putIfAbsent(segId,\n\t\t\t\t\tnew ConcurrentSkipListMap<ByteBuffer, ByteBuffer>());\n\t\thTreeStore.segDataBlocks.get(segId).put(key.duplicate(),\n\t\t\t\tdigest.duplicate());\n\t}\n\n\t@Override\n\tpublic void deleteSegmentData(long treeId, int segId, ByteBuffer key) {\n\t\tHashTreeMemStore indPartition = getIndHTree(treeId);\n\t\tMap<ByteBuffer, ByteBuffer> segDataBlock = indPartition.segDataBlocks\n\t\t\t\t.get(segId);\n\t\tif (segDataBlock != null)\n\t\t\tsegDataBlock.remove(key.duplicate());\n\t}\n\n\t@Override\n\tpublic List<SegmentData> getSegment(long treeId, int segId) {\n\t\tHashTreeMemStore indPartition = getIndHTree(treeId);\n\t\tConcurrentMap<ByteBuffer, ByteBuffer> segDataBlock = indPartition.segDataBlocks\n\t\t\t\t.get(segId);\n\t\tif (segDataBlock == null)\n\t\t\treturn Collections.emptyList();\n\t\tList<SegmentData> result = new ArrayList<SegmentData>();\n\t\tfor (Map.Entry<ByteBuffer, ByteBuffer> entry : segDataBlock.entrySet())\n\t\t\tresult.add(new SegmentData(segId, entry.getKey(), entry.getValue()));\n\t\treturn result;\n\t}\n\n\t/**\n\t * Iterator returned by this method is not thread safe.\n\t */\n\t@Override\n\tpublic Iterator<SegmentData> getSegmentDataIterator(long treeId) {\n\t\tfinal HashTreeMemStore memStore = getIndHTree(treeId);\n\t\tfinal Iterator<Map.Entry<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>>> dataBlocksItr = memStore.segDataBlocks\n\t\t\t\t.entrySet().iterator();\n\t\treturn convertMapEntriesToSegmentData(dataBlocksItr);\n\t}\n\n\t@Override\n\tpublic Iterator<SegmentData> getSegmentDataIterator(long treeId,\n\t\t\tint fromSegId, int toSegId) throws IOException {\n\t\tfinal HashTreeMemStore memStore = getIndHTree(treeId);\n\t\tfinal Iterator<Map.Entry<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>>> dataBlocksItr = memStore.segDataBlocks\n\t\t\t\t.subMap(fromSegId, true, toSegId, true).entrySet().iterator();\n\t\treturn convertMapEntriesToSegmentData(dataBlocksItr);\n\t}\n\n\tprivate static Iterator<SegmentData> convertMapEntriesToSegmentData(\n\t\t\tfinal Iterator<Map.Entry<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>>> dataBlocksItr) {\n\t\treturn new Iterator<SegmentData>() {\n\n\t\t\tvolatile int segId;\n\t\t\tvolatile Iterator<Map.Entry<ByteBuffer, ByteBuffer>> itr = null;\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\tif (itr == null || !itr.hasNext()) {\n\t\t\t\t\twhile (dataBlocksItr.hasNext()) {\n\t\t\t\t\t\tMap.Entry<Integer, ConcurrentSkipListMap<ByteBuffer, ByteBuffer>> entry = dataBlocksItr\n\t\t\t\t\t\t\t\t.next();\n\t\t\t\t\t\tsegId = entry.getKey();\n\t\t\t\t\t\titr = entry.getValue().entrySet().iterator();\n\t\t\t\t\t\tif (itr.hasNext())\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn (itr != null) && itr.hasNext();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic SegmentData next() {\n\t\t\t\tif (itr == null || !itr.hasNext())\n\t\t\t\t\tthrow new NoSuchElementException(\n\t\t\t\t\t\t\t\"No more elements exist to return.\");\n\t\t\t\tMap.Entry<ByteBuffer, ByteBuffer> entry = itr.next();\n\t\t\t\treturn new SegmentData(segId, entry.getKey(), entry.getValue());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void remove() {\n\t\t\t\tthrow new UnsupportedOperationException();\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic void putSegmentHash(long treeId, int nodeId, ByteBuffer digest) {\n\t\tHashTreeMemStore indPartition = getIndHTree(treeId);\n\t\tindPartition.segmentHashes.put(nodeId, digest.duplicate());\n\t}\n\n\t@Override\n\tpublic SegmentHash getSegmentHash(long treeId, int nodeId) {\n\t\tHashTreeMemStore indPartition = getIndHTree(treeId);\n\t\tByteBuffer hash = indPartition.segmentHashes.get(nodeId);\n\t\tif (hash == null)\n\t\t\treturn null;\n\t\treturn new SegmentHash(nodeId, hash);\n\t}\n\n\t@Override\n\tpublic List<SegmentHash> getSegmentHashes(long treeId,\n\t\t\tCollection<Integer> nodeIds) {\n\t\tList<SegmentHash> result = new ArrayList<SegmentHash>();\n\t\tfor (int nodeId : nodeIds) {\n\t\t\tByteBuffer hash = getIndHTree(treeId).segmentHashes.get(nodeId);\n\t\t\tif (hash != null)\n\t\t\t\tresult.add(new SegmentHash(nodeId, hash));\n\t\t}\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic void setCompleteRebuiltTimestamp(long treeId, long timestamp) {\n\t\tHashTreeMemStore indTree = getIndHTree(treeId);\n\t\tindTree.lastRebuiltTS.set(timestamp);\n\t}\n\n\t@Override\n\tpublic long getCompleteRebuiltTimestamp(long treeId) {\n\t\tlong value = getIndHTree(treeId).lastRebuiltTS.get();\n\t\treturn value;\n\t}\n\n\t@Override\n\tpublic void deleteTree(long treeId) {\n\t\ttreeIdAndIndHashTree.remove(treeId);\n\t}\n\n\t@Override\n\tpublic void markSegments(long treeId, List<Integer> segIds) {\n\t\tfor (int segId : segIds)\n\t\t\tgetIndHTree(treeId).markedSegments.set(segId);\n\t}\n\n\t@Override\n\tpublic void unmarkSegments(long treeId, List<Integer> segIds) {\n\t\tgetIndHTree(treeId).markedSegments.clearBits(segIds);\n\t}\n\n\t@Override\n\tpublic List<Integer> getMarkedSegments(long treeId) {\n\t\treturn getIndHTree(treeId).markedSegments.getAllSetBits();\n\t}\n\n\t@Override\n\tpublic void stop() {\n\t\t// Nothing to stop.\n\t}\n\n\t@Override\n\tpublic void start() {\n\t\t// Nothing to initialize\n\t}\n\n\t@Override\n\tprotected void setDirtySegmentInternal(long treeId, int segId) {\n\t\t// Nothing to do.\n\t}\n\n\t@Override\n\tprotected void clearDirtySegmentInternal(long treeId, int segId) {\n\t\t// Nothing to do.\n\t}\n\n\t@Override\n\tprotected List<Integer> getDirtySegmentsInternal(long treeId) {\n\t\treturn Collections.emptyList();\n\t}\n}", "public class HashTreesPersistentStore extends HashTreesBaseStore {\n\n\tprivate static final Logger LOG = LoggerFactory\n\t\t\t.getLogger(HashTreesPersistentStore.class);\n\tprivate static final byte[] EMPTY_VALUE = new byte[0];\n\n\tprivate final String dbDir;\n\tprivate final DB dbObj;\n\n\tpublic HashTreesPersistentStore(String dbDir) throws IOException {\n\t\tthis.dbDir = dbDir;\n\t\tthis.dbObj = initDB(dbDir);\n\t}\n\n\tprivate static boolean createDir(String dirName) {\n\t\tFile file = new File(dirName);\n\t\tif (file.exists())\n\t\t\treturn true;\n\t\treturn file.mkdirs();\n\t}\n\n\tprivate static DB initDB(String dbDir) throws IOException {\n\t\tcreateDir(dbDir);\n\t\tOptions options = new Options();\n\t\toptions.createIfMissing(true);\n\t\treturn new JniDBFactory().open(new File(dbDir), options);\n\t}\n\n\tpublic String getDbDir() {\n\t\treturn dbDir;\n\t}\n\n\t@Override\n\tprotected void setDirtySegmentInternal(long treeId, int segId) {\n\t\tdbObj.put(generateDirtySegmentKey(treeId, segId), EMPTY_VALUE);\n\t}\n\n\t@Override\n\tprotected void clearDirtySegmentInternal(long treeId, int segId) {\n\t\tbyte[] key = generateDirtySegmentKey(treeId, segId);\n\t\tdbObj.delete(key);\n\t}\n\n\t@Override\n\tprotected List<Integer> getDirtySegmentsInternal(long treeId) {\n\t\tDBIterator itr = dbObj.iterator();\n\t\tbyte[] prefixKey = generateBaseKey(BaseKey.DIRTY_SEG, treeId);\n\t\titr.seek(prefixKey);\n\t\tIterator<Integer> dirtySegmentsItr = new DataFilterableIterator<>(\n\t\t\t\tprefixKey, true, KVBYTES_TO_SEGID_CONVERTER, itr);\n\t\tList<Integer> dirtySegments = new ArrayList<>();\n\t\twhile (dirtySegmentsItr.hasNext()) {\n\t\t\tInteger treeIdAndDirtySeg = dirtySegmentsItr.next();\n\t\t\tdirtySegments.add(treeIdAndDirtySeg);\n\t\t}\n\t\treturn dirtySegments;\n\t}\n\n\t@Override\n\tpublic void putSegmentHash(long treeId, int nodeId, ByteBuffer digest) {\n\t\tdbObj.put(generateSegmentHashKey(treeId, nodeId), digest.array());\n\t}\n\n\t@Override\n\tpublic SegmentHash getSegmentHash(long treeId, int nodeId) {\n\t\tbyte[] value = dbObj.get(generateSegmentHashKey(treeId, nodeId));\n\t\tif (value != null)\n\t\t\treturn new SegmentHash(nodeId, ByteBuffer.wrap(value));\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic List<SegmentHash> getSegmentHashes(long treeId,\n\t\t\tCollection<Integer> nodeIds) {\n\t\tList<SegmentHash> result = new ArrayList<SegmentHash>();\n\t\tSegmentHash temp;\n\t\tfor (int nodeId : nodeIds) {\n\t\t\ttemp = getSegmentHash(treeId, nodeId);\n\t\t\tif (temp != null)\n\t\t\t\tresult.add(temp);\n\t\t}\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic void setCompleteRebuiltTimestamp(long treeId, long ts) {\n\t\tbyte[] value = new byte[ByteUtils.SIZEOF_LONG];\n\t\tByteBuffer bbValue = ByteBuffer.wrap(value);\n\t\tbbValue.putLong(ts);\n\t\tbyte[] key = generateMetaDataKey(MetaDataKey.FULL_REBUILT_TS, treeId);\n\t\tdbObj.put(key, value);\n\t}\n\n\t@Override\n\tpublic long getCompleteRebuiltTimestamp(long treeId) {\n\t\tbyte[] key = generateMetaDataKey(MetaDataKey.FULL_REBUILT_TS, treeId);\n\t\tbyte[] value = dbObj.get(key);\n\t\treturn (value == null) ? 0 : ByteUtils.toLong(value, 0);\n\t}\n\n\t@Override\n\tpublic void deleteTree(long treeId) {\n\t\tDBIterator dbItr;\n\t\tbyte[] temp = new byte[LEN_BASEKEY_AND_TREEID];\n\t\tfor (BaseKey keyPrefix : BaseKey.values()) {\n\t\t\tdbItr = dbObj.iterator();\n\t\t\tByteBuffer wrap = ByteBuffer.wrap(temp);\n\t\t\tfillBaseKey(wrap, keyPrefix, treeId);\n\t\t\tdbItr.seek(wrap.array());\n\t\t\tfor (; dbItr.hasNext(); dbItr.next()) {\n\t\t\t\tif (ByteUtils.compareTo(temp, 0, temp.length, dbItr.peekNext()\n\t\t\t\t\t\t.getKey(), 0, temp.length) != 0)\n\t\t\t\t\tbreak;\n\t\t\t\tdbObj.delete(dbItr.peekNext().getKey());\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void putSegmentData(long treeId, int segId, ByteBuffer key,\n\t\t\tByteBuffer digest) {\n\t\tbyte[] dbKey = generateSegmentDataKey(treeId, segId, key);\n\t\tdbObj.put(dbKey, digest.array());\n\t}\n\n\t@Override\n\tpublic SegmentData getSegmentData(long treeId, int segId, ByteBuffer key) {\n\t\tbyte[] dbKey = generateSegmentDataKey(treeId, segId, key);\n\t\tbyte[] value = dbObj.get(dbKey);\n\t\tif (value != null) {\n\t\t\tByteBuffer intKeyBB = ByteBuffer.wrap(key.array());\n\t\t\tByteBuffer valueBB = ByteBuffer.wrap(value);\n\t\t\treturn new SegmentData(segId, intKeyBB, valueBB);\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void deleteSegmentData(long treeId, int segId, ByteBuffer key) {\n\t\tbyte[] dbKey = generateSegmentDataKey(treeId, segId, key);\n\t\tdbObj.delete(dbKey);\n\t}\n\n\t@Override\n\tpublic Iterator<SegmentData> getSegmentDataIterator(long treeId) {\n\t\tbyte[] startKey = generateBaseKey(BaseKey.SEG_DATA, treeId);\n\t\tDBIterator iterator = dbObj.iterator();\n\t\titerator.seek(startKey);\n\t\treturn new DataFilterableIterator<>(startKey, false,\n\t\t\t\tKVBYTES_TO_SEGDATA_CONVERTER, iterator);\n\t}\n\n\t@Override\n\tpublic Iterator<SegmentData> getSegmentDataIterator(long treeId,\n\t\t\tint fromSegId, int toSegId) throws IOException {\n\t\tbyte[] startKey = generateSegmentDataKey(treeId, fromSegId);\n\t\tbyte[] endKey = generateSegmentDataKey(treeId, toSegId);\n\t\tDBIterator iterator = dbObj.iterator();\n\t\titerator.seek(startKey);\n\t\treturn new DataFilterableIterator<>(endKey, false,\n\t\t\t\tKVBYTES_TO_SEGDATA_CONVERTER, iterator);\n\t}\n\n\t@Override\n\tpublic List<SegmentData> getSegment(long treeId, int segId) {\n\t\tbyte[] startKey = generateSegmentDataKey(treeId, segId);\n\t\tDBIterator iterator = dbObj.iterator();\n\t\titerator.seek(startKey);\n\t\treturn Lists.newArrayList(new DataFilterableIterator<>(startKey, true,\n\t\t\t\tKVBYTES_TO_SEGDATA_CONVERTER, iterator));\n\t}\n\n\t@Override\n\tpublic void markSegments(long treeId, List<Integer> segIds) {\n\t\tfor (int segId : segIds) {\n\t\t\tbyte[] key = generateRebuildMarkerKey(treeId, segId);\n\t\t\tdbObj.put(key, EMPTY_VALUE);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void unmarkSegments(long treeId, List<Integer> segIds) {\n\t\tfor (int segId : segIds) {\n\t\t\tbyte[] key = generateRebuildMarkerKey(treeId, segId);\n\t\t\tdbObj.delete(key);\n\t\t}\n\t}\n\n\t@Override\n\tpublic List<Integer> getMarkedSegments(long treeId) {\n\t\tbyte[] startKey = generateBaseKey(BaseKey.REBUILD_MARKER, treeId);\n\t\tDBIterator itr = dbObj.iterator();\n\t\titr.seek(startKey);\n\n\t\treturn Lists.newArrayList(new DataFilterableIterator<>(startKey, true,\n\t\t\t\tKVBYTES_TO_SEGID_CONVERTER, itr));\n\t}\n\n\t/**\n\t * Deletes the db files.\n\t * \n\t */\n\tpublic void delete() {\n\t\tstop();\n\t\tFile dbDirObj = new File(dbDir);\n\t\tif (dbDirObj.exists())\n\t\t\tFileUtils.deleteQuietly(dbDirObj);\n\t}\n\n\t@Override\n\tpublic void start() {\n\t\t// Nothing to do.\n\t}\n\n\t@Override\n\tpublic void stop() {\n\t\ttry {\n\t\t\tdbObj.close();\n\t\t} catch (IOException e) {\n\t\t\tLOG.warn(\"Exception occurred while closing leveldb connection.\");\n\t\t}\n\t}\n\n}", "public interface HashTreesStore extends Service {\n\n\t/**\n\t * A segment data is the value inside a segment block.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @param key\n\t * @param digest\n\t */\n\tvoid putSegmentData(long treeId, int segId, ByteBuffer key,\n\t\t\tByteBuffer digest) throws IOException;\n\n\t/**\n\t * Returns the SegmentData for the given key if available, otherwise returns\n\t * null.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @param key\n\t * @return\n\t */\n\tSegmentData getSegmentData(long treeId, int segId, ByteBuffer key)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Deletes the given segement data from the block.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @param key\n\t */\n\tvoid deleteSegmentData(long treeId, int segId, ByteBuffer key)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Returns an iterator to read all the segment data of the given tree id.\n\t * \n\t * Note: Iterator implementations should throw\n\t * {@link HashTreesCustomRuntimeException} so that failure cases can be\n\t * handled properly by {@link HashTrees}\n\t * \n\t * @param treeId\n\t * @return\n\t */\n\tIterator<SegmentData> getSegmentDataIterator(long treeId)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Returns an iterator to read all the segment data of the given tree id,\n\t * and starting from a given segId and to segId.\n\t * \n\t * Note: Iterator implementations should throw\n\t * {@link HashTreesCustomRuntimeException} so that failure cases can be\n\t * handled properly by {@link HashTrees}\n\t * \n\t * @param treeId\n\t * @param fromSegId\n\t * , inclusive\n\t * @param toSegId\n\t * , inclusive\n\t * @return\n\t * @throws IOException\n\t */\n\tIterator<SegmentData> getSegmentDataIterator(long treeId, int fromSegId,\n\t\t\tint toSegId) throws IOException;\n\n\t/**\n\t * Given a segment id, returns the list of all segment data in the\n\t * individual segment block.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @return\n\t */\n\tList<SegmentData> getSegment(long treeId, int segId) throws IOException;\n\n\t/**\n\t * Segment hash is the hash of all data inside a segment block. A segment\n\t * hash is stored on a tree node.\n\t * \n\t * @param treeId\n\t * @param nodeId\n\t * , identifier of the node in the hash tree.\n\t * @param digest\n\t */\n\tvoid putSegmentHash(long treeId, int nodeId, ByteBuffer digest)\n\t\t\tthrows IOException;\n\n\t/**\n\t * \n\t * @param treeId\n\t * @param nodeId\n\t * @return\n\t */\n\tSegmentHash getSegmentHash(long treeId, int nodeId) throws IOException;\n\n\t/**\n\t * Returns the data inside the nodes of the hash tree. If the node id is not\n\t * present in the hash tree, the entry will be missing in the result.\n\t * \n\t * @param treeId\n\t * @param nodeIds\n\t * , internal tree node ids.\n\t * @return\n\t */\n\tList<SegmentHash> getSegmentHashes(long treeId, Collection<Integer> nodeIds)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Marks a segment as a dirty.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @return previousValue\n\t */\n\tboolean setDirtySegment(long treeId, int segId) throws IOException;\n\n\t/**\n\t * Clears the segments, which are passed as an argument.\n\t * \n\t * @param treeId\n\t * @param segId\n\t * @return previousValue\n\t */\n\tboolean clearDirtySegment(long treeId, int segId) throws IOException;\n\n\t/**\n\t * Gets the dirty segments without clearing those bits.\n\t * \n\t * @param treeId\n\t * @return\n\t */\n\tList<Integer> getDirtySegments(long treeId) throws IOException;\n\n\t/**\n\t * Sets flags for the given segments. Used during rebuild process by\n\t * {@link HashTrees#rebuildHashTree(long, boolean)}. If the process crashes\n\t * in the middle of rebuilding we don't want to loose track. This has to\n\t * persist that information, so that we can reuse it after the process\n\t * recovery.\n\t * \n\t * @param segIds\n\t */\n\tvoid markSegments(long treeId, List<Integer> segIds) throws IOException;\n\n\t/**\n\t * Gets the marked segments for the given treeId.\n\t * \n\t * @param treeId\n\t * @return\n\t */\n\tList<Integer> getMarkedSegments(long treeId) throws IOException;\n\n\t/**\n\t * Unsets flags for the given segments. Used during rebuild process by\n\t * {@link HashTrees#rebuildHashTree(long, boolean)}. After rebuilding is\n\t * done, this will be cleared.\n\t * \n\t * @param segIds\n\t */\n\tvoid unmarkSegments(long treeId, List<Integer> segIds) throws IOException;\n\n\t/**\n\t * Deletes the segment hashes, and segment data for the given treeId.\n\t * \n\t * @param treeId\n\t */\n\tvoid deleteTree(long treeId) throws IOException;\n\n\t/**\n\t * Stores the timestamp at which the complete HashTree was rebuilt. This\n\t * method updates the value in store only if the given value is higher than\n\t * the existing timestamp, otherwise a noop.\n\t * \n\t * @param timestamp\n\t */\n\tvoid setCompleteRebuiltTimestamp(long treeId, long timestamp)\n\t\t\tthrows IOException;\n\n\t/**\n\t * Returns the timestamp at which the complete HashTree was rebuilt.\n\t * \n\t * @return\n\t */\n\tlong getCompleteRebuiltTimestamp(long treeId) throws IOException;\n}", "public class HashTreesImplTestUtils {\n\n\tprivate static final Random RANDOM = new Random(System.currentTimeMillis());\n\tpublic static final int ROOT_NODE = 0;\n\tpublic static final int DEFAULT_TREE_ID = 1;\n\tpublic static final int DEFAULT_SEG_DATA_BLOCKS_COUNT = 1 << 5;\n\tpublic static final int DEFAULT_HTREE_SERVER_PORT_NO = 11111;\n\tpublic static final SegIdProviderTest SEG_ID_PROVIDER = new SegIdProviderTest();\n\tpublic static final SimpleTreeIdProvider TREE_ID_PROVIDER = new SimpleTreeIdProvider();\n\n\t/**\n\t * Default SegId provider which expects the key to be an integer wrapped as\n\t * bytes.\n\t * \n\t */\n\tpublic static class SegIdProviderTest implements SegmentIdProvider {\n\n\t\t@Override\n\t\tpublic int getSegmentId(byte[] key) {\n\t\t\ttry {\n\t\t\t\tByteBuffer bb = ByteBuffer.wrap(key);\n\t\t\t\treturn bb.getInt();\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Exception occurred while converting the string\");\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic static class HTreeComponents {\n\n\t\tpublic final HashTreesStore hTStore;\n\t\tpublic final SimpleMemStore store;\n\t\tpublic final HashTreesImpl hTree;\n\n\t\tpublic HTreeComponents(final HashTreesStore hTStore,\n\t\t\t\tfinal SimpleMemStore store, final HashTreesImpl hTree) {\n\t\t\tthis.hTStore = hTStore;\n\t\t\tthis.store = store;\n\t\t\tthis.hTree = hTree;\n\t\t}\n\t}\n\n\tpublic static byte[] randomBytes() {\n\t\tbyte[] emptyBuffer = new byte[8];\n\t\tRANDOM.nextBytes(emptyBuffer);\n\t\treturn emptyBuffer;\n\t}\n\n\tpublic static ByteBuffer randomByteBuffer() {\n\t\tbyte[] random = new byte[8];\n\t\tRANDOM.nextBytes(random);\n\t\treturn ByteBuffer.wrap(random);\n\t}\n\n\tpublic static String randomDirName() {\n\t\treturn \"/tmp/test/random\" + RANDOM.nextInt();\n\t}\n\n\tpublic static HTreeComponents createHashTree(int noOfSegDataBlocks,\n\t\t\tboolean enabledNonBlockingCalls,\n\t\t\tfinal HashTreesIdProvider treeIdProv,\n\t\t\tfinal SegmentIdProvider segIdPro, final HashTreesStore hTStore) {\n\t\tSimpleMemStore store = new SimpleMemStore();\n\t\tHashTreesImpl hTree = new HashTreesImpl.Builder(store, treeIdProv,\n\t\t\t\thTStore).setNoOfSegments(noOfSegDataBlocks)\n\t\t\t\t.setEnabledNonBlockingCalls(enabledNonBlockingCalls)\n\t\t\t\t.setSegmentIdProvider(segIdPro).build();\n\t\tstore.registerHashTrees(hTree);\n\t\treturn new HTreeComponents(hTStore, store, hTree);\n\t}\n\n\tpublic static HTreeComponents createHashTree(int noOfSegments,\n\t\t\tboolean enabledNonBlockingCalls, final HashTreesStore hTStore) {\n\t\tSimpleMemStore store = new SimpleMemStore();\n\t\tModuloSegIdProvider segIdProvider = new ModuloSegIdProvider(\n\t\t\t\tnoOfSegments);\n\t\tHashTreesImpl hTree = new HashTreesImpl.Builder(store,\n\t\t\t\tTREE_ID_PROVIDER, hTStore).setNoOfSegments(noOfSegments)\n\t\t\t\t.setEnabledNonBlockingCalls(enabledNonBlockingCalls)\n\t\t\t\t.setSegmentIdProvider(segIdProvider).build();\n\t\tstore.registerHashTrees(hTree);\n\t\treturn new HTreeComponents(hTStore, store, hTree);\n\t}\n\n\tpublic static HashTreesMemStore generateInMemoryStore() {\n\t\treturn new HashTreesMemStore();\n\t}\n\n\tpublic static HashTreesPersistentStore generatePersistentStore()\n\t\t\tthrows IOException {\n\t\treturn new HashTreesPersistentStore(randomDirName());\n\t}\n\n\tpublic static HashTreesStore[] generateInMemoryAndPersistentStores()\n\t\t\tthrows IOException {\n\t\tHashTreesStore[] stores = new HashTreesStore[2];\n\t\tstores[0] = generateInMemoryStore();\n\t\tstores[1] = generatePersistentStore();\n\t\treturn stores;\n\t}\n\n\tpublic static void closeStores(HashTreesStore... stores) {\n\t\tfor (HashTreesStore store : stores) {\n\t\t\tif (store instanceof HashTreesPersistentStore) {\n\t\t\t\tHashTreesPersistentStore pStore = (HashTreesPersistentStore) store;\n\t\t\t\tFileUtils.deleteQuietly(new File(pStore.getDbDir()));\n\t\t\t}\n\t\t}\n\t}\n}", "public class SegmentData implements org.apache.thrift.TBase<SegmentData, SegmentData._Fields>, java.io.Serializable, Cloneable {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"SegmentData\");\n\n private static final org.apache.thrift.protocol.TField SEG_ID_FIELD_DESC = new org.apache.thrift.protocol.TField(\"segId\", org.apache.thrift.protocol.TType.I32, (short)1);\n private static final org.apache.thrift.protocol.TField KEY_FIELD_DESC = new org.apache.thrift.protocol.TField(\"key\", org.apache.thrift.protocol.TType.STRING, (short)2);\n private static final org.apache.thrift.protocol.TField DIGEST_FIELD_DESC = new org.apache.thrift.protocol.TField(\"digest\", org.apache.thrift.protocol.TType.STRING, (short)3);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new SegmentDataStandardSchemeFactory());\n schemes.put(TupleScheme.class, new SegmentDataTupleSchemeFactory());\n }\n\n public int segId; // required\n public ByteBuffer key; // required\n public ByteBuffer digest; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n SEG_ID((short)1, \"segId\"),\n KEY((short)2, \"key\"),\n DIGEST((short)3, \"digest\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // SEG_ID\n return SEG_ID;\n case 2: // KEY\n return KEY;\n case 3: // DIGEST\n return DIGEST;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n private static final int __SEGID_ISSET_ID = 0;\n private BitSet __isset_bit_vector = new BitSet(1);\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.SEG_ID, new org.apache.thrift.meta_data.FieldMetaData(\"segId\", org.apache.thrift.TFieldRequirementType.REQUIRED, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\n tmpMap.put(_Fields.KEY, new org.apache.thrift.meta_data.FieldMetaData(\"key\", org.apache.thrift.TFieldRequirementType.REQUIRED, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));\n tmpMap.put(_Fields.DIGEST, new org.apache.thrift.meta_data.FieldMetaData(\"digest\", org.apache.thrift.TFieldRequirementType.REQUIRED, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(SegmentData.class, metaDataMap);\n }\n\n public SegmentData() {\n }\n\n public SegmentData(\n int segId,\n ByteBuffer key,\n ByteBuffer digest)\n {\n this();\n this.segId = segId;\n setSegIdIsSet(true);\n this.key = key;\n this.digest = digest;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public SegmentData(SegmentData other) {\n __isset_bit_vector.clear();\n __isset_bit_vector.or(other.__isset_bit_vector);\n this.segId = other.segId;\n if (other.isSetKey()) {\n this.key = org.apache.thrift.TBaseHelper.copyBinary(other.key);\n;\n }\n if (other.isSetDigest()) {\n this.digest = org.apache.thrift.TBaseHelper.copyBinary(other.digest);\n;\n }\n }\n\n public SegmentData deepCopy() {\n return new SegmentData(this);\n }\n\n @Override\n public void clear() {\n setSegIdIsSet(false);\n this.segId = 0;\n this.key = null;\n this.digest = null;\n }\n\n public int getSegId() {\n return this.segId;\n }\n\n public SegmentData setSegId(int segId) {\n this.segId = segId;\n setSegIdIsSet(true);\n return this;\n }\n\n public void unsetSegId() {\n __isset_bit_vector.clear(__SEGID_ISSET_ID);\n }\n\n /** Returns true if field segId is set (has been assigned a value) and false otherwise */\n public boolean isSetSegId() {\n return __isset_bit_vector.get(__SEGID_ISSET_ID);\n }\n\n public void setSegIdIsSet(boolean value) {\n __isset_bit_vector.set(__SEGID_ISSET_ID, value);\n }\n\n public byte[] getKey() {\n setKey(org.apache.thrift.TBaseHelper.rightSize(key));\n return key == null ? null : key.array();\n }\n\n public ByteBuffer bufferForKey() {\n return key;\n }\n\n public SegmentData setKey(byte[] key) {\n setKey(key == null ? (ByteBuffer)null : ByteBuffer.wrap(key));\n return this;\n }\n\n public SegmentData setKey(ByteBuffer key) {\n this.key = key;\n return this;\n }\n\n public void unsetKey() {\n this.key = null;\n }\n\n /** Returns true if field key is set (has been assigned a value) and false otherwise */\n public boolean isSetKey() {\n return this.key != null;\n }\n\n public void setKeyIsSet(boolean value) {\n if (!value) {\n this.key = null;\n }\n }\n\n public byte[] getDigest() {\n setDigest(org.apache.thrift.TBaseHelper.rightSize(digest));\n return digest == null ? null : digest.array();\n }\n\n public ByteBuffer bufferForDigest() {\n return digest;\n }\n\n public SegmentData setDigest(byte[] digest) {\n setDigest(digest == null ? (ByteBuffer)null : ByteBuffer.wrap(digest));\n return this;\n }\n\n public SegmentData setDigest(ByteBuffer digest) {\n this.digest = digest;\n return this;\n }\n\n public void unsetDigest() {\n this.digest = null;\n }\n\n /** Returns true if field digest is set (has been assigned a value) and false otherwise */\n public boolean isSetDigest() {\n return this.digest != null;\n }\n\n public void setDigestIsSet(boolean value) {\n if (!value) {\n this.digest = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case SEG_ID:\n if (value == null) {\n unsetSegId();\n } else {\n setSegId((Integer)value);\n }\n break;\n\n case KEY:\n if (value == null) {\n unsetKey();\n } else {\n setKey((ByteBuffer)value);\n }\n break;\n\n case DIGEST:\n if (value == null) {\n unsetDigest();\n } else {\n setDigest((ByteBuffer)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case SEG_ID:\n return Integer.valueOf(getSegId());\n\n case KEY:\n return getKey();\n\n case DIGEST:\n return getDigest();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case SEG_ID:\n return isSetSegId();\n case KEY:\n return isSetKey();\n case DIGEST:\n return isSetDigest();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof SegmentData)\n return this.equals((SegmentData)that);\n return false;\n }\n\n public boolean equals(SegmentData that) {\n if (that == null)\n return false;\n\n boolean this_present_segId = true;\n boolean that_present_segId = true;\n if (this_present_segId || that_present_segId) {\n if (!(this_present_segId && that_present_segId))\n return false;\n if (this.segId != that.segId)\n return false;\n }\n\n boolean this_present_key = true && this.isSetKey();\n boolean that_present_key = true && that.isSetKey();\n if (this_present_key || that_present_key) {\n if (!(this_present_key && that_present_key))\n return false;\n if (!this.key.equals(that.key))\n return false;\n }\n\n boolean this_present_digest = true && this.isSetDigest();\n boolean that_present_digest = true && that.isSetDigest();\n if (this_present_digest || that_present_digest) {\n if (!(this_present_digest && that_present_digest))\n return false;\n if (!this.digest.equals(that.digest))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return 0;\n }\n\n public int compareTo(SegmentData other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n SegmentData typedOther = (SegmentData)other;\n\n lastComparison = Boolean.valueOf(isSetSegId()).compareTo(typedOther.isSetSegId());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetSegId()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.segId, typedOther.segId);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetKey()).compareTo(typedOther.isSetKey());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetKey()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.key, typedOther.key);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetDigest()).compareTo(typedOther.isSetDigest());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetDigest()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.digest, typedOther.digest);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"SegmentData(\");\n boolean first = true;\n\n sb.append(\"segId:\");\n sb.append(this.segId);\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"key:\");\n if (this.key == null) {\n sb.append(\"null\");\n } else {\n org.apache.thrift.TBaseHelper.toString(this.key, sb);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"digest:\");\n if (this.digest == null) {\n sb.append(\"null\");\n } else {\n org.apache.thrift.TBaseHelper.toString(this.digest, sb);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // alas, we cannot check 'segId' because it's a primitive and you chose the non-beans generator.\n if (key == null) {\n throw new org.apache.thrift.protocol.TProtocolException(\"Required field 'key' was not present! Struct: \" + toString());\n }\n if (digest == null) {\n throw new org.apache.thrift.protocol.TProtocolException(\"Required field 'digest' was not present! Struct: \" + toString());\n }\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\n __isset_bit_vector = new BitSet(1);\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class SegmentDataStandardSchemeFactory implements SchemeFactory {\n public SegmentDataStandardScheme getScheme() {\n return new SegmentDataStandardScheme();\n }\n }\n\n private static class SegmentDataStandardScheme extends StandardScheme<SegmentData> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, SegmentData struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // SEG_ID\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\n struct.segId = iprot.readI32();\n struct.setSegIdIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // KEY\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.key = iprot.readBinary();\n struct.setKeyIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 3: // DIGEST\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.digest = iprot.readBinary();\n struct.setDigestIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n if (!struct.isSetSegId()) {\n throw new org.apache.thrift.protocol.TProtocolException(\"Required field 'segId' was not found in serialized data! Struct: \" + toString());\n }\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, SegmentData struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n oprot.writeFieldBegin(SEG_ID_FIELD_DESC);\n oprot.writeI32(struct.segId);\n oprot.writeFieldEnd();\n if (struct.key != null) {\n oprot.writeFieldBegin(KEY_FIELD_DESC);\n oprot.writeBinary(struct.key);\n oprot.writeFieldEnd();\n }\n if (struct.digest != null) {\n oprot.writeFieldBegin(DIGEST_FIELD_DESC);\n oprot.writeBinary(struct.digest);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class SegmentDataTupleSchemeFactory implements SchemeFactory {\n public SegmentDataTupleScheme getScheme() {\n return new SegmentDataTupleScheme();\n }\n }\n\n private static class SegmentDataTupleScheme extends TupleScheme<SegmentData> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, SegmentData struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n oprot.writeI32(struct.segId);\n oprot.writeBinary(struct.key);\n oprot.writeBinary(struct.digest);\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, SegmentData struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n struct.segId = iprot.readI32();\n struct.setSegIdIsSet(true);\n struct.key = iprot.readBinary();\n struct.setKeyIsSet(true);\n struct.digest = iprot.readBinary();\n struct.setDigestIsSet(true);\n }\n }\n\n}", "public class SegmentHash implements org.apache.thrift.TBase<SegmentHash, SegmentHash._Fields>, java.io.Serializable, Cloneable {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"SegmentHash\");\n\n private static final org.apache.thrift.protocol.TField NODE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField(\"nodeId\", org.apache.thrift.protocol.TType.I32, (short)1);\n private static final org.apache.thrift.protocol.TField HASH_FIELD_DESC = new org.apache.thrift.protocol.TField(\"hash\", org.apache.thrift.protocol.TType.STRING, (short)2);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new SegmentHashStandardSchemeFactory());\n schemes.put(TupleScheme.class, new SegmentHashTupleSchemeFactory());\n }\n\n public int nodeId; // required\n public ByteBuffer hash; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n NODE_ID((short)1, \"nodeId\"),\n HASH((short)2, \"hash\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // NODE_ID\n return NODE_ID;\n case 2: // HASH\n return HASH;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n private static final int __NODEID_ISSET_ID = 0;\n private BitSet __isset_bit_vector = new BitSet(1);\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.NODE_ID, new org.apache.thrift.meta_data.FieldMetaData(\"nodeId\", org.apache.thrift.TFieldRequirementType.REQUIRED, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\n tmpMap.put(_Fields.HASH, new org.apache.thrift.meta_data.FieldMetaData(\"hash\", org.apache.thrift.TFieldRequirementType.REQUIRED, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(SegmentHash.class, metaDataMap);\n }\n\n public SegmentHash() {\n }\n\n public SegmentHash(\n int nodeId,\n ByteBuffer hash)\n {\n this();\n this.nodeId = nodeId;\n setNodeIdIsSet(true);\n this.hash = hash;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public SegmentHash(SegmentHash other) {\n __isset_bit_vector.clear();\n __isset_bit_vector.or(other.__isset_bit_vector);\n this.nodeId = other.nodeId;\n if (other.isSetHash()) {\n this.hash = org.apache.thrift.TBaseHelper.copyBinary(other.hash);\n;\n }\n }\n\n public SegmentHash deepCopy() {\n return new SegmentHash(this);\n }\n\n @Override\n public void clear() {\n setNodeIdIsSet(false);\n this.nodeId = 0;\n this.hash = null;\n }\n\n public int getNodeId() {\n return this.nodeId;\n }\n\n public SegmentHash setNodeId(int nodeId) {\n this.nodeId = nodeId;\n setNodeIdIsSet(true);\n return this;\n }\n\n public void unsetNodeId() {\n __isset_bit_vector.clear(__NODEID_ISSET_ID);\n }\n\n /** Returns true if field nodeId is set (has been assigned a value) and false otherwise */\n public boolean isSetNodeId() {\n return __isset_bit_vector.get(__NODEID_ISSET_ID);\n }\n\n public void setNodeIdIsSet(boolean value) {\n __isset_bit_vector.set(__NODEID_ISSET_ID, value);\n }\n\n public byte[] getHash() {\n setHash(org.apache.thrift.TBaseHelper.rightSize(hash));\n return hash == null ? null : hash.array();\n }\n\n public ByteBuffer bufferForHash() {\n return hash;\n }\n\n public SegmentHash setHash(byte[] hash) {\n setHash(hash == null ? (ByteBuffer)null : ByteBuffer.wrap(hash));\n return this;\n }\n\n public SegmentHash setHash(ByteBuffer hash) {\n this.hash = hash;\n return this;\n }\n\n public void unsetHash() {\n this.hash = null;\n }\n\n /** Returns true if field hash is set (has been assigned a value) and false otherwise */\n public boolean isSetHash() {\n return this.hash != null;\n }\n\n public void setHashIsSet(boolean value) {\n if (!value) {\n this.hash = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case NODE_ID:\n if (value == null) {\n unsetNodeId();\n } else {\n setNodeId((Integer)value);\n }\n break;\n\n case HASH:\n if (value == null) {\n unsetHash();\n } else {\n setHash((ByteBuffer)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case NODE_ID:\n return Integer.valueOf(getNodeId());\n\n case HASH:\n return getHash();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case NODE_ID:\n return isSetNodeId();\n case HASH:\n return isSetHash();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof SegmentHash)\n return this.equals((SegmentHash)that);\n return false;\n }\n\n public boolean equals(SegmentHash that) {\n if (that == null)\n return false;\n\n boolean this_present_nodeId = true;\n boolean that_present_nodeId = true;\n if (this_present_nodeId || that_present_nodeId) {\n if (!(this_present_nodeId && that_present_nodeId))\n return false;\n if (this.nodeId != that.nodeId)\n return false;\n }\n\n boolean this_present_hash = true && this.isSetHash();\n boolean that_present_hash = true && that.isSetHash();\n if (this_present_hash || that_present_hash) {\n if (!(this_present_hash && that_present_hash))\n return false;\n if (!this.hash.equals(that.hash))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return 0;\n }\n\n public int compareTo(SegmentHash other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n SegmentHash typedOther = (SegmentHash)other;\n\n lastComparison = Boolean.valueOf(isSetNodeId()).compareTo(typedOther.isSetNodeId());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetNodeId()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.nodeId, typedOther.nodeId);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetHash()).compareTo(typedOther.isSetHash());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetHash()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.hash, typedOther.hash);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"SegmentHash(\");\n boolean first = true;\n\n sb.append(\"nodeId:\");\n sb.append(this.nodeId);\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"hash:\");\n if (this.hash == null) {\n sb.append(\"null\");\n } else {\n org.apache.thrift.TBaseHelper.toString(this.hash, sb);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // alas, we cannot check 'nodeId' because it's a primitive and you chose the non-beans generator.\n if (hash == null) {\n throw new org.apache.thrift.protocol.TProtocolException(\"Required field 'hash' was not present! Struct: \" + toString());\n }\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\n __isset_bit_vector = new BitSet(1);\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class SegmentHashStandardSchemeFactory implements SchemeFactory {\n public SegmentHashStandardScheme getScheme() {\n return new SegmentHashStandardScheme();\n }\n }\n\n private static class SegmentHashStandardScheme extends StandardScheme<SegmentHash> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, SegmentHash struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // NODE_ID\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\n struct.nodeId = iprot.readI32();\n struct.setNodeIdIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // HASH\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.hash = iprot.readBinary();\n struct.setHashIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n if (!struct.isSetNodeId()) {\n throw new org.apache.thrift.protocol.TProtocolException(\"Required field 'nodeId' was not found in serialized data! Struct: \" + toString());\n }\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, SegmentHash struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n oprot.writeFieldBegin(NODE_ID_FIELD_DESC);\n oprot.writeI32(struct.nodeId);\n oprot.writeFieldEnd();\n if (struct.hash != null) {\n oprot.writeFieldBegin(HASH_FIELD_DESC);\n oprot.writeBinary(struct.hash);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class SegmentHashTupleSchemeFactory implements SchemeFactory {\n public SegmentHashTupleScheme getScheme() {\n return new SegmentHashTupleScheme();\n }\n }\n\n private static class SegmentHashTupleScheme extends TupleScheme<SegmentHash> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, SegmentHash struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n oprot.writeI32(struct.nodeId);\n oprot.writeBinary(struct.hash);\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, SegmentHash struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n struct.nodeId = iprot.readI32();\n struct.setNodeIdIsSet(true);\n struct.hash = iprot.readBinary();\n struct.setHashIsSet(true);\n }\n }\n\n}", "public class ByteUtils {\n\n\t// ensuring non instantiability\n\tprivate ByteUtils() {\n\n\t}\n\n\t/**\n\t * Size of boolean in bytes\n\t */\n\tpublic static final int SIZEOF_BOOLEAN = Byte.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of byte in bytes\n\t */\n\tpublic static final int SIZEOF_BYTE = SIZEOF_BOOLEAN;\n\n\t/**\n\t * Size of char in bytes\n\t */\n\tpublic static final int SIZEOF_CHAR = Character.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of double in bytes\n\t */\n\tpublic static final int SIZEOF_DOUBLE = Double.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of float in bytes\n\t */\n\tpublic static final int SIZEOF_FLOAT = Float.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of int in bytes\n\t */\n\tpublic static final int SIZEOF_INT = Integer.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of long in bytes\n\t */\n\tpublic static final int SIZEOF_LONG = Long.SIZE / Byte.SIZE;\n\n\t/**\n\t * Size of short in bytes\n\t */\n\tpublic static final int SIZEOF_SHORT = Short.SIZE / Byte.SIZE;\n\n\tpublic static byte[] sha1(byte[] input) {\n\t\treturn getDigest(\"SHA-1\").digest(input);\n\t}\n\n\tpublic static MessageDigest getDigest(String algorithm) {\n\t\ttry {\n\t\t\treturn MessageDigest.getInstance(algorithm);\n\t\t} catch (NoSuchAlgorithmException e) {\n\t\t\tthrow new IllegalStateException(\"Unknown algorithm: \" + algorithm,\n\t\t\t\t\te);\n\t\t}\n\t}\n\n\t/**\n\t * @param left\n\t * left operand\n\t * @param right\n\t * right operand\n\t * @return 0 if equal, < 0 if left is less than right, etc.\n\t */\n\tpublic static int compareTo(final byte[] left, final byte[] right) {\n\t\treturn compareTo(left, 0, left.length, right, 0, right.length);\n\t}\n\n\t/**\n\t * Lexographically compare two arrays.\n\t * \n\t * @param buffer1\n\t * left operand\n\t * @param buffer2\n\t * right operand\n\t * @param offset1\n\t * Where to start comparing in the left buffer\n\t * @param offset2\n\t * Where to start comparing in the right buffer\n\t * @param length1\n\t * How much to compare from the left buffer\n\t * @param length2\n\t * How much to compare from the right buffer\n\t * @return 0 if equal, < 0 if left is less than right, etc.\n\t */\n\tpublic static int compareTo(byte[] buffer1, int offset1, int length1,\n\t\t\tbyte[] buffer2, int offset2, int length2) {\n\t\t// Bring WritableComparator code local\n\t\tint end1 = offset1 + length1;\n\t\tint end2 = offset2 + length2;\n\t\tfor (int i = offset1, j = offset2; i < end1 && j < end2; i++, j++) {\n\t\t\tint a = (buffer1[i] & 0xff);\n\t\t\tint b = (buffer2[j] & 0xff);\n\t\t\tif (a != b) {\n\t\t\t\treturn a - b;\n\t\t\t}\n\t\t}\n\t\treturn length1 - length2;\n\t}\n\n\t/**\n\t * Converts a byte array to a long value. Reverses {@link #toBytes(long)}\n\t * \n\t * @param bytes\n\t * array\n\t * @return the long value\n\t */\n\tpublic static long toLong(byte[] bytes) {\n\t\treturn toLong(bytes, 0, SIZEOF_LONG);\n\t}\n\n\t/**\n\t * Converts a byte array to a long value. Assumes there will be\n\t * {@link #SIZEOF_LONG} bytes available.\n\t * \n\t * @param bytes\n\t * bytes\n\t * @param offset\n\t * offset\n\t * @return the long value\n\t */\n\tpublic static long toLong(byte[] bytes, int offset) {\n\t\treturn toLong(bytes, offset, SIZEOF_LONG);\n\t}\n\n\t/**\n\t * Converts a byte array to a long value.\n\t * \n\t * @param bytes\n\t * array of bytes\n\t * @param offset\n\t * offset into array\n\t * @param length\n\t * length of data (must be {@link #SIZEOF_LONG})\n\t * @return the long value\n\t * @throws IllegalArgumentException\n\t * if length is not {@link #SIZEOF_LONG} or if there's not\n\t * enough room in the array at the offset indicated.\n\t */\n\tpublic static long toLong(byte[] bytes, int offset, final int length) {\n\t\tif (length != SIZEOF_LONG || offset + length > bytes.length) {\n\t\t\tthrow explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_LONG);\n\t\t}\n\t\tlong l = 0;\n\t\tfor (int i = offset; i < offset + length; i++) {\n\t\t\tl <<= 8;\n\t\t\tl ^= bytes[i] & 0xFF;\n\t\t}\n\t\treturn l;\n\t}\n\n\tprivate static IllegalArgumentException explainWrongLengthOrOffset(\n\t\t\tfinal byte[] bytes, final int offset, final int length,\n\t\t\tfinal int expectedLength) {\n\t\tString reason;\n\t\tif (length != expectedLength) {\n\t\t\treason = \"Wrong length: \" + length + \", expected \" + expectedLength;\n\t\t} else {\n\t\t\treason = \"offset (\" + offset + \") + length (\" + length\n\t\t\t\t\t+ \") exceed the\" + \" capacity of the array: \"\n\t\t\t\t\t+ bytes.length;\n\t\t}\n\t\treturn new IllegalArgumentException(reason);\n\t}\n\n\t/**\n\t * Copy the specified bytes into a new array\n\t * \n\t * @param array\n\t * The array to copy from\n\t * @param from\n\t * The index in the array to begin copying from\n\t * @param to\n\t * The least index not copied\n\t * @return A new byte[] containing the copied bytes\n\t */\n\tpublic static byte[] copy(byte[] array, int from, int to) {\n\t\tif (to - from < 0) {\n\t\t\treturn new byte[0];\n\t\t} else {\n\t\t\tbyte[] a = new byte[to - from];\n\t\t\tSystem.arraycopy(array, from, a, 0, to - from);\n\t\t\treturn a;\n\t\t}\n\t}\n\n\tpublic static int roundUpToPowerOf2(int number) {\n\t\treturn (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;\n\t}\n}" ]
import org.hashtrees.thrift.generated.SegmentData; import org.hashtrees.thrift.generated.SegmentHash; import org.hashtrees.util.ByteUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.hashtrees.store.HashTreesMemStore; import org.hashtrees.store.HashTreesPersistentStore; import org.hashtrees.store.HashTreesStore; import org.hashtrees.test.utils.HashTreesImplTestUtils;
/* * 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.hashtrees.test; public class HashTreesStoreTest { private static final int DEF_TREE_ID = 1; private static final int DEF_SEG_ID = 0; private static interface HTStoreHelper { HashTreesStore getInstance() throws IOException; HashTreesStore restartInstance(HashTreesStore htStore) throws IOException; void cleanup(HashTreesStore htStore) throws IOException; } private static class HTPersistentStoreHelper implements HTStoreHelper { @Override public HashTreesStore getInstance() throws IOException { return new HashTreesPersistentStore( HashTreesImplTestUtils.randomDirName()); } @Override public void cleanup(HashTreesStore htStore) { ((HashTreesPersistentStore) htStore).delete(); } @Override public HashTreesStore restartInstance(HashTreesStore htStore) throws IOException { ((HashTreesPersistentStore) htStore).stop(); return new HashTreesPersistentStore( ((HashTreesPersistentStore) htStore).getDbDir()); } } private static class HTMemStoreHelper implements HTStoreHelper { @Override public HashTreesStore getInstance() throws IOException { return new HashTreesMemStore(); } @Override public void cleanup(HashTreesStore htStore) { // nothing to do. } @Override public HashTreesStore restartInstance(HashTreesStore htStore) throws IOException { return htStore; } } private static final Set<HTStoreHelper> helpers = new HashSet<>(); static { helpers.add(new HTPersistentStoreHelper()); helpers.add(new HTMemStoreHelper()); } @Test public void testSegmentData() throws IOException { for (HTStoreHelper helper : helpers) { HashTreesStore htStore = helper.getInstance(); try { ByteBuffer key = ByteBuffer.wrap("key1".getBytes());
ByteBuffer digest = ByteBuffer.wrap(ByteUtils.sha1("digest1"
6
ryantenney/passkit4j
src/main/java/com/ryantenney/passkit4j/Pass.java
[ "public interface NamedInputStreamSupplier extends InputStreamSupplier {\n\n\tpublic String getName();\n\n}", "@Data\n@Accessors(chain=true, fluent=true)\n@RequiredArgsConstructor\npublic class Barcode {\n\n\t@NonNull private BarcodeFormat format;\n\n\t@NonNull private String message;\n\n\tprivate String messageEncoding = \"iso-8859-1\";\n\n\tprivate String altText = null;\n\n}", "@Data\n@Accessors(chain=true, fluent=true)\n@RequiredArgsConstructor\n@NoArgsConstructor(access=AccessLevel.PROTECTED)\npublic class Beacon {\n\n\t@NonNull private String proximityUUID;\n\n\t@JsonInclude(Include.NON_DEFAULT) private long major = -1;\n\t@JsonInclude(Include.NON_DEFAULT) private long minor = -1;\n\n\tprivate String relevantText;\n\n}", "@Data\n@Accessors(fluent=true)\n@ToString(includeFieldNames=true)\n@JsonSerialize(using=Color.ColorSerializer.class)\n@JsonDeserialize(using=Color.ColorDeserializer.class)\npublic class Color {\n\n\tpublic static final Color WHITE = new Color(255, 255, 255);\n\tpublic static final Color BLACK = new Color(0, 0, 0);\n\n\tprivate final int red;\n\tprivate final int green;\n\tprivate final int blue;\n\n\tpublic Color(int red, int green, int blue) {\n\t\tthis.red = red;\n\t\tthis.green = green;\n\t\tthis.blue = blue;\n\t}\n\n\tpublic Color(java.awt.Color color) {\n\t\tthis.red = color.getRed();\n\t\tthis.green = color.getGreen();\n\t\tthis.blue = color.getBlue();\n\t}\n\n\tstatic final class ColorSerializer extends JsonSerializer<Color> {\n\n\t\t@Override\n\t\tpublic void serialize(Color color, JsonGenerator json, SerializerProvider serializer) throws IOException, JsonProcessingException {\n\t\t\tjson.writeString(String.format(\"rgb(%d, %d, %d)\", color.red(), color.green(), color.blue()));\n\t\t}\n\n\t}\n\n\tstatic final class ColorDeserializer extends JsonDeserializer<Color> {\n\n\t\t@Override\n\t\tpublic Color deserialize(JsonParser json, DeserializationContext context) throws IOException, JsonProcessingException {\n\t\t\tString str = json.getText().replace(\"rgb(\", \"\").replace(\")\", \"\");\n\t\t\tStringTokenizer tok = new StringTokenizer(str, \",\");\n\t\t\tint red = Integer.parseInt(tok.nextToken().trim(), 10);\n\t\t\tint green = Integer.parseInt(tok.nextToken().trim(), 10);\n\t\t\tint blue = Integer.parseInt(tok.nextToken().trim(), 10);\n\t\t\treturn new Color(red, green, blue);\n\t\t}\n\n\t}\n\n}", "@Data\n@Accessors(chain=true, fluent=true)\n@NoArgsConstructor\npublic class Location {\n\n\tprivate double latitude;\n\tprivate double longitude;\n\n\tpublic Location(double latitude, double longitude) {\n\t this.latitude = latitude;\n\t this.longitude = longitude;\n\t}\n\n\t@JsonInclude(Include.NON_DEFAULT) private double altitude = Double.NaN;\n\tprivate String relevantText;\n\n}", "@Data\n@Accessors(chain=true, fluent=true)\n@RequiredArgsConstructor\n@NoArgsConstructor(access=AccessLevel.PROTECTED)\npublic class NFC {\n\n\t@NonNull private String message;\n\n\tprivate String encryptionPublicKey;\n\n}", "@Data\npublic abstract class PassInformation {\n\n\t@JsonIgnore private final String typeName;\n\n\tprivate List<Field<?>> headerFields;\n\tprivate List<Field<?>> primaryFields;\n\tprivate List<Field<?>> secondaryFields;\n\tprivate List<Field<?>> backFields;\n\tprivate List<Field<?>> auxiliaryFields;\n\n\tprotected PassInformation(final String typeName) {\n\t\tthis.typeName = typeName;\n\t}\n\n\tpublic String typeName() {\n\t\treturn this.typeName;\n\t}\n\n\tpublic PassInformation headerFields(Field<?>... fields) {\n\t\tthis.headerFields = Arrays.asList(fields);\n\t\treturn this;\n\t}\n\n\tpublic PassInformation headerFields(List<Field<?>> fields) {\n\t\tthis.headerFields = fields;\n\t\treturn this;\n\t}\n\n\tpublic PassInformation primaryFields(Field<?>... fields) {\n\t\tthis.primaryFields = Arrays.asList(fields);\n\t\treturn this;\n\t}\n\n\tpublic PassInformation primaryFields(List<Field<?>> fields) {\n\t\tthis.primaryFields = fields;\n\t\treturn this;\n\t}\n\n\tpublic PassInformation secondaryFields(Field<?>... fields) {\n\t\tthis.secondaryFields = Arrays.asList(fields);\n\t\treturn this;\n\t}\n\n\tpublic PassInformation secondaryFields(List<Field<?>> fields) {\n\t\tthis.secondaryFields = fields;\n\t\treturn this;\n\t}\n\n\tpublic PassInformation backFields(Field<?>... fields) {\n\t\tthis.backFields = Arrays.asList(fields);\n\t\treturn this;\n\t}\n\n\tpublic PassInformation backFields(List<Field<?>> fields) {\n\t\tthis.backFields = fields;\n\t\treturn this;\n\t}\n\n\tpublic PassInformation auxiliaryFields(Field<?>... fields) {\n\t\tthis.auxiliaryFields = Arrays.asList(fields);\n\t\treturn this;\n\t}\n\n\tpublic PassInformation auxiliaryFields(List<Field<?>> fields) {\n\t\tthis.auxiliaryFields = fields;\n\t\treturn this;\n\t}\n\n}" ]
import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.experimental.Accessors; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.util.ISO8601Utils; import com.ryantenney.passkit4j.io.NamedInputStreamSupplier; import com.ryantenney.passkit4j.model.Barcode; import com.ryantenney.passkit4j.model.Beacon; import com.ryantenney.passkit4j.model.Color; import com.ryantenney.passkit4j.model.Location; import com.ryantenney.passkit4j.model.NFC; import com.ryantenney.passkit4j.model.PassInformation;
package com.ryantenney.passkit4j; @Data @NoArgsConstructor @Accessors(chain=true, fluent=true) public class Pass { // Standard Keys @NonNull private String description; @NonNull private String organizationName; @NonNull private String passTypeIdentifier; @NonNull private String serialNumber; @NonNull private String teamIdentifier; @JsonProperty("formatVersion") private final int $formatVersion = 1; // Visual Appearance Keys private Barcode barcode; private List<Barcode> barcodes; private Color backgroundColor; private Color foregroundColor; private String groupingIdentifier; private Color labelColor; private String logoText; @JsonInclude(Include.NON_DEFAULT) private boolean suppressStripShine = false; // Web Service Keys private String webServiceURL; private String authenticationToken; // Relevance Keys private boolean ignoresTimeZone = false; private List<Location> locations; private List<Beacon> beacons; private Integer maxDistance; private Date relevantDate; // Associated App Keys private List<Long> associatedStoreIdentifiers; private String appLaunchURL; // Companion App Keys private JsonNode userInfo; // Expiration Keys private Date expirationDate; @JsonInclude(Include.NON_DEFAULT) private boolean voided = false; // NFC Keys private NFC nfc;
@JsonIgnore private PassInformation passInformation;
6
quartzweb/quartz-web
src/main/java/com/github/quartzweb/service/strategy/JobServiceStrategy.java
[ "public class UnsupportedClassException extends RuntimeException {\n public UnsupportedClassException() {\n }\n\n public UnsupportedClassException(String message) {\n super(message);\n }\n\n public UnsupportedClassException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public UnsupportedClassException(Throwable cause) {\n super(cause);\n }\n}", "public class MethodInvoker implements Serializable {\n\n\n private static final long serialVersionUID = 8125699928726329418L;\n\n private Class<?> targetClass;\n\n private Object targetObject;\n\n private String targetMethod;\n\n private String staticMethod;\n\n private Object[] arguments = new Object[0];\n\n /** The method we will call */\n private Method methodObject;\n\n\n /**\n * Set the target class on which to call the target method.\n * Only necessary when the target method is static; else,\n * a target object needs to be specified anyway.\n * @see #setTargetObject\n * @see #setTargetMethod\n */\n public void setTargetClass(Class<?> targetClass) {\n this.targetClass = targetClass;\n }\n\n /**\n * Return the target class on which to call the target method.\n */\n public Class<?> getTargetClass() {\n return this.targetClass;\n }\n\n /**\n * Set the target object on which to call the target method.\n * Only necessary when the target method is not static;\n * else, a target class is sufficient.\n * @see #setTargetClass\n * @see #setTargetMethod\n */\n public void setTargetObject(Object targetObject) {\n this.targetObject = targetObject;\n if (targetObject != null) {\n this.targetClass = targetObject.getClass();\n }\n }\n\n /**\n * Return the target object on which to call the target method.\n */\n public Object getTargetObject() {\n return this.targetObject;\n }\n\n /**\n * Set the name of the method to be invoked.\n * Refers to either a static method or a non-static method,\n * depending on a target object being set.\n * @see #setTargetClass\n * @see #setTargetObject\n */\n public void setTargetMethod(String targetMethod) {\n this.targetMethod = targetMethod;\n }\n\n /**\n * Return the name of the method to be invoked.\n */\n public String getTargetMethod() {\n return this.targetMethod;\n }\n\n /**\n * Set a fully qualified static method name to invoke,\n * e.g. \"example.MyExampleClass.myExampleMethod\".\n * Convenient alternative to specifying targetClass and targetMethod.\n * @see #setTargetClass\n * @see #setTargetMethod\n */\n public void setStaticMethod(String staticMethod) {\n this.staticMethod = staticMethod;\n }\n\n /**\n * Set arguments for the method invocation. If this property is not set,\n * or the Object array is of length 0, a method with no arguments is assumed.\n */\n public void setArguments(Object[] arguments) {\n this.arguments = (arguments != null ? arguments : new Object[0]);\n }\n\n /**\n * Return the arguments for the method invocation.\n */\n public Object[] getArguments() {\n return this.arguments;\n }\n\n\n /**\n * Prepare the specified method.\n * The method can be invoked any number of times afterwards.\n * @see #getPreparedMethod\n * @see #invoke\n */\n public void prepare() throws ClassNotFoundException, NoSuchMethodException {\n // 判断静态方法\n if (this.staticMethod != null) {\n int lastDotIndex = this.staticMethod.lastIndexOf('.');\n if (lastDotIndex == -1 || lastDotIndex == this.staticMethod.length()) {\n throw new IllegalArgumentException(\n \"staticMethod must be a fully qualified class plus method name: \" +\n \"e.g. 'example.MyExampleClass.myExampleMethod'\");\n }\n String className = this.staticMethod.substring(0, lastDotIndex);\n String methodName = this.staticMethod.substring(lastDotIndex + 1);\n this.targetClass = resolveClassName(className);\n this.targetMethod = methodName;\n }\n\n Class<?> targetClass = getTargetClass();\n String targetMethod = getTargetMethod();\n if (targetClass == null) {\n throw new IllegalArgumentException(\"Either 'targetClass' or 'targetObject' is required\");\n }\n if (targetMethod == null) {\n throw new IllegalArgumentException(\"Property 'targetMethod' is required\");\n }\n\n Object[] arguments = getArguments();\n Class<?>[] argTypes = new Class<?>[arguments.length];\n for (int i = 0; i < arguments.length; ++i) {\n argTypes[i] = (arguments[i] != null ? arguments[i].getClass() : Object.class);\n }\n\n // Try to get the exact method first.\n try {\n this.methodObject = targetClass.getMethod(targetMethod, argTypes);\n }\n catch (NoSuchMethodException ex) {\n // Just rethrow exception if we can't get any match.\n this.methodObject = findMatchingMethod();\n if (this.methodObject == null) {\n throw ex;\n }\n }\n }\n\n /**\n * Resolve the given class name into a Class.\n * <p>The default implementations uses {@code ClassUtils.forName},\n * using the thread context class loader.\n * @param className the class name to resolve\n * @return the resolved Class\n * @throws ClassNotFoundException if the class name was invalid\n */\n protected Class<?> resolveClassName(String className) throws ClassNotFoundException {\n return ClassUtils.forName(className, ClassUtils.getDefaultClassLoader());\n }\n\n /**\n * Find a matching method with the specified name for the specified arguments.\n * @return a matching method, or {@code null} if none\n * @see #getTargetClass()\n * @see #getTargetMethod()\n * @see #getArguments()\n */\n protected Method findMatchingMethod() {\n String targetMethod = getTargetMethod();\n Object[] arguments = getArguments();\n int argCount = arguments.length;\n List<Method> methods = new ArrayList<Method>();\n // 获取全部方法,包括父类和接口\n ReflectionUtils.getAllDeclaredMethods(getTargetClass(), methods);\n // 转换成数组\n Method[] candidates = methods.toArray(new Method[methods.size()]);\n // 类型权重\n int minTypeDiffWeight = Integer.MAX_VALUE;\n Method matchingMethod = null;\n // 遍历所有方法\n for (Method candidate : candidates) {\n if (candidate.getName().equals(targetMethod)) {\n // 获取方法类型\n Class<?>[] paramTypes = candidate.getParameterTypes();\n //长度相等开始做类型权重判读\n if (paramTypes.length == argCount) {\n int typeDiffWeight = ClassUtils.getTypeDifferenceWeight(paramTypes, arguments);\n // 获取权重最小的\n if (typeDiffWeight < minTypeDiffWeight) {\n minTypeDiffWeight = typeDiffWeight;\n matchingMethod = candidate;\n }\n }\n }\n }\n\n return matchingMethod;\n }\n\n /**\n * Return the prepared Method object that will be invoked.\n * <p>Can for example be used to determine the return type.\n * @return the prepared Method object (never {@code null})\n * @throws IllegalStateException if the invoker hasn't been prepared yet\n * @see #prepare\n * @see #invoke\n */\n public Method getPreparedMethod() throws IllegalStateException {\n if (this.methodObject == null) {\n throw new IllegalStateException(\"prepare() must be called prior to invoke() on MethodInvoker\");\n }\n return this.methodObject;\n }\n\n /**\n * Return whether this invoker has been prepared already,\n * i.e. whether it allows access to {@link #getPreparedMethod()} already.\n */\n public boolean isPrepared() {\n return (this.methodObject != null);\n }\n\n /**\n * Invoke the specified method.\n * <p>The invoker needs to have been prepared before.\n * @return the object (possibly null) returned by the method invocation,\n * or {@code null} if the method has a void return type\n * @throws InvocationTargetException if the target method threw an exception\n * @throws IllegalAccessException if the target method couldn't be accessed\n * @see #prepare\n */\n public Object invoke() throws InvocationTargetException, IllegalAccessException {\n // In the static case, target will simply be {@code null}.\n Object targetObject = getTargetObject();\n Method preparedMethod = getPreparedMethod();\n if (targetObject == null && !Modifier.isStatic(preparedMethod.getModifiers())) {\n throw new IllegalArgumentException(\"Target method must not be non-static without a target\");\n }\n ReflectionUtils.makeAccessible(preparedMethod);\n return preparedMethod.invoke(targetObject, getArguments());\n }\n\n public Object prepareInvoke() throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException {\n prepare();\n return invoke();\n }\n\n}", "public class JobInfosVO extends HashMap<String, List<JobInfo>> {\n\n\n /**\n * 获取 jobInfo实体类\n *\n * @return jobInfos jobInfo实体类\n */\n public List<JobInfo> getJobInfos(String schedulerName) {\n return this.get(schedulerName);\n }\n\n /**\n * 设置 jobInfo实体类\n *\n * @param jobInfos jobInfo实体类\n */\n public void addJobInfos(String schedulerName, List<JobInfo> jobInfos) {\n this.put(schedulerName, jobInfos);\n }\n}", "public class QuartzWebManager {\n\n private final static QuartzWebManager instance = new QuartzWebManager();\n\n private QuartzWebManager() {\n }\n\n public static QuartzWebManager getInstance() {\n return instance;\n }\n\n private static QuartzManager quartzManager = QuartzManager.getInstance();\n\n private static QuartzBeanManagerFacade quartzBeanManagerFacade = QuartzBeanManagerFacade.getInstance();\n\n public static BasicInfo getBasicInfo() {\n String versionIteration = QuartzScheduler.getVersionIteration();\n String versionMajor = QuartzScheduler.getVersionMajor();\n String versionMinor = QuartzScheduler.getVersionMinor();\n BasicInfo basicInfo = new BasicInfo();\n basicInfo.setQuartzWebVersion(VERSION.getVersionNumber());\n basicInfo.setVersionMajor(versionMajor);\n basicInfo.setVersionMinor(versionMinor);\n basicInfo.setVersionIteration(versionIteration);\n basicInfo.setQuartzVersion(versionMajor + \".\" + versionMinor + \".\" + versionIteration);\n basicInfo.setJavaVMStartTime(DateUtils.getVMStartTime());\n basicInfo.setJavaVMName(System.getProperty(\"java.vm.name\"));\n basicInfo.setJavaVersion(System.getProperty(\"java.version\"));\n basicInfo.setJavaClassPath(System.getProperty(\"java.class.path\"));\n return basicInfo;\n }\n\n /**\n * 获取Scheduler基本信息\n *\n * @return 返回基本信息的Map\n * @throws SchedulerException 异常\n */\n public static List<SchedulerInfo> getAllSchedulerInfo() throws SchedulerException {\n List<SchedulerInfo> schedulerInfos = new ArrayList<SchedulerInfo>();\n Collection<Scheduler> allSchedulers = quartzManager.getSchedulers();\n\n for (Scheduler scheduler : allSchedulers) {\n // 获取Job数量\n List<JobDetail> allJobsOfScheduler = QuartzUtils.getAllJobsOfScheduler(scheduler);\n\n int triggerCount = 0;\n // 错误Trigger数量\n int triggerErrorCount = 0;\n // 堵塞Trigger数量\n int triggerBlockedCount = 0;\n // 暂停Trigger数量\n int triggerPausedCount = 0;\n for (JobDetail jobDetail : allJobsOfScheduler) {\n List<? extends Trigger> triggersOfJob = QuartzUtils.getTriggersOfJob(jobDetail, scheduler);\n for (Trigger trigger : triggersOfJob) {\n triggerCount++;\n boolean isError = QuartzUtils.isTriggerError(trigger, scheduler);\n if (isError) {\n triggerErrorCount++;\n }\n boolean isBlocked = QuartzUtils.isTriggerBlocked(trigger, scheduler);\n if (isBlocked) {\n triggerBlockedCount++;\n }\n boolean isPaused = QuartzUtils.isTriggerPaused(trigger, scheduler);\n if (isPaused) {\n triggerPausedCount++;\n }\n }\n\n }\n\n // schedulerConext中参数Map\n List<Map<String, Object>> schedulerContextMapList = new ArrayList<Map<String, Object>>();\n SchedulerContext context = scheduler.getContext();\n Set<String> contextKeySet = context.keySet();\n for (String contextKey : contextKeySet) {\n Map<String, Object> contextMap = new LinkedHashMap<String, Object>();\n Object contextKeyObj = context.get(contextKey);\n // 是否支持json转换\n boolean support = JSONWriter.support(contextKeyObj);\n if (support) {\n contextMap.put(\"key\", contextKey);\n contextMap.put(\"value\", contextKeyObj);\n } else {\n contextMap.put(\"key\", contextKey);\n contextMap.put(\"value\", contextKeyObj.toString());\n }\n schedulerContextMapList.add(contextMap);\n }\n\n\n SchedulerInfo schedulerInfo = new SchedulerInfo();\n schedulerInfo.setSchedulerName(scheduler.getSchedulerName());\n schedulerInfo.setShutdown(scheduler.isShutdown());\n schedulerInfo.setStarted(scheduler.isStarted());\n schedulerInfo.setInStandbyMode(scheduler.isInStandbyMode());\n // 设置job数量\n schedulerInfo.setJobCount(allJobsOfScheduler.size());\n // 设置数量\n schedulerInfo.setTriggerCount(triggerCount);\n schedulerInfo.setTriggerErrorCount(triggerErrorCount);\n schedulerInfo.setTriggerBlockedCount(triggerBlockedCount);\n schedulerInfo.setTriggerPausedCount(triggerPausedCount);\n // 设置schedulerContext\n schedulerInfo.setSchedulerContext(schedulerContextMapList);\n\n schedulerInfos.add(schedulerInfo);\n }\n return schedulerInfos;\n }\n\n\n /**\n * 启动\n *\n * @param schedulerName schedler名称\n * @throws SchedulerException 异常\n */\n public static void schedulerStart(String schedulerName) throws SchedulerException {\n quartzManager.schedulerStart(schedulerName);\n }\n\n /**\n * 延时启动\n *\n * @param schedulerName schedler名称\n * @param delayed 延时启动秒数\n * @throws SchedulerException 异常信息\n */\n public static void schedulerStart(String schedulerName, int delayed) throws SchedulerException {\n quartzManager.schedulerStart(schedulerName, delayed);\n }\n\n public static void schedulerShutdown(String schedulerName) throws SchedulerException {\n quartzManager.schedulerShutdown(schedulerName);\n }\n\n public static void schedulerShutdown(String schedulerName, boolean waitForJobsToComplete) throws SchedulerException {\n quartzManager.schedulerShutdown(schedulerName, waitForJobsToComplete);\n }\n\n /**\n * 获取Job的信息\n *\n * @return\n * @throws SchedulerException\n */\n public static JobInfosVO getAllJobInfo() throws SchedulerException {\n\n Collection<Scheduler> allSchedulers = quartzManager.getSchedulers();\n JobInfosVO jobInfosVO = new JobInfosVO();\n for (Scheduler scheduler : allSchedulers) {\n List<JobDetail> allJobs = QuartzUtils.getAllJobsOfScheduler(scheduler);\n List<JobInfo> jobInfos = new ArrayList<JobInfo>();\n\n for (JobDetail jobDetail : allJobs) {\n JobInfo jobInfo = new JobInfo();\n jobInfo.setSchedulerName(scheduler.getSchedulerName());\n jobInfo.setJobName(QuartzUtils.getJobName(jobDetail));\n jobInfo.setJobGroup(QuartzUtils.getJobGroup(jobDetail));\n jobInfo.setJobClass(jobDetail.getJobClass().getName());\n jobInfo.setConcurrentExectionDisallowed(jobDetail.isConcurrentExectionDisallowed());\n jobInfo.setDurable(jobDetail.isDurable());\n jobInfo.setPersistJobDataAfterExecution(jobDetail.isPersistJobDataAfterExecution());\n jobInfo.setJobDataMap(jobDetail.getJobDataMap());\n jobInfo.setDescription(jobDetail.getDescription());\n jobInfos.add(jobInfo);\n }\n jobInfosVO.addJobInfos(scheduler.getSchedulerName(), jobInfos);\n }\n\n return jobInfosVO;\n }\n\n public static List<JobInfo> getAllJobInfo(String schedulerName) throws SchedulerException {\n\n List<JobDetail> allJobs = quartzManager.getAllJobsOfScheduler(schedulerName);\n List<JobInfo> jobInfos = new ArrayList<JobInfo>();\n\n for (JobDetail jobDetail : allJobs) {\n JobInfo jobInfo = new JobInfo();\n jobInfo.setSchedulerName(schedulerName);\n jobInfo.setJobName(QuartzUtils.getJobName(jobDetail));\n jobInfo.setJobGroup(QuartzUtils.getJobGroup(jobDetail));\n jobInfo.setJobClass(jobDetail.getJobClass().getName());\n jobInfo.setConcurrentExectionDisallowed(jobDetail.isConcurrentExectionDisallowed());\n jobInfo.setDurable(jobDetail.isDurable());\n jobInfo.setPersistJobDataAfterExecution(jobDetail.isPersistJobDataAfterExecution());\n jobInfo.setJobDataMap(jobDetail.getJobDataMap());\n jobInfo.setDescription(jobDetail.getDescription());\n jobInfos.add(jobInfo);\n }\n return jobInfos;\n }\n\n /**\n * 校验job是否存在\n * @param schedulerName\n * @param jobName\n * @param jobGroup\n * @return true存在\n * @throws SchedulerException\n */\n public static boolean checkJobExist(String schedulerName,String jobName,String jobGroup) throws SchedulerException {\n return quartzManager.existJob(schedulerName, jobName, jobGroup);\n }\n\n public static Trigger getTrigger(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {\n return quartzManager.getTrigger(schedulerName, triggerName, triggerGroup);\n }\n\n public static void runTrigger(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {\n quartzManager.runTrigger(schedulerName, triggerName, triggerGroup);\n }\n /**\n * 获取触发器集合\n * @param schedulerName\n * @param jobName\n * @param jobGroup\n * @return\n * @throws SchedulerException\n */\n public static List<Trigger> getTriggers(String schedulerName, String jobName, String jobGroup) throws SchedulerException {\n List<? extends Trigger> triggersOfJob = quartzManager.getTriggersOfJob(schedulerName, jobName, jobGroup);\n List<Trigger> triggers = new ArrayList<Trigger>();\n triggers.addAll(triggersOfJob);\n return triggers;\n }\n\n public static List<TriggerInfo> getTriggerInfo(String schedulerName, String jobName, String jobGroup) throws SchedulerException {\n\n // 最终返回数据\n List<? extends Trigger> triggersOfJob = getTriggers(schedulerName, jobName, jobGroup);\n List<TriggerInfo> triggerInfos = new ArrayList<TriggerInfo>();\n for (Trigger trigger : triggersOfJob) {\n TriggerInfo triggerInfo = new TriggerInfo();\n triggerInfo.setSchedulerName(schedulerName);\n triggerInfo.setJobName(jobName);\n triggerInfo.setJobGroup(jobGroup);\n triggerInfo.setTriggerName(QuartzUtils.getTriggerName(trigger));\n triggerInfo.setTriggerGroup(QuartzUtils.getTriggerGroup(trigger));\n // 上次触发时间\n triggerInfo.setPreviousFireTime(trigger.getPreviousFireTime());\n // 下次触发时间\n triggerInfo.setNextFireTime(trigger.getNextFireTime());\n // 优先级\n triggerInfo.setPriority(trigger.getPriority());\n triggerInfo.setStartTime(trigger.getStartTime());\n triggerInfo.setEndTime(trigger.getEndTime());\n //获取misfire的值,默认为0\n triggerInfo.setMisfireInstruction(trigger.getMisfireInstruction());\n // 最后触发时间\n triggerInfo.setFinalFireTime(trigger.getFinalFireTime());\n // 某个时间后的触发时间\n triggerInfo.setFireTimeAfter(trigger.getFireTimeAfter(new Date()));\n // 日历名称\n triggerInfo.setCalendarName(trigger.getCalendarName());\n // 描述\n triggerInfo.setDescription(trigger.getDescription());\n triggerInfo.setTriggerState(quartzManager.getTriggerState(schedulerName, trigger).name());\n if (trigger instanceof CronTrigger) {\n CronTrigger cronTrigger = (CronTrigger) trigger;\n triggerInfo.setCronExpression(cronTrigger.getCronExpression());\n } else {\n triggerInfo.setCronExpression(\"\");\n }\n triggerInfos.add(triggerInfo);\n }\n\n return triggerInfos;\n }\n\n /**\n * 核查名称是否正确\n * @param className\n */\n public static boolean checkClass(String className) {\n Assert.notEmpty(className, \"className can not be empty\");\n Object bean = null;\n try {\n bean = quartzBeanManagerFacade.getBean(className);\n } catch (Exception ignored) {\n }\n if (bean != null) {\n return true;\n }\n try {\n Class.forName(className);\n return true;\n } catch (ClassNotFoundException e) {\n return false;\n }\n\n }\n\n public static Class getClass(String className) {\n Assert.notEmpty(className, \"className can not be empty\");\n Object bean = null;\n try {\n bean = quartzBeanManagerFacade.getBean(className);\n } catch (Exception ignored) {\n }\n if (bean != null) {\n return bean.getClass();\n }\n try {\n Class<?> clazz = ClassUtils.forName(className,ClassUtils.getDefaultClassLoader());\n return clazz;\n } catch (ClassNotFoundException e) {\n return null;\n }\n\n }\n /**\n * 根据class名称获取bean\n * @param className\n * @return\n */\n public static Object getBean(String className) {\n Assert.notEmpty(className, \"className can not be empty\");\n Object bean = quartzBeanManagerFacade.getBean(className);\n return bean;\n }\n\n /**\n * 根据参数类型和class名称获取bean\n * @param className\n * @param args 参数\n * @return\n */\n public static Object getBean(String className, Object[] args) {\n Assert.notEmpty(className, \"className can not be empty\");\n Object bean = quartzBeanManagerFacade.getBean(className, args);\n return bean;\n }\n\n public static Method[] getAllDeclaredMethods(Class<?> clazz){\n Assert.notNull(clazz, \"class can not be null\");\n List<Method> methodList = new ArrayList<Method>();\n // 获取全部方法,包括父类和接口\n ReflectionUtils.getAllDeclaredMethods(clazz, methodList);\n\n // 转换成数组\n Method[] methods = methodList.toArray(new Method[methodList.size()]);\n return methods;\n }\n\n public static Method[] getMethods(Class<?> clazz){\n Assert.notNull(clazz, \"class can not be null\");\n // 获取全部方法,包括父类和接口\n return clazz.getDeclaredMethods();\n }\n /**\n * 获取构造函数信息\n * [\n * [参数类型1,参数类型2],\n * [参数类型1]\n * ]\n * @param clazz\n * @return\n */\n public static List<List<String>> getConstructorInfo(Class<?> clazz){\n Assert.notNull(clazz, \"object can not be null\");\n Constructor[] constructors = clazz.getConstructors();\n /**\n * [\n * [参数类型1,参数类型2],\n * [参数类型1]\n * ]\n */\n List<List<String>> dataList = new ArrayList<List<String>>();\n for (Constructor constructor : constructors) {\n Class[] parameterTypes = constructor.getParameterTypes();\n ArrayList<String> parameterTypeNames = new ArrayList<String>();\n for (Class parameterType : parameterTypes) {\n String parameterTypeName = parameterType.getName();\n parameterTypeNames.add(parameterTypeName);\n }\n dataList.add(parameterTypeNames);\n }\n return dataList;\n }\n\n /**\n * 获取方法信息,名称后面添加了一个#,方便前台解析\n * [\n * methodName1#=[参数类型1,参数类型2],\n * methodName2#=[参数类型1]\n * ]\n * @param clazz\n * @return\n */\n public static List<Map<String,List<String>>> getMethodInfo(Class<?> clazz){\n Assert.notNull(clazz, \"class can not be null\");\n Method[] methods = getMethods(clazz);\n /**\n * [\n * methodName1=[参数类型1,参数类型2],\n * methodName2=[参数类型1]\n * ]\n */\n List<Map<String,List<String>>> dataList = new ArrayList<Map<String,List<String>>>();\n for (Method method : methods) {\n Class[] parameterTypes = method.getParameterTypes();\n Map<String, List<String>> nameType = new LinkedHashMap<String, List<String>>();\n String name = method.getName();\n List<String> parameterTypeNames = new ArrayList<String>();\n for (Class parameterType : parameterTypes) {\n String parameterTypeName = parameterType.getName();\n parameterTypeNames.add(parameterTypeName);\n }\n nameType.put(name+\"#\",parameterTypeNames);\n dataList.add(nameType);\n }\n return dataList;\n }\n\n public static JobDetail getJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {\n return quartzManager.getJob(schedulerName, jobName, jobGroup);\n }\n\n public static JobDetail addJob(String schedulerName, JobDetail jobDetail) throws SchedulerException {\n quartzManager.addJob(schedulerName, jobDetail);\n return jobDetail;\n }\n\n public static JobDetail addMethodInovkeJob(String schedulerName, String jobName, String jobGroup, String description,\n MethodInvoker methodInvoker) throws SchedulerException {\n return quartzManager.addMethodInovkeJob(schedulerName, jobName, jobGroup, description, methodInvoker);\n }\n\n public static JobDetail addMethodInovkeJob(String schedulerName, String jobName, String jobGroup, String jobClass,\n Object[] constructorArguments, String jobClassMethodName,\n Object[] jobClassMethodArgs, String description) throws SchedulerException {\n return quartzManager.addMethodInovkeJob(schedulerName, jobName, jobGroup, jobClass, constructorArguments,\n jobClassMethodName,jobClassMethodArgs,description);\n }\n\n public static JobDetail addStatefulMethodJob(String schedulerName, String jobName, String jobGroup, String description,\n MethodInvoker methodInvoker) throws SchedulerException {\n return quartzManager.addStatefulMethodJob(schedulerName, jobName, jobGroup, description, methodInvoker);\n }\n\n public static JobDetail addStatefulMethodJob(String schedulerName, String jobName, String jobGroup, String jobClass,\n Object[] constructorArguments, String jobClassMethodName,\n Object[] jobClassMethodArgs, String description) throws SchedulerException {\n return quartzManager.addStatefulMethodJob(schedulerName, jobName, jobGroup, jobClass, constructorArguments,\n jobClassMethodName,jobClassMethodArgs,description);\n }\n\n public static JobDetail updateJob(String schedulerName, JobDetail jobDetail) throws SchedulerException {\n quartzManager.updateJob(schedulerName, jobDetail);\n return jobDetail;\n }\n\n public static JobDetail updateMethodInovkeJob(String schedulerName, String jobName, String jobGroup, String description,\n MethodInvoker methodInvoker) throws SchedulerException {\n return quartzManager.updateMethodInovkeJob(schedulerName, jobName, jobGroup, description, methodInvoker);\n }\n\n public static JobDetail updateMethodInovkeJob(String schedulerName, String jobName, String jobGroup, String jobClass,\n Object[] constructorArguments, String jobClassMethodName,\n Object[] jobClassMethodArgs, String description) throws SchedulerException {\n return quartzManager.updateMethodInovkeJob(schedulerName, jobName, jobGroup, jobClass, constructorArguments,\n jobClassMethodName,jobClassMethodArgs,description);\n }\n\n public static JobDetail updateStatefulMethodJob(String schedulerName, String jobName, String jobGroup, String description,\n MethodInvoker methodInvoker) throws SchedulerException {\n return quartzManager.updateStatefulMethodJob(schedulerName, jobName, jobGroup, description, methodInvoker);\n }\n\n public static JobDetail updateStatefulMethodJob(String schedulerName, String jobName, String jobGroup, String jobClass,\n Object[] constructorArguments, String jobClassMethodName,\n Object[] jobClassMethodArgs, String description) throws SchedulerException {\n return quartzManager.updateStatefulMethodJob(schedulerName, jobName, jobGroup, jobClass, constructorArguments,\n jobClassMethodName,jobClassMethodArgs,description);\n }\n\n public static void addTriggerForJob(String schedulerName, String jobName, String jobGroup, Trigger trigger) throws SchedulerException {\n quartzManager.addTriggerForJob(schedulerName, jobName, jobGroup, trigger);\n }\n\n public static void addTriggerForJob(String schedulerName, JobDetail jobDetail, Trigger trigger) throws SchedulerException {\n quartzManager.addTriggerForJob(schedulerName, jobDetail, trigger);\n }\n\n public static void addTriggerForJob(String schedulerName, Trigger trigger) throws SchedulerException {\n quartzManager.addTriggerForJob(schedulerName, trigger);\n }\n\n public static void updateTriggerForJob(String schedulerName, Trigger trigger) throws SchedulerException {\n quartzManager.updateTriggerForJob(schedulerName, trigger);\n }\n\n public static void pauseJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {\n quartzManager.pauseJob(schedulerName, jobName, jobGroup);\n\n }\n\n public static void resumeJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {\n quartzManager.resumeJob(schedulerName, jobName, jobGroup);\n }\n\n public static void removeJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {\n quartzManager.removeJob(schedulerName, jobName, jobGroup);\n }\n\n public static void runJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {\n quartzManager.runJob(schedulerName, jobName, jobGroup);\n }\n\n /**\n * 核查触发器是否存在\n * @param schedulerName\n * @param triggerName\n * @param triggerGroup\n * @return\n */\n public static boolean checkTriggerExists(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {\n return quartzManager.existTrigger(schedulerName, triggerName, triggerGroup);\n }\n\n public static void pauseTrigger(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {\n quartzManager.pauseTrigger(schedulerName, triggerName, triggerGroup);\n\n }\n\n public static void resumeTrigger(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {\n quartzManager.resumeTrigger(schedulerName, triggerName, triggerGroup);\n }\n\n public static void removeTrigger(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {\n quartzManager.removeTrigger(schedulerName, triggerName, triggerGroup);\n }\n\n}", "public class JSONResult {\n\n /**\n * 返回结果code\n */\n private int resultCode;\n\n /**\n * 返回结果\n */\n private Object content;\n\n /**\n * 返回json结果-成功(1)\n */\n public static final int RESULT_CODE_SUCCESS = 1;\n\n /**\n * 返回json结果-失败(-1)\n */\n public static final int RESULT_CODE_ERROR = -1;\n\n public JSONResult(int resultCode, Object content) {\n this.resultCode = resultCode;\n this.content = content;\n }\n\n /**\n * 创建一个json结果\n * @param resultCode\n * @param content\n * @return\n */\n public static JSONResult build(int resultCode, Object content){\n return new JSONResult(resultCode, content);\n }\n\n public String json() {\n Map<String, Object> dataMap = new LinkedHashMap<String, Object>();\n dataMap.put(\"resultCode\", this.resultCode);\n dataMap.put(\"content\", this.content);\n return JSONUtils.toJSONString(dataMap);\n }\n\n\n public static String returnJSON(int resultCode, Object content) {\n Map<String, Object> dataMap = new LinkedHashMap<String, Object>();\n dataMap.put(\"resultCode\", resultCode);\n dataMap.put(\"content\", content);\n return JSONUtils.toJSONString(dataMap);\n }\n}", "public class QuartzWebURL {\n\n public enum BasicURL implements ServiceStrategyURL {\n BASIC(\"/api/basic.json\");\n\n private String url;\n\n BasicURL(String url) {\n this.url = url;\n }\n\n public String getURL() {\n return url;\n }\n\n public static boolean lookup(String url) {\n if(StringUtils.isEmpty(url)){\n return false;\n }\n BasicURL[] basicURLs = BasicURL.values();\n for (BasicURL basicURL : basicURLs) {\n if (url.startsWith(basicURL.getURL())) {\n return true;\n }\n }\n return false;\n }\n }\n\n public enum SchedulerURL implements ServiceStrategyURL {\n\n INFO(\"/api/schedulerInfo.json\"),\n START(\"/api/schedulerStart.json\"),\n START_DELAYED(\"/api/schedulerStartDelayed.json\"),\n SHUTDOWN(\"/api/schedulerShutdown.json\"),\n SHUTDOWN_WAIT(\"/api/schedulerShutdownWait.json\");\n\n private String url;\n\n SchedulerURL(String url) {\n this.url = url;\n }\n\n public String getURL() {\n return url;\n }\n\n public static boolean lookup(String url) {\n if(StringUtils.isEmpty(url)){\n return false;\n }\n SchedulerURL[] schedulerURLs = SchedulerURL.values();\n for (SchedulerURL schedulerURL : schedulerURLs) {\n if (url.startsWith(schedulerURL.getURL())) {\n return true;\n }\n }\n return false;\n }\n }\n\n public enum JobURL implements ServiceStrategyURL {\n INFO(\"/api/jobInfo.json\"),\n ADD(\"/api/jobAdd.json\"),\n RESUME(\"/api/jobResume.json\"),\n REMOVE(\"/api/jobRemove.json\"),\n PAUSE(\"/api/jobPause.json\"),\n RUN(\"/api/jobRun.json\");\n\n private String url;\n\n JobURL(String url) {\n this.url = url;\n }\n\n public String getURL() {\n return url;\n }\n\n public static boolean lookup(String url) {\n if(StringUtils.isEmpty(url)){\n return false;\n }\n JobURL[] jobURLs = JobURL.values();\n for (JobURL jobURL : jobURLs) {\n if (url.startsWith(jobURL.getURL())) {\n return true;\n }\n }\n return false;\n }\n }\n\n public enum TriggerURL implements ServiceStrategyURL {\n INFO(\"/api/triggerInfo.json\"),\n ADD(\"/api/triggerAdd.json\"),\n RESUME(\"/api/triggerResume.json\"),\n REMOVE(\"/api/triggerRemove.json\"),\n PAUSE(\"/api/triggerPause.json\"),\n RUN(\"/api/triggerRun.json\");\n\n private String url;\n\n TriggerURL(String url) {\n this.url = url;\n }\n\n public String getURL() {\n return url;\n }\n\n public static boolean lookup(String url) {\n if(StringUtils.isEmpty(url)){\n return false;\n }\n TriggerURL[] triggerURLs = TriggerURL.values();\n for (TriggerURL triggerURL : triggerURLs) {\n if (url.startsWith(triggerURL.getURL())) {\n return true;\n }\n }\n return false;\n }\n }\n\n public enum ValidateURL implements ServiceStrategyURL {\n VALIDATE_CLASS(\"/api/validateClass.json\"),\n VALIDATE_CLASSINFO(\"/api/classInfo.json\"),\n VALIDATE_ASSIGNABLE(\"/api/assignable.json\"),\n VALIDATE_JOB(\"/api/validateJob.json\"),\n VALIDATE_TRIGGER(\"/api/validateTrigger.json\"),\n VALIDATE_CRONEXPRESSION(\"/api/validateCronExpression.json\");\n private String url;\n\n ValidateURL(String url) {\n this.url = url;\n }\n\n public String getURL() {\n return url;\n }\n\n public static boolean lookup(String url) {\n if(StringUtils.isEmpty(url)){\n return false;\n }\n ValidateURL[] validateURLs = ValidateURL.values();\n for (ValidateURL validateURL : validateURLs) {\n if (url.startsWith(validateURL.getURL())) {\n return true;\n }\n }\n return false;\n }\n\n }\n\n}", "public abstract class Assert {\n\n\n public static void isTrue(boolean expression, String message) {\n if (!expression) {\n throw new IllegalArgumentException(message);\n }\n }\n\n\n public static void isNull(Object object, String message) {\n if (object != null) {\n throw new IllegalArgumentException(message);\n }\n }\n\n public static void isEmpty(String str, String message) {\n if (!StringUtils.isEmpty(str)) {\n throw new IllegalArgumentException(message);\n }\n }\n\n public static void notEmpty(String str, String message) {\n if (StringUtils.isEmpty(str)) {\n throw new IllegalArgumentException(message);\n }\n }\n\n public static void isInteger(String integer, String message) {\n if (!StringUtils.isInteger(integer)) {\n throw new IllegalArgumentException(message);\n }\n }\n\n public static void notNull(Object object, String message) {\n if (object == null) {\n throw new IllegalArgumentException(message);\n }\n }\n\n public static void noNullElements(Object[] array, String message) {\n if (array != null) {\n for (Object element : array) {\n if (element == null) {\n throw new IllegalArgumentException(message);\n }\n }\n }\n }\n\n public static void equalsAnyOne(String unexpected, String[] actuals, String message) {\n if (unexpected == null) {\n return;\n }\n for (String actual : actuals) {\n if (actual != null) {\n if (actual.equals(unexpected)) {\n return;\n }\n }\n }\n throw new IllegalArgumentException(message);\n }\n\n public static void isInstanceOf(Class<?> type, Object obj, String message) {\n notNull(type, \"Type to check against must not be null\");\n if (!type.isInstance(obj)) {\n throw new IllegalArgumentException(message + \" \" +\n \"Object of class [\" + (obj != null ? obj.getClass().getName() : \"null\") +\n \"] must be an instance of \" + type);\n }\n }\n\n public static void isAssignable(Class<?> superType, Class<?> subType, String message) {\n notNull(superType, \"Type to check against must not be null\");\n if (subType == null || !superType.isAssignableFrom(subType)) {\n throw new IllegalArgumentException(message + subType + \" is not assignable to \" + superType);\n }\n }\n\n /**\n * 校验cron表达式\n * @param unexpected\n * @param message\n */\n public static void isCronExpression(String unexpected, String message) {\n boolean validExpression = CronExpression.isValidExpression(unexpected);\n if (!validExpression) {\n throw new IllegalArgumentException(message);\n }\n }\n\n}", "public class StringUtils {\n\n /**\n * 判断两个字符串是否相等\n * @param a 字符\n * @param b 字符\n * @return true相等,false不相等\n */\n public static boolean equals(String a, String b) {\n if (a == null) {\n return b == null;\n }\n return a.equals(b);\n }\n\n /**\n * 忽略大小写判断两个字符串是否相等\n * @param a 字符\n * @param b 字符\n * @return true相等,false不相等\n */\n public static boolean equalsIgnoreCase(String a, String b) {\n if (a == null) {\n return b == null;\n }\n return a.equalsIgnoreCase(b);\n }\n\n /**\n * 判断字符串是否为空(NULL或空串\"\")\n * @param value 字符串\n * @return true为空,false不为空\n */\n public static boolean isEmpty(CharSequence value) {\n if (value == null || value.length() == 0) {\n return true;\n }\n return false;\n }\n\n /**\n * 是否为整数\n * @param str\n * @return\n */\n public static boolean isInteger(String str) {\n Pattern pattern = Pattern.compile(\"^[-\\\\+]?[\\\\d]*$\");\n return pattern.matcher(str).matches();\n }\n\n /**\n * 判断是否为大于某个数字的整数\n * @param str\n * @param integer\n * @return\n */\n public static boolean isIntegerGTNumber(String str,Integer integer) {\n // 是整数\n if (isInteger(str)) {\n int source = Integer.parseInt(str);\n return source > integer;\n } else {\n return false;\n }\n }\n}" ]
import com.github.quartzweb.exception.UnsupportedClassException; import com.github.quartzweb.job.MethodInvoker; import com.github.quartzweb.manager.web.JobInfosVO; import com.github.quartzweb.manager.web.QuartzWebManager; import com.github.quartzweb.service.JSONResult; import com.github.quartzweb.service.QuartzWebURL; import com.github.quartzweb.utils.Assert; import com.github.quartzweb.utils.StringUtils; import org.quartz.JobBuilder; import org.quartz.JobDataMap; import org.quartz.JobDetail; import java.util.LinkedHashMap; import java.util.Map;
/** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.service.strategy; /** * @author quxiucheng [[email protected]] */ public class JobServiceStrategy implements ServiceStrategy<JobServiceStrategyParameter> { @Override public JSONResult service(ServiceStrategyURL serviceStrategyURL, JobServiceStrategyParameter parameter) { String url = serviceStrategyURL.getURL(); // 列出信息 if (QuartzWebURL.JobURL.INFO.getURL().equals(url)) { return getInfo(); } String schedulerName = parameter.getSchedulerName(); String jobName = parameter.getJobName(); String jobGroup = parameter.getJobGroup(); String jobClass = parameter.getJobClass(); Map<String, String> jobDataMap = parameter.getJobDataMap(); String description = parameter.getDescription(); // 转换类型 Map<String, Object> jobDataMapObject = new LinkedHashMap<String, Object>(); if (jobDataMap != null) { jobDataMapObject.putAll(jobDataMap); } //添加 if (QuartzWebURL.JobURL.ADD.getURL().equals(url)) { JobServiceStrategyParameter.JobType jobType = parameter.getJobType(); if (jobType == null) { throw new IllegalArgumentException("jobType can not be null"); } // 继承org.quartz.Job添加 if (jobType.getDictValue() == JobServiceStrategyParameter.JobType.JOB.getDictValue()) { return addQuartzJob(schedulerName, jobName, jobGroup, jobClass, jobDataMapObject, description); } else { String jobClassMethodName = parameter.getJobClassMethodName();
Assert.notEmpty(jobClassMethodName, "jobClassMethodName can not be null");
6
ArcadiaPlugins/Arcadia-Spigot
src/main/java/me/redraskal/arcadia/game/WingRushGame.java
[ "public class Arcadia extends JavaPlugin {\n\n private ArcadiaAPI api;\n public Configuration mainConfiguration;\n\n public void onEnable() {\n this.api = new ArcadiaAPI(this);\n new File(this.getDataFolder().getPath() + \"/translations/\").mkdirs();\n if(new File(this.getDataFolder().getPath() + \"/translations/\").listFiles().length == 0) {\n this.getAPI().getTranslationManager().saveDefaultLocale(\"en_us.properties\");\n }\n this.getAPI().getTranslationManager().refreshCache();\n\n this.getServer().getPluginManager().registerEvents(new ConnectionListener(), this);\n this.getServer().getPluginManager().registerEvents(new DamageListener(), this);\n this.getServer().getPluginManager().registerEvents(new WorldListener(), this);\n this.getServer().getPluginManager().registerEvents(new SpectatorListener(), this);\n this.getServer().getPluginManager().registerEvents(new ChatListener(), this);\n this.getServer().getPluginManager().registerEvents(new ItemListener(), this);\n\n this.getCommand(\"spec\").setExecutor(new SpectateCommand());\n this.getCommand(\"setgame\").setExecutor(new SetGameCommand());\n\n this.mainConfiguration = new Configuration(this.getDataFolder(), \"config.yml\", this);\n this.mainConfiguration.copyDefaults();\n\n this.getAPI().getTranslationManager().setDefaultLocale(mainConfiguration.fetch().getString(\"language\"));\n this.getAPI().getTranslationManager().autoDetectLanguage\n = this.mainConfiguration.fetch().getBoolean(\"auto-detect-language\");\n\n this.getAPI().getGameRegistry().registerGame(BombardmentGame.class);\n this.getAPI().getGameRegistry().registerGame(ColorShuffleGame.class);\n this.getAPI().getGameRegistry().registerGame(DeadEndGame.class);\n this.getAPI().getGameRegistry().registerGame(ElectricFloorGame.class);\n this.getAPI().getGameRegistry().registerGame(HorseRaceGame.class);\n this.getAPI().getGameRegistry().registerGame(KingOfTheHillGame.class);\n this.getAPI().getGameRegistry().registerGame(MineFieldGame.class);\n this.getAPI().getGameRegistry().registerGame(MusicalMinecartsGame.class);\n this.getAPI().getGameRegistry().registerGame(PotionDropGame.class);\n this.getAPI().getGameRegistry().registerGame(RainbowJumpGame.class);\n this.getAPI().getGameRegistry().registerGame(RedLightGreenLightGame.class);\n this.getAPI().getGameRegistry().registerGame(SpleefGame.class);\n this.getAPI().getGameRegistry().registerGame(TrampolinioGame.class);\n this.getAPI().getGameRegistry().registerGame(WingRushGame.class);\n\n this.getAPI().getGameRegistry().setVotingData(BombardmentGame.class,\n new VotingData(new MaterialData(Material.COAL_BLOCK),\n getAPI().getTranslationManager().fetchTranslation(\"game.bombardment.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(ColorShuffleGame.class,\n new VotingData(new MaterialData(Material.WOOL),\n getAPI().getTranslationManager().fetchTranslation(\"game.colorshuffle.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(DeadEndGame.class,\n new VotingData(new MaterialData(Material.GOLD_BLOCK),\n getAPI().getTranslationManager().fetchTranslation(\"game.deadend.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(ElectricFloorGame.class,\n new VotingData(new MaterialData(Material.STAINED_GLASS, (byte) 14),\n getAPI().getTranslationManager().fetchTranslation(\"game.electricfloor.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(HorseRaceGame.class,\n new VotingData(new MaterialData(Material.GOLD_BARDING),\n getAPI().getTranslationManager().fetchTranslation(\"game.horserace.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(KingOfTheHillGame.class,\n new VotingData(new MaterialData(Material.RAW_FISH),\n getAPI().getTranslationManager().fetchTranslation(\"game.koth.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(MineFieldGame.class,\n new VotingData(new MaterialData(Material.STONE_PLATE),\n getAPI().getTranslationManager().fetchTranslation(\"game.minefield.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(MusicalMinecartsGame.class,\n new VotingData(new MaterialData(Material.MINECART),\n getAPI().getTranslationManager().fetchTranslation(\"game.musicalminecarts.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(PotionDropGame.class,\n new VotingData(new MaterialData(Material.POTION, (byte) 8197),\n getAPI().getTranslationManager().fetchTranslation(\"game.potiondrop.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(RainbowJumpGame.class,\n new VotingData(new MaterialData(Material.WOOL, (byte) 10),\n getAPI().getTranslationManager().fetchTranslation(\"game.rainbowjump.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(RedLightGreenLightGame.class,\n new VotingData(new MaterialData(Material.WOOL, (byte) 14),\n getAPI().getTranslationManager().fetchTranslation(\"game.redlightgreenlight.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(SpleefGame.class,\n new VotingData(new MaterialData(Material.SNOW_BLOCK),\n getAPI().getTranslationManager().fetchTranslation(\"game.spleef.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(TrampolinioGame.class,\n new VotingData(new MaterialData(Material.WOOL, (byte) 15),\n getAPI().getTranslationManager().fetchTranslation(\"game.trampolinio.name\").build()));\n this.getAPI().getGameRegistry().setVotingData(WingRushGame.class,\n new VotingData(new MaterialData(Material.ELYTRA),\n getAPI().getTranslationManager().fetchTranslation(\"game.wingrush.name\").build()));\n\n this.mainConfiguration.fetch().getStringList(\"default-rotation\").forEach(line -> {\n try {\n Class<? extends BaseGame> clazz = (Class<? extends BaseGame>) Class.forName(line);\n this.getAPI().getGameManager().getRotation().addGame(clazz);\n } catch (Exception e) {\n e.printStackTrace();\n }\n });\n\n this.mainConfiguration.fetch().getStringList(\"map-directories\").forEach(line -> {\n File mapFolder = new File(line.replace(\"%data_folder%\", this.getDataFolder().getPath()));\n mapFolder.mkdirs();\n this.getAPI().getMapRegistry().loadMaps(mapFolder);\n });\n\n if(this.mainConfiguration.fetch().getBoolean(\"randomize\")) {\n this.getAPI().getGameManager().getRotation().setRotationOrder(RotationOrder.RANDOM);\n }\n if(this.mainConfiguration.fetch().getBoolean(\"allow-game-voting\")) {\n this.getAPI().getGameManager().getRotation().setRotationOrder(RotationOrder.VOTE);\n }\n if(this.mainConfiguration.fetch().getBoolean(\"randomize-first-rotation\")) {\n this.getAPI().getGameManager().getRotation().shuffle();\n }\n this.nextGameInRotation(true);\n\n if(this.getServer().getPluginManager().isPluginEnabled(\"UltraCosmetics\")) {\n this.getServer().getPluginManager().registerEvents(new UltraCosmeticsSupport(), this);\n }\n }\n\n public void onDisable() {\n this.getAPI().getGameManager().setGameState(GameState.FINISHED);\n for(Player player : Bukkit.getOnlinePlayers()) {\n if(player.getVehicle() != null) {\n Entity vehicle = player.getVehicle();\n vehicle.eject();\n vehicle.remove();\n }\n this.getAPI().getGameManager().setAlive(player, false);\n }\n this.getAPI().getTranslationManager().kickPlayers(\"common.server-restarting\");\n removeCustomWorlds();\n }\n\n public void removeCustomWorlds() {\n if(this.getAPI().getMapRegistry().getCurrentWorld() != null) {\n this.getAPI().getMapRegistry().unloadWorld(this.getAPI().getMapRegistry().getCurrentWorld());\n }\n if(this.getAPI().getMapRegistry().oldWorld != null) {\n this.getAPI().getMapRegistry().unloadWorld(this.getAPI().getMapRegistry().oldWorld);\n }\n }\n\n /**\n * Switches to the next game in the rotation!\n */\n public void nextGameInRotation(boolean first) {\n if(!first) this.getAPI().getGameManager().getRotation().nextGame();\n List<GameMap> possibleMaps = this.getAPI().getGameRegistry().getMaps(this.getAPI().getGameManager().getRotation().getCurrentGame());\n this.getAPI().getGameManager().setCurrentGame(\n this.getAPI().getGameManager().getRotation().getCurrentGame(),\n possibleMaps.get(new Random().nextInt(possibleMaps.size())));\n }\n\n /**\n * Returns the fun API for this madness.\n * @return\n */\n public ArcadiaAPI getAPI() {\n return this.api;\n }\n}", "public class Freeze implements Listener {\n\n private final ArmorStand entity;\n private final Player player;\n\n public Freeze(Player player) {\n this.player = player;\n this.entity = player.getLocation().getWorld().spawn(player.getLocation(),\n ArmorStand.class);\n Arcadia.getPlugin(Arcadia.class).getServer()\n .getPluginManager().registerEvents(this, Arcadia.getPlugin(Arcadia.class));\n entity.setVisible(false);\n entity.setGravity(false);\n entity.setBasePlate(false);\n entity.setSmall(false);\n entity.setCanPickupItems(false);\n new BukkitRunnable() {\n public void run() {\n entity.addPassenger(player);\n }\n }.runTaskLater(Arcadia.getPlugin(Arcadia.class), 1L);\n }\n\n @EventHandler\n public void onEntityDamage(EntityDamageEvent event) {\n if(event.getEntity().getUniqueId() == entity.getUniqueId())\n event.setCancelled(true);\n if(event.getEntity().getUniqueId() == player.getUniqueId())\n event.setCancelled(true);\n }\n\n @EventHandler\n public void onEntityDamaged(EntityDamageByEntityEvent event) {\n if(event.getDamager().getUniqueId() == player.getUniqueId())\n event.setCancelled(true);\n }\n\n @EventHandler\n public void onEntityManipulate(PlayerArmorStandManipulateEvent event) {\n if(event.getRightClicked().getUniqueId() == entity.getUniqueId())\n event.setCancelled(true);\n }\n\n @EventHandler\n public void onPluginDisable(PluginDisableEvent event) {\n if(event.getPlugin() == Arcadia.getPlugin(Arcadia.class)) {\n destroy();\n }\n }\n\n public boolean destroy() {\n if(entity.isDead()) return false;\n entity.remove();\n HandlerList.unregisterAll(this);\n return true;\n }\n}", "public class Utils {\n\n public static String formatTime(int minutes, int seconds) {\n String temp = \"\";\n if(minutes < 10) temp+=\"0\";\n temp+=minutes;\n temp+=\":\";\n if(seconds < 10) temp+=\"0\";\n temp+=seconds;\n return temp;\n }\n\n public static String formatTimeFancy(int minutes, int seconds) {\n String temp = \"\";\n if(minutes > 0) temp+=minutes+\"m\";\n if(seconds > 0) temp+=seconds+\"s\";\n return temp;\n }\n\n private static Map<DyeColor, ChatColor> dyeChatMap;\n static {\n dyeChatMap = Maps.newHashMap();\n dyeChatMap.put(DyeColor.BLACK, ChatColor.DARK_GRAY);\n dyeChatMap.put(DyeColor.BLUE, ChatColor.DARK_BLUE);\n dyeChatMap.put(DyeColor.BROWN, ChatColor.GOLD);\n dyeChatMap.put(DyeColor.CYAN, ChatColor.AQUA);\n dyeChatMap.put(DyeColor.GRAY, ChatColor.GRAY);\n dyeChatMap.put(DyeColor.GREEN, ChatColor.DARK_GREEN);\n dyeChatMap.put(DyeColor.LIGHT_BLUE, ChatColor.BLUE);\n dyeChatMap.put(DyeColor.LIME, ChatColor.GREEN);\n dyeChatMap.put(DyeColor.MAGENTA, ChatColor.LIGHT_PURPLE);\n dyeChatMap.put(DyeColor.ORANGE, ChatColor.GOLD);\n dyeChatMap.put(DyeColor.PINK, ChatColor.LIGHT_PURPLE);\n dyeChatMap.put(DyeColor.PURPLE, ChatColor.DARK_PURPLE);\n dyeChatMap.put(DyeColor.RED, ChatColor.DARK_RED);\n dyeChatMap.put(DyeColor.SILVER, ChatColor.GRAY);\n dyeChatMap.put(DyeColor.WHITE, ChatColor.WHITE);\n dyeChatMap.put(DyeColor.YELLOW, ChatColor.YELLOW);\n }\n\n public static ChatColor convertDyeColor(DyeColor dyeColor) {\n return dyeChatMap.get(dyeColor);\n }\n\n public static String parseWinner(Player winner) {\n if(winner == null) return Arcadia.getPlugin(Arcadia.class).getAPI().getTranslationManager()\n .fetchTranslation(\"ui.unknown-player\").build();\n return winner.getName();\n }\n\n public static Location parseLocation(String location) {\n if(location.split(\",\").length > 3) {\n return new Location(Arcadia.getPlugin(Arcadia.class).getAPI().getMapRegistry().getCurrentWorld(),\n Double.valueOf(location.split(\",\")[0]), Double.valueOf(location.split(\",\")[1]), Double.valueOf(location.split(\",\")[2]),\n Float.valueOf(location.split(\",\")[3]), Float.valueOf(location.split(\",\")[4]));\n } else {\n return new Location(Arcadia.getPlugin(Arcadia.class).getAPI().getMapRegistry().getCurrentWorld(),\n Double.valueOf(location.split(\",\")[0]), Double.valueOf(location.split(\",\")[1]), Double.valueOf(location.split(\",\")[2]));\n }\n }\n\n public static MaterialData parseMaterialData(String data) {\n if(data.split(\":\").length > 1) {\n return new MaterialData(Material.getMaterial(data.split(\":\")[0]),\n Integer.valueOf(data.split(\":\")[1]).byteValue());\n } else {\n return new MaterialData(Material.getMaterial(data.split(\":\")[0]));\n }\n }\n\n public static String getNMSVersion() {\n return Bukkit.getServer().getClass().getPackage().getName().replace(\".\", \",\").split(\",\")[3];\n }\n\n public static boolean fullyUnloadWorld(World world) {\n for(Chunk chunk : world.getLoadedChunks()) {\n chunk.unload(false);\n }\n if(Bukkit.unloadWorld(world, false)) {\n flushRegionFileCache();\n FileUtils.deleteDirectory(new File(Bukkit.getWorldContainer().getAbsolutePath(), world.getName()));\n return true;\n }\n return false;\n }\n\n public static void flushRegionFileCache() {\n try {\n Method method = Class.forName(\"net.minecraft.server.\" + getNMSVersion() + \".RegionFileCache\").getMethod(\"a\");\n method.invoke(null);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public static void resetPlayer(Player player) {\n player.setLevel(0);\n player.setExp(0);\n player.setFoodLevel(20);\n player.setHealth(20);\n player.setHealthScale(20);\n player.setExhaustion(0);\n player.getInventory().clear();\n ItemStack blankItem = new ItemStack(Material.STAINED_GLASS_PANE, 1, (byte) 15);\n ItemMeta blankMeta = blankItem.getItemMeta();\n blankMeta.setDisplayName(\"\" + ChatColor.RED);\n blankItem.setItemMeta(blankMeta);\n for(int i=9; i<=35; i++) {\n player.getInventory().setItem(i, blankItem);\n }\n player.getInventory().setHelmet(new ItemStack(Material.AIR, 1));\n player.getInventory().setChestplate(new ItemStack(Material.AIR, 1));\n player.getInventory().setLeggings(new ItemStack(Material.AIR, 1));\n player.getInventory().setBoots(new ItemStack(Material.AIR, 1));\n for(PotionEffect potionEffect : player.getActivePotionEffects()) {\n player.removePotionEffect(potionEffect.getType());\n }\n player.setFireTicks(0);\n }\n\n public static void setSpacer(Player player, int slot) {\n ItemStack blankItem = new ItemStack(Material.STAINED_GLASS_PANE, 1, (byte) 15);\n ItemMeta blankMeta = blankItem.getItemMeta();\n blankMeta.setDisplayName(\"\" + ChatColor.RED);\n blankItem.setItemMeta(blankMeta);\n player.getInventory().setItem(slot, blankItem);\n }\n\n public static List<Map.Entry<String, Integer>> entriesSortedByValues(Map<String,Integer> map) {\n List<Map.Entry<String,Integer>> sortedEntries = new ArrayList<>(map.entrySet());\n Collections.sort(sortedEntries,\n new Comparator<Map.Entry<String, Integer>>() {\n @Override\n public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {\n return e2.getValue().compareTo(e1.getValue());\n }\n }\n );\n return sortedEntries;\n }\n\n public static org.bukkit.util.Vector getRandomCircleVector() {\n double rnd = new Random().nextDouble() * 2.0D * Math.PI;\n double x = Math.cos(rnd);\n double z = Math.sin(rnd);\n return new org.bukkit.util.Vector(x, 0.0D, z);\n }\n\n public static Location getLocationAroundCircle(Location center, double radius, double angleInRadian) {\n double x = center.getX() + radius * Math.cos(angleInRadian);\n double z = center.getZ() + radius * Math.sin(angleInRadian);\n double y = center.getY();\n\n Location loc = new Location(center.getWorld(), x, y, z);\n org.bukkit.util.Vector difference = center.toVector().clone().subtract(loc.toVector());\n loc.setDirection(difference);\n\n return loc;\n }\n\n public static void showNotification(String title, String icon,\n AdvancementAPI.FrameType frameType, Player... players) {\n AdvancementAPI.builder(new NamespacedKey(\"test\", \"custom/\" + UUID.randomUUID().toString()))\n .title(title)\n .description(\"\")\n .icon(icon)\n .hidden(false)\n .toast(true)\n .announce(false)\n .trigger(AdvancementAPI.Trigger.builder(AdvancementAPI.Trigger.TriggerType.IMPOSSIBLE, \"default\"))\n .background(\"minecraft:textures/gui/advancements/backgrounds/stone.png\")\n .frame(frameType)\n .build().show(Arcadia.getPlugin(Arcadia.class), players);\n }\n}", "public abstract class BaseGame implements Listener {\n\n private final ArcadiaAPI api;\n\n private final String name;\n private final SidebarSettings sidebarSettings;\n private Sidebar sidebar;\n private GameMap gameMap;\n private final String description;\n private String[] requiredSettings;\n private List<Player> deathOrder = new ArrayList<Player>();\n public List<Player> spectatorCache = new ArrayList<Player>();\n\n public boolean allowPVP = false;\n public boolean killOnMapExit = true;\n public List<MaterialData> breakableBlocks = new ArrayList<>();\n\n /**\n * The base game layout.\n * @param name\n * @param requiredSettings\n * @param description\n */\n public BaseGame(String name, String[] requiredSettings, SidebarSettings sidebarSettings, GameMap gameMap, String description) {\n Preconditions.checkNotNull(name, \"Game name cannot be null\");\n Preconditions.checkNotNull(name, \"Description cannot be null\");\n this.name = name;\n if(requiredSettings != null) {\n this.requiredSettings = requiredSettings;\n } else {\n this.requiredSettings = new String[]{};\n }\n this.description = description;\n List<String> defaultRequiredSettings = new ArrayList<String>();\n for(String setting : this.requiredSettings) defaultRequiredSettings.add(setting);\n defaultRequiredSettings.add(\"spectatorLocation\");\n defaultRequiredSettings.add(\"mapBoundsA\");\n defaultRequiredSettings.add(\"mapBoundsB\");\n this.requiredSettings = defaultRequiredSettings\n .toArray(new String[defaultRequiredSettings.size()]);\n this.sidebarSettings = sidebarSettings;\n try {\n this.sidebar = sidebarSettings.getClazz().newInstance();\n } catch (Exception e) {\n e.printStackTrace();\n }\n this.api = Arcadia.getPlugin(Arcadia.class).getAPI();\n this.gameMap = gameMap;\n }\n\n @EventHandler\n public void onPlayerDeath(PlayerAliveStatusEvent event) {\n if(!event.isAlive() && !deathOrder.contains(event.getPlayer())) {\n deathOrder.add(event.getPlayer());\n }\n }\n\n /**\n * Kills all the players, which ends the game.\n */\n public void endGame() {\n GameManager manager = this.getAPI().getGameManager();\n for (Player player : Bukkit.getOnlinePlayers()) {\n if (manager.isAlive(player)) {\n manager.setAlive(player, false);\n }\n }\n }\n\n /**\n * Returns the list of players who died in order.\n * @return\n */\n public List<Player> getDeathOrder() {\n return this.deathOrder;\n }\n\n /**\n * Returns the fun API :D\n * @return\n */\n public ArcadiaAPI getAPI() {\n return this.api;\n }\n\n /**\n * Returns the game name.\n * @return\n */\n public String getName() {\n return this.name;\n }\n\n /**\n * Returns all the required settings for a map.\n * @return\n */\n public String[] getRequiredSettings() {\n return this.requiredSettings;\n }\n\n /**\n * Returns the game description (line-by-line).\n * @return\n */\n public String getDescription() {\n return this.description;\n }\n\n /**\n * Returns the current GameMap.\n * @return\n */\n public GameMap getGameMap() {\n return this.gameMap;\n }\n\n /**\n * Returns the Sidebar instance.\n * @return\n */\n public Sidebar getSidebar() {\n return this.sidebar;\n }\n\n /**\n * Returns the SidebarSettings instance.\n * @return\n */\n public SidebarSettings getSidebarSettings() {\n return this.sidebarSettings;\n }\n\n /**\n * This event is called when a map is loaded in.\n * (Right before the countdown begins)\n */\n public abstract void onPreStart();\n\n /**\n * This event is called after the game countdown\n * has ended.\n */\n public abstract void onGameStart();\n\n /**\n * This event is called once the game has ended.\n * (Due to a winner, or the maximum time reached)\n */\n public abstract void onGameEnd();\n}", "public class GameMap {\n\n private final String name;\n private final File mapDirectory;\n private final Map<String, Object> settings = new HashMap<>();\n\n /**\n * Initializes a new GameMap instance used in the game system.\n * @param name\n * @param mapDirectory\n */\n public GameMap(String name, File mapDirectory) {\n Preconditions.checkNotNull(name, \"Map name cannot be null\");\n Preconditions.checkNotNull(mapDirectory, \"Map directory cannot be null\");\n this.name = name;\n this.mapDirectory = mapDirectory;\n }\n\n /**\n * Returns the map name.\n * @return\n */\n public String getName() {\n return this.name;\n }\n\n /**\n * Returns the map directory.\n * @return\n */\n public File getMapDirectory() {\n return this.mapDirectory;\n }\n\n /**\n * Returns the specified map setting if it exists.\n * @param key\n * @return\n */\n public Object fetchSetting(String key) {\n if(!settings.containsKey(key)) return null;\n return settings.get(key);\n }\n\n /**\n * Returns true if the specified map setting exists.\n * @param key\n * @return\n */\n public boolean doesSettingExist(String key) {\n return settings.containsKey(key);\n }\n\n /**\n * Modifies a setting as long as the Object is not null.\n * @param key\n * @param value\n */\n public void modifySetting(String key, Object value) {\n Preconditions.checkNotNull(value, \"Setting cannot be null\");\n settings.put(key, value);\n }\n}", "public class SidebarSettings {\n\n private final Class<? extends Sidebar> clazz;\n private final WinMethod winMethod;\n private final int gameMinutes;\n private final int gameSeconds;\n\n public SidebarSettings(Class<? extends Sidebar> clazz,\n WinMethod winMethod, int gameMinutes, int gameSeconds) {\n this.clazz = clazz;\n this.winMethod = winMethod;\n this.gameMinutes = gameMinutes;\n this.gameSeconds = gameSeconds+1;\n }\n\n public Class<? extends Sidebar> getClazz() {\n return this.clazz;\n }\n\n public WinMethod getWinMethod() {\n return this.winMethod;\n }\n\n public int getGameMinutes() {\n return this.gameMinutes;\n }\n\n public int getGameSeconds() {\n return this.gameSeconds;\n }\n}", "public enum WinMethod {\n\n LAST_PLAYER_STANDING(0),\n HIGHEST_SCORE(1);\n\n private final int id;\n\n private WinMethod(int id) {\n this.id = id;\n }\n\n public int getID() {\n return this.id;\n }\n\n public Player calculateWinner(int place) {\n ArcadiaAPI api = Arcadia.getPlugin(Arcadia.class).getAPI();\n if(this.id == 0) {\n List<Player> deathOrder = api.getGameManager().getCurrentGame().getDeathOrder();\n Iterator<Player> iterator = deathOrder.iterator();\n while(iterator.hasNext()) {\n Player next = iterator.next();\n if(api.getGameManager().getCurrentGame().spectatorCache.contains(next)) {\n iterator.remove();\n }\n }\n if(deathOrder.size() > (deathOrder.size()-place) && (deathOrder.size()-place) > -1) {\n return deathOrder.get((deathOrder.size()-place));\n } else {\n return null;\n }\n }\n if(this.id == 1) {\n Objective sidebar = api.getGameManager().getCurrentGame().getSidebar().getSidebar();\n Map<String, Integer> scores = new HashMap<>();\n Bukkit.getOnlinePlayers().forEach(player -> {\n if(sidebar.getScore(player.getName()) != null) {\n if(!api.getGameManager().getCurrentGame().spectatorCache.contains(player)) {\n scores.put(player.getUniqueId().toString(), sidebar.getScore(player.getName()).getScore());\n }\n }\n });\n List<Map.Entry<String, Integer>> sorted = Utils.entriesSortedByValues(scores);\n if(sorted.size() > (place-1) && (place-1) > -1) {\n return Bukkit.getPlayer(UUID.fromString(sorted.get((place-1)).getKey()));\n } else {\n return null;\n }\n }\n return null;\n }\n}", "public class ScoreSidebar extends Sidebar {\n\n public boolean removeDeadPlayers = false;\n public boolean fixScoreboard = true;\n\n @Override\n public void onCreation() {\n ArcadiaAPI api = Arcadia.getPlugin(Arcadia.class).getAPI();\n for(Player player : Bukkit.getOnlinePlayers()) {\n if(!api.getGameManager().isAlive(player)) continue;\n this.setScore(player, 0);\n }\n }\n\n @EventHandler\n public void onPlayerStatus(PlayerAliveStatusEvent event) {\n if(!event.isAlive() && removeDeadPlayers) {\n this.getSidebar().getScoreboard().resetScores(event.getPlayer().getName());\n }\n }\n\n /**\n * Updates the specified Player's score.\n * @param player\n * @param score\n */\n public void setScore(Player player, int score) {\n this.getSidebar().getScore(player.getName()).setScore(score);\n }\n\n /**\n * Returns the specified Player's score.\n * @param player\n * @return\n */\n public int getScore(Player player) {\n if(this.getSidebar().getScore(player) != null) {\n return this.getSidebar().getScore(player).getScore();\n }\n return 0;\n }\n}" ]
import me.redraskal.arcadia.Arcadia; import me.redraskal.arcadia.Freeze; import me.redraskal.arcadia.Utils; import me.redraskal.arcadia.api.game.BaseGame; import me.redraskal.arcadia.api.map.GameMap; import me.redraskal.arcadia.api.scoreboard.SidebarSettings; import me.redraskal.arcadia.api.scoreboard.WinMethod; import me.redraskal.arcadia.api.scoreboard.defaults.ScoreSidebar; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List;
package me.redraskal.arcadia.game; public class WingRushGame extends BaseGame { private Location startLocationCenter; private List<Freeze> freezeList = new ArrayList<>(); public WingRushGame(GameMap gameMap) { super(Arcadia.getPlugin(Arcadia.class).getAPI().getTranslationManager().fetchTranslation("game.wingrush.name").build(), new String[]{"startPositionCenter"},
new SidebarSettings(ScoreSidebar.class,
7
aponom84/MetrizedSmallWorld
src/main/java/org/latna/msw/evaluation/WikiSparseAggregationTest.java
[ "public abstract class MetricElement {\n private final List<MetricElement> friends;\n\n public MetricElement() {\n friends = Collections.synchronizedList(new ArrayList());\n }\n \n /**\n * Calculate metric between current object and another.\n * @param gme any element for whose metric can be calculated. Any element from domain set. \n * @return distance value\n */\n public abstract double calcDistance(MetricElement gme);\n\n public synchronized List<MetricElement> getAllFriends() {\n return friends;\n }\n\n public List<MetricElement> getAllFriendsOfAllFriends() {\n HashSet <MetricElement> hs=new HashSet();\n hs.add(this);\n for(int i=0;i<friends.size();i++){\n hs.add(friends.get(i));\n for(int j=0;j<friends.get(i).getAllFriends().size();j++)\n hs.add(friends.get(i).getAllFriends().get(j));\n }\n return new ArrayList(hs);\n }\n\n public MetricElement getClosestElemet(MetricElement q) {\n double min=this.calcDistance(q);\n int nummin=-1;\n for(int i=0;i<friends.size();i++){\n double temp=friends.get(i).calcDistance(q);\n if(temp<min){\n nummin=i;\n min=temp;\n }\n\n }\n if(nummin==-1)\n return this;\n else\n return friends.get(nummin);\n }\n\n public SearchResult getClosestElemetSearchResult(MetricElement q) {\n SearchResult s;\n TreeSet <EvaluatedElement> set = new TreeSet();\n for(int i=0;i<friends.size();i++){\n double temp=friends.get(i).calcDistance(q);\n\n set.add(new EvaluatedElement(temp, friends.get(i)));\n\n }\n return new SearchResult(set, null);\n }\n\n public synchronized void addFriend(MetricElement e) {\n if(!friends.contains(e))\n friends.add(e);\n }\n\n public synchronized void removeFriend(MetricElement e) {\n if(friends.contains(e))\n friends.remove(e);\n }\n\n public synchronized void removeAllFriends() {\n friends.clear();\n }\n\n}", "public interface MaskValidator {\n /**\n * @param element which need to verify\n * @param query\n * @return true if element corresponds to query\n */\n public boolean validate(MetricElement element, MetricElement query);\n}", "public class MetrizedSmallWorld extends AbstractMetricStructure{\n private int initAttempts;\n private int nn;\n private int size = 0; //number of elements\n \n public MetrizedSmallWorld() {\n super();\n }\n \n /**\n * Number of closest element of approximation of Voronoi neighborhood\n * @param nn \n */\n public void setNN(int nn) {\n this.nn = nn;\n }\n \n /**\n * The number of attempts that will be used for retrieval of nn closest elements \n * in the adding algorithm\n * @param initAttempts \n */\n public void setInitAttempts(int initAttempts) {\n this.initAttempts = initAttempts;\n }\n @Override\n public void add(MetricElement newElement) {\n try {\n MetricElement enterPoint = this.getProvider().getRandomEnterPoint();\n\n //check if newElement is the first element, if true then return\n if ((enterPoint == null)) {\n elements.add(newElement);\n incSize();\n return;\n }\n\n newElement.removeAllFriends();\n\n SearchResult sr = AlgorithmLib.kSearchElementsWithAttempts(newElement, this.getProvider(), nn, initAttempts);\n\n int i = 0;\n for (EvaluatedElement ee : sr.getViewedList()) {\n if (i >= nn) {\n break;\n }\n i++;\n\n if (!newElement.getAllFriends().contains(ee.getMetricElement())) {\n newElement.addFriend(ee.getMetricElement());\n ee.getMetricElement().addFriend(newElement);\n } else {\n //because programm doesn't contain of any bugs, you will never see this error\n throw new Error(\"Algorithm bug! Ha-ha-ha. Kill your self!\");\n }\n }\n elements.add(newElement);\n incSize();\n } catch (Exception ex) {\n ex.printStackTrace();\n } catch (Throwable ex) {\n ex.printStackTrace();\n }\n }\n \n /**\n * Force remove element from the structure. Halls and gaps are possible to be appeared. \n * @param element - removed element\n */\n public void removeElement(MetricElement element) {\n for(MetricElement friend : element.getAllFriends())\n {\n friend.removeFriend(element);\n }\n elements.remove(element);\n decSize();\n \n }\n \n @Override\n public SearchResult nnSearch(MetricElement query, int attempts) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public SearchResult knnSearch(MetricElement query, int k, int attempts) {\n return AlgorithmLib.kSearchElementsWithAttempts(query, getProvider(), k, attempts);\n }\n\n public String toString() {\n return \"Modified Algorithm nn=\" + String.valueOf(nn) + \" initAttems=\" + String.valueOf(initAttempts);\n }\n}", "public class AlgorithmLib {\n \n private static Random random = new Random();\n \n public static SearchResult aggregateSearch3(AbstractMetricStructure db, MetricElement query, int attempts, int exactNumberOfAnswers, MaskValidator maskValidator) {\n int k = 3;\n int foundAnswers = 0;\n int cyclesWithoutResults = 0;\n boolean goodElementFound = false;\n HashSet <MetricElement> globalViewedSet = new HashSet <MetricElement> ();\n \n while (cyclesWithoutResults < 8) {\n SearchResult res = AlgorithmLib.kSearchElements(query, db.provider.getRandomEnterPoint(), k, globalViewedSet);\n goodElementFound = false;\n \n \n Set visitedSet = new HashSet <MetricElement>();\n TreeSet <EvaluatedElement> candidateSet = new TreeSet();\n for (EvaluatedElement ee: res.getViewedList()) {\n //globalViewedSet.add(ee.getMetricElement());\n if (maskValidator.validate(ee.getMetricElement(), query)) {\n candidateSet.add(ee); \n foundAnswers++;\n goodElementFound = true;\n } \n }\n System.out.println(\"-----\");\n\n while (!candidateSet.isEmpty()) {\n EvaluatedElement currEv = candidateSet.first();\n candidateSet.remove(currEv);\n\n for (MetricElement e: currEv.getMetricElement().getAllFriends()) {\n if (!globalViewedSet.contains(e)) {\n globalViewedSet.add(e);\n\n if ( maskValidator.validate(e,query) ) {\n foundAnswers++;\n candidateSet.add(new EvaluatedElement(e.calcDistance(query), e));\n goodElementFound = true;\n }\n } \n } \n \n System.out.println(foundAnswers + \"/\"+ exactNumberOfAnswers + \" Scaned% \" + (double)globalViewedSet.size() / (double) db.getElements().size() + \n \" found: \" + String.valueOf( (double) foundAnswers / (double) exactNumberOfAnswers ) );\n }\n \n if (!goodElementFound) \n cyclesWithoutResults++;\n else \n cyclesWithoutResults = 0;\n }\n \n \n \n \n //TODO\n return new SearchResult(null, null);\n }\n public static SearchResult aggregateSearch2(AbstractMetricStructure db, MetricElement query, int attempts, int exactNumberOfAnswers, MaskValidator maskValidator) {\n int foundAnswers = 0;\n SearchResult res = db.knnSearch(query, 10, attempts);\n HashSet <MetricElement> viewedSet = new HashSet <MetricElement> ();\n Set visitedSet = new HashSet <MetricElement>();\n TreeSet <EvaluatedElement> candidateSet = new TreeSet();\n for (EvaluatedElement ee: res.getViewedList()) {\n viewedSet.add(ee.getMetricElement());\n if (maskValidator.validate(ee.getMetricElement(), query)) {\n candidateSet.add(ee); \n foundAnswers++;\n } \n }\n System.out.println(\"-----\");\n \n while (!candidateSet.isEmpty()) {\n EvaluatedElement currEv = candidateSet.first();\n candidateSet.remove(currEv);\n \n for (MetricElement e: currEv.getMetricElement().getAllFriends()) {\n if (!viewedSet.contains(e)) {\n viewedSet.add(e);\n \n if ( maskValidator.validate(e,query) ) {\n foundAnswers++;\n candidateSet.add(new EvaluatedElement(e.calcDistance(query), e));\n }\n } \n } \n System.out.println(foundAnswers + \"/\"+ exactNumberOfAnswers + \" Scaned% \" + (double)viewedSet.size() / (double) db.getElements().size() + \n \" found: \" + String.valueOf( (double) foundAnswers / (double) exactNumberOfAnswers ) );\n }\n return res;\n }\n \n \n public static SearchResult aggregateSearch(AbstractMetricStructure db, MetricElement query, int attempts, int exactNumberOfAnswers, MaskValidator maskValidator) {\n int foundAnswers = 0;\n SearchResult res = db.knnSearch(query, 10, attempts);\n \n EvaluatedElement start = res.getViewedList().first();\n \n HashSet <MetricElement> viewedSet = new HashSet <MetricElement> ();\n Set visitedSet = new HashSet <MetricElement>();\n TreeSet <EvaluatedElement> candidateSet = new TreeSet();\n \n List <MetricElement> newList;\n \n candidateSet.add(start);\n viewedSet.add(start.getMetricElement());\n \n boolean stillContatinsCorrespoundAnswer = false;\n \n System.out.println(\"-----\");\n \n while (!candidateSet.isEmpty()) {\n EvaluatedElement currEv = candidateSet.first();\n candidateSet.remove(currEv);\n \n stillContatinsCorrespoundAnswer = false;\n \n for (MetricElement e: currEv.getMetricElement().getAllFriends()) {\n if (!viewedSet.contains(e)) {\n viewedSet.add(e);\n \n if ( maskValidator.validate(e,query) ) {\n foundAnswers++;\n candidateSet.add(new EvaluatedElement(e.calcDistance(query), e));\n }\n } \n } \n System.out.println(foundAnswers + \"/\"+ exactNumberOfAnswers + \" Scaned% \" + (double)viewedSet.size() / (double) db.getElements().size() + \n \" found: \" + String.valueOf( (double) foundAnswers / (double) exactNumberOfAnswers ) );\n }\n return res;\n }\n \n \n \n /**\n * The simple implementation of the greedy search algorithm\n * Search the closest element to toFound in base from newEnterPoint\n */\n public static MetricElement searchElement(MetricElement tofound, MetricElement newEnterPoint) {\n MetricElement curElement=newEnterPoint,newElement;\n while(true){\n newElement=curElement.getClosestElemet(tofound);\n if(newElement==curElement)\n break;\n curElement=newElement;\n }\n return curElement;\n }\n\n \n /**\n * Performs greedy search of toFound element as query from newEnterPoint and \n * returns all elements which have been scanned by algorithm\n * @param toFound query element \n * @param newEnterPoint element from which the search starts\n * @return metric and scanned after greedy search\n */\n \n public static SearchResult searchElementSearchResult(MetricElement toFound, MetricElement newEnterPoint) {\n MetricElement curElement=newEnterPoint,newElement;\n TreeSet <EvaluatedElement> viewed = new TreeSet();\n Set <MetricElement> visitedSet = new HashSet();\n viewed.add(new EvaluatedElement(toFound.calcDistance(newEnterPoint),newEnterPoint));\n\n while(true){\n viewed.addAll(curElement.getClosestElemetSearchResult(toFound).getViewedList());\n visitedSet.add(curElement);\n \n newElement=viewed.first().getMetricElement();\n\n if(newElement==curElement)\n break;\n curElement=newElement;\n }\n return new SearchResult(viewed, visitedSet);\n }\n \n /**\n * Search the most k-closest elements to the query. \n * This algorithm has not published yet. Please, don't steal it :-) \n * Or you can publish it, but add me as co-author. (c) Alexander Ponomarenko 27.08.2012\n * @param query\n * @param newEnterPoint\n * @param k\n * @return all elements and metric values which was calculated during searching of k-closest elements\n */\n public static SearchResult kSearchElements(MetricElement query, MetricElement newEnterPoint, int k, Set <MetricElement> globalViewedSet ) {\n double lowerBound = Double.MAX_VALUE;\n\n Set visitedSet = new HashSet <MetricElement>(); //the set of elements which has used to extend our view represented by viewedSet\n\n TreeSet <EvaluatedElement> viewedSet = new TreeSet(); //the set of all elements which distance was calculated\n // Map <MetricElement, Double> viewedMap = new HashMap ();\n \n TreeSet <EvaluatedElement> candidateSet = new TreeSet(); //the set of elememts which we can use to e\n EvaluatedElement ev = new EvaluatedElement(query.calcDistance(newEnterPoint), newEnterPoint);\n\n candidateSet.add(ev);\n viewedSet.add(ev);\n globalViewedSet.add(newEnterPoint);\n //viewedMap.put(ev.getMetricElement(), ev.getDistance());\n\n while (!candidateSet.isEmpty()) {\n EvaluatedElement currEv = candidateSet.first();\n candidateSet.remove(currEv);\n lowerBound = getKDistance(viewedSet, k);\n //check condition for the lower bound\n if (currEv.getDistance() > lowerBound ) {\n break;\n }\n\n visitedSet.add(currEv.getMetricElement());\n\n List <MetricElement> neighbor = currEv.getMetricElement().getAllFriends();\n synchronized (neighbor){\n //calculate distance to each element from the neighbour\n\n for (MetricElement el: neighbor) {\n if (!globalViewedSet.contains(el) ) {\n EvaluatedElement evEl = new EvaluatedElement(query.calcDistance(el), el);\n globalViewedSet.add(el);\n viewedSet.add(evEl);\n candidateSet.add(evEl);\n\n }\n }\n }\n }\n return new SearchResult(viewedSet, visitedSet);\n }\n\n /**\n * Search of most k-closest elements to the query with several attempts\n * @param query\n * @param provider\n * @param k number of closest elements which we should to find\n * @param attempts number of search attempts\n * @return all elements with metric which values have been calculated at the searching time \n */\n\n public static SearchResult kSearchElementsWithAttempts(MetricElement query, EnterPointProvider provider, int k, int attempts) {\n Set <MetricElement> globalViewedHashSet = new HashSet <MetricElement> ();\n TreeSet <EvaluatedElement> globalViewedSet = new TreeSet();\n Set <MetricElement> visitedSet = new HashSet();\n \n for (int i = 0; i < attempts; i++) {\n SearchResult sr = kSearchElements(query, provider.getRandomEnterPoint(), k, globalViewedHashSet);\n\n globalViewedSet.addAll(sr.getViewedList());\n visitedSet.addAll(sr.getVisitedSet());\n\n }\n\n return new SearchResult(globalViewedSet, visitedSet);\n }\n \n /**\n * deprecated due of useless \n * @param query\n * @param provider\n * @param k\n * @param attempts\n * @return set of scanned elements. \n */\n public static SearchResult kSearchElementsWithAttemptsMultiThread(MetricElement query, EnterPointProvider provider, int k, int attempts) {\n ConcurrentSkipListSet <EvaluatedElement> globalViewedSet = new ConcurrentSkipListSet<> ();\n int steps = 0;\n \n List <Thread> threads = new ArrayList <>();\n \n for (int i=0; i < attempts; i++) {\n KSearchRunnable ksr = new KSearchRunnable(query, provider.getRandomEnterPoint(), k, globalViewedSet);\n threads.add(ksr);\n ksr.run();\n // SearchResult sr = kSearchElements(query, provider.getRandomEnterPoint(), k);\n // System.out.println(\"one attempt viewedSet size = \" + sr.getViewedList().size() );\n\n // globalViewedSet.addAll(sr.getViewedList());\n //check for correct\n // todo steps = steps + sr.getSteps(); \n \n }\n \n for (Thread thread : threads) {\n try {\n thread.join();\n } catch (InterruptedException ex) {\n throw new Error(ex);\n }\n }\n \n \n \n return new SearchResult(new TreeSet(globalViewedSet), null);\n }\n \n /**\n * Perform m independent k-nn searches in the different threads\n * @param query\n * @param provider\n * @param k\n * @param attempts\n * @return set of scanned elements. \n */\n public static SearchResult kSearchElementsWithAttemptsFuters(MetricElement query, EnterPointProvider provider, int k, int attempts) {\n ConcurrentSkipListSet<EvaluatedElement> globalViewedSet = new ConcurrentSkipListSet<EvaluatedElement>();\n ConcurrentSkipListSet <MetricElement> visitedSet = new ConcurrentSkipListSet <MetricElement>();\n int steps = 0;\n ExecutorService executor = Executors.newFixedThreadPool(10);\n List< Future<SearchResult>> futureList = new ArrayList<Future<SearchResult>>();\n\n for (int i = 0; i < attempts; i++) {\n Future<SearchResult> future = executor.submit(new KSearchCallable(query, provider.getRandomEnterPoint(), k));\n futureList.add(future);\n }\n\n for (Future<SearchResult> future : futureList) {\n try {\n SearchResult sr = future.get();\n\n globalViewedSet.addAll(sr.getViewedList());\n visitedSet.addAll(sr.getVisitedSet());\n //check for correct\n steps = steps + sr.getVisitedSet().size();\n \n } catch (InterruptedException ex) {\n throw new Error(ex);\n } catch (ExecutionException ex) {\n throw new Error(ex);\n }\n }\n \n executor.shutdown();\n\n return new SearchResult(new TreeSet(globalViewedSet), visitedSet);\n }\n\n private static double getKDistance(SortedSet <EvaluatedElement> treeSet, int k) {\n if (k >= treeSet.size()) return treeSet.last().getDistance();\n int i = 0;\n for (EvaluatedElement e: treeSet) {\n if (i >=k) return e.getDistance();\n i++;\n }\n\n throw new Error(\"Can not get K Distance. \");\n }\n\n /**\n * Scan list of element and returns the closest element for element @param toFound\n */\n\n public static MetricElement getTheBestElement(MetricElement toFound, List <MetricElement> elements) {\n MetricElement bestResult = null;\n double bestDistance = Double.MAX_VALUE;\n\n //пока сброс точки входа происходит случайным образом.\n for (MetricElement currElement: elements ) {\n if (currElement.calcDistance(toFound) < bestDistance) {\n bestDistance = currElement.calcDistance(toFound);\n bestResult = currElement;\n }\n }\n return bestResult;\n }\n\n /**\n *\n * @return all locals minimus after running several attempts\n */\n public static List <MetricElement> getAllSearchedElements(MetricElement toFound, int ac, EnterPointProvider provider) {\n List <MetricElement> result = new ArrayList();\n for (int i = 0; i < ac; i++) {\n MetricElement currElement = AlgorithmLib.searchElement(toFound,provider.getRandomEnterPoint());\n\n if (!result.contains(currElement)) {\n result.add(currElement);\n }\n }\n return result;\n }\n\n /**\n *\n * @return all locals minimus after they know after several attempts\n */\n public static SearchResult getAllSearchedElementsSearchResult(MetricElement toFound, int ac, EnterPointProvider provider) {\n TreeSet <EvaluatedElement> set = new TreeSet();\n Set <MetricElement> visitedSet = new HashSet();\n int step =0;\n for (int i = 0; i < ac; i++) {\n SearchResult sr = AlgorithmLib.searchElementSearchResult(toFound,provider.getRandomEnterPoint());\n\n set.addAll(sr.getViewedList());\n visitedSet.addAll(sr.getVisitedSet());\n }\n return new SearchResult(set, visitedSet);\n }\n\n public static MetricElement getLocalMin(MetricElement start, MetricElement query) {\n MetricElement current = start;\n\n MetricElement bestNext = start;\n double bestDistance = bestNext.calcDistance(query);\n do {\n current = bestNext;\n for (MetricElement x: current.getAllFriends()) {\n Double xDistance = x.calcDistance(query);\n if (xDistance < bestDistance) {\n bestNext = x;\n bestDistance = xDistance;\n }\n }\n } while (bestNext != current);\n return current;\n }\n\n public static class ElementComparator implements Comparator{\n MetricElement e;\n\n public ElementComparator(MetricElement e) {\n this.e = e;\n }\n\n\n public int compare(Object o1, Object o2) {\n MetricElement cur1=(MetricElement)o1;\n MetricElement cur2=(MetricElement)o2;\n double d1=e.calcDistance(cur1);\n double d2=e.calcDistance(cur2);\n if(d1>d2)\n return 1;\n if(d1<d2)\n return -1;\n return 0;\n }\n\n }\n\n public static MetricElement searchWithAttempts(MetricElement query, EnterPointProvider provider, int attemptsCount) {\n List <MetricElement> localMins = AlgorithmLib.getAllSearchedElements(query, attemptsCount, provider);\n return AlgorithmLib.getTheBestElement(query, localMins);\n }\n \n /**\n * \n * Useless because it do the same as method kSearchElemts with m starting points in the candidate list\n */\n public static class KSearchRunnable extends Thread {\n private MetricElement newEnterPoint;\n private MetricElement query; \n private int k;\n private ConcurrentSkipListSet <EvaluatedElement> globalViewedSet;\n public KSearchRunnable(MetricElement query, MetricElement newEnterPoint, int k, ConcurrentSkipListSet <EvaluatedElement> globalViewedSet) {\n this.newEnterPoint = newEnterPoint;\n this.query = query;\n this.k = k;\n this.globalViewedSet = globalViewedSet;\n }\n public void run() {\n double lowerBound = Double.MAX_VALUE;\n\n // Set visitedSet = new HashSet <MetricElement>(); //the set of elements which has used to extend our view represented by viewedSet\n\n \n Map <MetricElement, Double> viewedMap = new HashMap ();\n\n TreeSet <EvaluatedElement> candidateSet = new TreeSet(); //the set of elememts which we can use to e\n EvaluatedElement ev = new EvaluatedElement(query.calcDistance(newEnterPoint), newEnterPoint);\n\n candidateSet.add(ev);\n globalViewedSet.add(ev);\n viewedMap.put(ev.getMetricElement(), ev.getDistance());\n\n\n while (!candidateSet.isEmpty()) {\n EvaluatedElement currEv = candidateSet.first();\n candidateSet.remove(currEv);\n lowerBound = getKDistance(globalViewedSet, k);\n //check condition for lower bound\n if (currEv.getDistance() > lowerBound ) {\n break;\n }\n\n //\n // visitedSet.add(currEv.getMetricElement());\n\n List <MetricElement> neighbor = currEv.getMetricElement().getAllFriends();\n //calculate distance for each element from enighbor\n for (MetricElement el: neighbor) {\n if (!viewedMap.containsKey(el) ) {\n EvaluatedElement evEl = new EvaluatedElement(query.calcDistance(el), el);\n viewedMap.put(el, evEl.getDistance());\n globalViewedSet.add(evEl);\n candidateSet.add(evEl);\n\n }\n }\n\n }\n }\n \n } \n \n public static class CalculateDistance implements Callable <EvaluatedElement> {\n private MetricElement q,x;\n \n public CalculateDistance(MetricElement q, MetricElement x) {\n this.q = q;\n this.x = x;\n }\n \n public EvaluatedElement call() throws Exception {\n System.out.println(\"Calc!\");\n return new EvaluatedElement(q.calcDistance(x),x);\n }\n }\n \n public static class KSearchCallable implements Callable <SearchResult> { \n private MetricElement q, enterPoint;\n \n private int k;\n \n\n public KSearchCallable(MetricElement query, MetricElement newEnterPoint, int k) {\n this.q = query;\n this.k = k;\n this.enterPoint = newEnterPoint;\n }\n \n public SearchResult call() throws Exception {\n double lowerBound = Double.MAX_VALUE;\n\n Set visitedSet = new HashSet<MetricElement>(); //the set of elements which has used to extend our view represented by viewedSet\n\n TreeSet<EvaluatedElement> viewedSet = new TreeSet(); //the set of all elements which distance was calculated\n Map<MetricElement, Double> viewedMap = new HashMap();\n\n TreeSet<EvaluatedElement> candidateSet = new TreeSet(); //the set of elememts which we can use to e\n EvaluatedElement ev = new EvaluatedElement(q.calcDistance(enterPoint), enterPoint);\n\n candidateSet.add(ev);\n viewedSet.add(ev);\n viewedMap.put(ev.getMetricElement(), ev.getDistance());\n\n\n while (!candidateSet.isEmpty()) {\n EvaluatedElement currEv = candidateSet.first();\n candidateSet.remove(currEv);\n lowerBound = getKDistance(viewedSet, k);\n //check condition for lower bound\n if (currEv.getDistance() > lowerBound) {\n break;\n }\n\n //\n visitedSet.add(currEv.getMetricElement());\n\n List<MetricElement> neighbor = currEv.getMetricElement().getAllFriends();\n //calculate distance for each element from enighbor\n\n ExecutorService executor = Executors.newCachedThreadPool();\n List<Future<EvaluatedElement>> futureList = new ArrayList<Future<EvaluatedElement>>();\n\n for (MetricElement el : neighbor) {\n if (!viewedMap.containsKey(el)) {\n\n /* Future <EvaluatedElement> future = executor.submit(new CalculateDistance(query, el));\n futureList.add(future);\n */\n\n EvaluatedElement evEl = new EvaluatedElement(q.calcDistance(el), el);\n viewedMap.put(el, evEl.getDistance());\n viewedSet.add(evEl);\n candidateSet.add(evEl);\n\n }\n }\n\n //MetricElement currElement = candidateSet.\n }\n return new SearchResult(viewedSet, visitedSet);\n }\n \n }\n \n public static MetricElement getRandomWalkElement(MetricElement enterPoint, int numberOfSteps) {\n MetricElement curr = enterPoint;\n \n for (int i = 0; i < numberOfSteps; i++ ) {\n List <MetricElement> friends = curr.getAllFriends();\n \n synchronized (friends) {\n int r = random.nextInt(friends.size());\n \n if (r >= friends.size() ) {\n System.out.println(\"Zhopaaaa\");\n }\n \n curr = friends.get(r);\n \n }\n }\n \n return curr;\n }\n}", "public class EuclidianFactory implements MetricElementFactory, Supplier<MetricElement> {\n \n private int dimension; \n private int n; //number of elements\n private List <MetricElement> allElements;\n private static Random random = new Random();\n\n public List<MetricElement> getElements() {\n allElements = new ArrayList(n);\n \n for (int i=0; i < n; i++) {\n double x[] = new double[dimension];\n for (int j=0; j < dimension; j++) {\n x[j] = random.nextDouble();\n }\n \n allElements.add(new Euclidean(x));\n }\n return allElements;\n }\n\n public void setParameterString(String param) {\n throw new UnsupportedOperationException(\"Not supported yet.\"); //To change body of generated methods, choose Tools | Templates.\n }\n \n /*\n\n * Create factory and generate list with n uniformaly distributed elements\n * @param dimension\n * @param n - number of elements \n * @param seed - random seed\n */ \n public EuclidianFactory(int dimension, int n) {\n this.dimension = dimension;\n this.n = n;\n }\n \n public static MetricElement getRandomElement(int dimension) {\n double x[] = new double[dimension];\n for (int j=0; j < dimension; j++) {\n x[j] = random.nextDouble();\n }\n return new Euclidean(x);\n }\n \n public EuclidianFactory(int dimension, int n, double standardDeviation) {\n this.dimension = dimension;\n this.n = n;\n \n RandomEngine engine = new DRand();\n Normal normal = new Normal(0, standardDeviation, engine);\n \n allElements = new ArrayList(n);\n \n for (int i=0; i < n; i++) {\n double x[] = new double[dimension];\n for (int j=0; j < dimension; j++) {\n x[j] = normal.nextDouble();\n }\n \n allElements.add(new Euclidean(x)); \n }\n }\n \n \n public int getDimension() {\n return dimension;\n }\n\n @Override\n public MetricElement get() {\n double x[] = new double[dimension];\n for (int j=0; j < dimension; j++) {\n x[j] = random.nextDouble();\n }\n return new Euclidean(x);\n }\n}", "public class WikiSparse extends MetricElement {\n private Map <Integer, Double> termVector;\n\n public WikiSparse() {\n super();\n termVector = new HashMap();\n }\n\n public void addTerm(int termId, double value) {\n termVector.put(termId, value);\n }\n\n @Override\n public double calcDistance(MetricElement gme) {\n double res = 0;\n if (!(gme instanceof WikiSparse)) {\n throw new Error(\"You trie calculate distance for non Document type object\");\n }\n WikiSparse otherDoc = (WikiSparse) gme;\n WikiSparse doc1;\n WikiSparse doc2;\n\n if (otherDoc.termVector.size() < this.termVector.size()) {\n doc1 = otherDoc; \n doc2 = this;\n } else {\n doc1 = this;\n doc2 = otherDoc;\n }\n\n for ( Entry <Integer, Double> i : doc1.termVector.entrySet()) {\n if (doc2.termVector.containsKey(i.getKey()) ) {\n res = res + i.getValue()*doc2.termVector.get(i.getKey());\n }\n }\n\n res = res / ( doc1.getVectorLenght() * doc2.getVectorLenght() );\n res = java.lang.Math.acos(res);\n return res;\n }\n\n private double getVectorLenght() {\n double res = 0;\n\n for (Double d: termVector.values())\n res = res + d*d;\n\n return Math.sqrt(res);\n }\n /**\n * \n * @param mask\n * @return true if the term vector of current element contains all words from the mask\n */\n \n public boolean correspoundToMask(WikiSparse mask) { \n for (Integer t: mask.termVector.keySet()) {\n if (this.termVector.get(t) == null)\n return false;\n } \n return true;\n }\n\n public boolean equals(Object o) {\n WikiSparse otherDocument = (WikiSparse) o ;\n return otherDocument.termVector.equals(this.termVector);\n }\n \n \n public WikiSparse getRandomSubDoc(Random random, int len) {\n int size = termVector.size();\n WikiSparse newDoc = new WikiSparse();\n Integer [] keys = new Integer [size];\n keys = (Integer[]) termVector.keySet().toArray(keys);\n \n for (int i = 0; i < len; i++) {\n newDoc.addTerm(keys[random.nextInt(size)], 1.0/(double) len);\n }\n return newDoc;\n } \n\n}", "public class WikiSparseFactory {\n public String inputFilePath=\"G:\\\\WikiData\\\\wikipedia.txt\";\n private int maxDoc; \n private Scanner globalScanner = null;\n\n public WikiSparseFactory(String inputFilePath) {\n if (!inputFilePath.isEmpty())\n this.inputFilePath = inputFilePath;\n \n try {\n globalScanner = new Scanner(new File(this.inputFilePath));\n } catch (FileNotFoundException ex) {\n System.out.println(ex);\n }\n }\n \n public MetricElement getElement() {\n if ( !globalScanner.hasNextLine() ) \n return null;\n Scanner lineScanner = new Scanner(globalScanner.nextLine());\n \n WikiSparse newDoc = new WikiSparse();\n\n while (lineScanner.hasNext()) {\n int termId = lineScanner.nextInt();\n String d = lineScanner.next();\n double value = new Double(d);\n\n newDoc.addTerm(termId, value);\n }\n \n return newDoc;\n }\n \n public List<MetricElement> getElements(int n) {\n List <MetricElement> docList = new ArrayList(n);\n int i=0;\n while (globalScanner.hasNextLine()) {\n if (i >= n) break; \n Scanner lineScanner = new Scanner(globalScanner.nextLine());\n \n WikiSparse newDoc = new WikiSparse();\n\n while (lineScanner.hasNext()) {\n int termId = lineScanner.nextInt();\n String d = lineScanner.next();\n double value = new Double(d);\n\n newDoc.addTerm(termId, value);\n }\n docList.add(newDoc);\n \n i++;\n }\n System.out.println(i+ \" documents readed\");\n return docList;\n }\n \n public List <MetricElement> getShortQueries(int n, int wordCount, int maxWordNumber) {\n List <MetricElement> docList = new ArrayList(n);\n Random random = new Random(100);\n for (int i = 0; i < n; i++) {\n WikiSparse newDoc = new WikiSparse();\n for (int j = 0; j < wordCount; j++) \n newDoc.addTerm(random.nextInt(maxWordNumber), 1);\n docList.add(newDoc);\n }\n return docList;\n }\n \n public List<MetricElement> getShortQueriesReal(int n, int wordCount) {\n List<MetricElement> docList = new ArrayList(n);\n Random random = new Random(100);\n for (int i = 0; i < n; i++) {\n Scanner lineScanner = new Scanner(globalScanner.nextLine());\n\n WikiSparse newDoc = new WikiSparse();\n\n while (lineScanner.hasNext()) {\n int termId = lineScanner.nextInt();\n String d = lineScanner.next();\n double value = new Double(d);\n\n newDoc.addTerm(termId, value);\n\n\n }\n \n \n \n \n \n docList.add(newDoc.getRandomSubDoc(random, wordCount));\n }\n return docList;\n }\n}" ]
import org.latna.msw.MetricElement; import org.latna.msw.MaskValidator; import org.latna.msw.MetrizedSmallWorld; import org.latna.msw.AlgorithmLib; import org.latna.msw.euclidian.EuclidianFactory; import org.latna.msw.wikisparse.WikiSparse; import org.latna.msw.wikisparse.WikiSparseFactory; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit;
package org.latna.msw.evaluation; /** * V02.05.2014 * @author Alexander Ponomarenko [email protected] */ public class WikiSparseAggregationTest { public static final int NUMBER_OF_THREADS = 4; public static final String outFileName = "WikiSparceAggregate.txt"; /* public static SearchResult aggregateSearch(AbstractMetricStructure db, WikiSparse query, int attempts, int exactNumberOfAnswers) { int foundAnswers = 0; SearchResult res = db.knnSearch(query, 1, attempts); EvaluatedElement start = res.getViewedList().first(); HashSet <MetricElement> viewedSet = new HashSet <MetricElement> (); Set visitedSet = new HashSet <MetricElement>(); TreeSet <EvaluatedElement> candidateSet = new TreeSet(); List <MetricElement> newList; candidateSet.add(start); viewedSet.add(start.getMetricElement()); boolean stillContatinsCorrespoundAnswer = false; while (!candidateSet.isEmpty()) { EvaluatedElement currEv = candidateSet.first(); candidateSet.remove(currEv); stillContatinsCorrespoundAnswer = false; for (MetricElement e: currEv.getMetricElement().getAllFriends()) { if (!viewedSet.contains(e)) { viewedSet.add(e); WikiSparse ws = (WikiSparse) e; if ( ws.correspoundToMask(query) ) { foundAnswers++; candidateSet.add(new EvaluatedElement(e.calcDistance(query), e)); } } } System.out.println("Scaned: " + viewedSet.size() + " found: " + String.valueOf( (double) foundAnswers / (double) exactNumberOfAnswers ) ); } return res; } */ /** * Scan input string and run the test * @param args the command line arguments */ public static void main(String[] args) throws IOException { /*int nn = Integer.valueOf(args[0]); int k = Integer.valueOf(args[1]); int initAttempts = Integer.valueOf(args[2]); int minAttempts = Integer.valueOf(args[3]); int maxAttempts = Integer.valueOf(args[4]); int dataBaseSize = Integer.valueOf(args[5]); int querySetSize = Integer.valueOf(args[6]); int testSeqSize = Integer.valueOf(args[7]); String dataPath = args[8]; String queryPath = args[9]; */ // int[] checkPoints = {1000, 5000, 10000, 50000, 100000, 500000}; int[] checkPoints = {1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 100000, 500000}; // int[] checkPoints = {1000,5000, 10000, 50000,100000,500000, 1000000,2000000,5000000,10000000,20000000, 50000000}; // int[] checkPoints = {1000}; // int dimensionality = 30; int nn = 20; //number of nearest neighbors used in construction algorithm to approximate voronoi neighbor int k = 5; //number of k-closest elements for the knn search int initAttempts = 4; //number of search attempts used during the contruction of the structure int minAttempts = 1; //minimum number of attempts used during the test search int maxAttempts = 10; //maximum number of attempts //int dataBaseSize = 1000; // int dataBaseSize = 0; the restriction on the number of elements in the data structure. To set no restriction set value = 0 int querySetSize = 10; //the restriction on the number of quleries. To set no restriction set value = 0 //number elements in the random selected subset used to verify accuracy of the search. int elementNumber = 0; int lastSize = 0; // WikiSparse Factory factory = new WikiSparseFactory("C:\\Users\\Aponom\\wikipedia.txt"); WikiSparseFactory factory = new WikiSparseFactory("E:\\WikiData\\wikipedia.txt"); WikiSparseFactory queryFactory = new WikiSparseFactory(""); MetrizedSmallWorld db = new MetrizedSmallWorld(); db.setNN(nn); db.setInitAttempts(initAttempts);
List <MetricElement> testQueries = queryFactory.getShortQueries(querySetSize, 2, 10000);
0
desht/ScrollingMenuSign
src/main/java/me/desht/scrollingmenusign/views/SMSSpoutView.java
[ "public class SMSException extends DHUtilsException {\n\n private static final long serialVersionUID = 1L;\n\n public SMSException(String message) {\n super(message);\n }\n\n}", "public class SMSMenu extends Observable implements SMSPersistable, SMSUseLimitable, ConfigurationListener, Comparable<SMSMenu> {\n public static final String FAKE_SPACE = \"\\u203f\";\n\n public static final String AUTOSORT = \"autosort\";\n public static final String DEFAULT_CMD = \"defcmd\";\n public static final String OWNER = \"owner\";\n public static final String TITLE = \"title\";\n public static final String ACCESS = \"access\";\n public static final String REPORT_USES = \"report_uses\";\n public static final String GROUP = \"group\";\n\n private final String name;\n private final List<SMSMenuItem> items = new ArrayList<SMSMenuItem>();\n private final Map<String, Integer> itemMap = new HashMap<String, Integer>();\n private final SMSRemainingUses uses;\n private final AttributeCollection attributes; // menu attributes to be displayed and/or edited by players\n\n private String title; // cache colour-parsed version of the title attribute\n private UUID ownerId; // cache owner's UUID (could be null)\n private boolean autosave;\n private boolean inThaw;\n\n /**\n * Construct a new menu\n *\n * @param name Name of the menu\n * @param title Title of the menu\n * @param owner Owner of the menu\n * @throws SMSException If there is already a menu at this location\n * @deprecated use {@link SMSMenu(String,String,Player)} or {@link SMSMenu(String,String, org.bukkit.plugin.Plugin )}\n */\n @Deprecated\n public SMSMenu(String name, String title, String owner) {\n this.name = name;\n this.uses = new SMSRemainingUses(this);\n this.attributes = new AttributeCollection(this);\n registerAttributes();\n setAttribute(OWNER, owner == null ? ScrollingMenuSign.CONSOLE_OWNER : owner);\n ownerId = ScrollingMenuSign.CONSOLE_UUID;\n setAttribute(TITLE, title);\n autosave = true;\n }\n\n /**\n * Construct a new menu\n *\n * @param name Name of the menu\n * @param title Title of the menu\n * @param owner Owner of the menu\n * @throws SMSException If there is already a menu at this location\n */\n public SMSMenu(String name, String title, Player owner) {\n this.name = name;\n this.uses = new SMSRemainingUses(this);\n this.attributes = new AttributeCollection(this);\n registerAttributes();\n setAttribute(OWNER, owner == null ? ScrollingMenuSign.CONSOLE_OWNER : owner.getName());\n ownerId = owner == null ? ScrollingMenuSign.CONSOLE_UUID : owner.getUniqueId();\n setAttribute(TITLE, title);\n autosave = true;\n }\n\n /**\n * Construct a new menu\n *\n * @param name Name of the menu\n * @param title Title of the menu\n * @param owner Owner of the menu\n * @throws SMSException If there is already a menu at this location\n */\n public SMSMenu(String name, String title, Plugin owner) {\n this.name = name;\n this.uses = new SMSRemainingUses(this);\n this.attributes = new AttributeCollection(this);\n registerAttributes();\n setAttribute(OWNER, owner == null ? ScrollingMenuSign.CONSOLE_OWNER : \"[\" + owner.getName() + \"]\");\n ownerId = ScrollingMenuSign.CONSOLE_UUID;\n setAttribute(TITLE, title);\n autosave = true;\n }\n\n /**\n * Construct a new menu from a frozen configuration object.\n *\n * @param node A ConfigurationSection containing the menu's properties\n * @throws SMSException If there is already a menu at this location\n */\n @SuppressWarnings(\"unchecked\")\n public SMSMenu(ConfigurationSection node) {\n SMSPersistence.mustHaveField(node, \"name\");\n SMSPersistence.mustHaveField(node, \"title\");\n SMSPersistence.mustHaveField(node, \"owner\");\n\n inThaw = true;\n\n this.name = node.getString(\"name\");\n this.uses = new SMSRemainingUses(this, node.getConfigurationSection(\"usesRemaining\"));\n this.attributes = new AttributeCollection(this);\n registerAttributes();\n String id = node.getString(\"owner_id\");\n if (id != null && !id.isEmpty()) {\n this.ownerId = UUID.fromString(id);\n } else {\n this.ownerId = ScrollingMenuSign.CONSOLE_UUID;\n }\n\n // migration of group -> owner_group access in 2.4.0\n if (!node.contains(\"group\") && node.contains(ACCESS) && node.getString(ACCESS).equals(\"GROUP\")) {\n LogUtils.info(\"menu \" + name + \": migrate GROUP -> OWNER_GROUP access\");\n node.set(\"access\", \"OWNER_GROUP\");\n }\n\n for (String k : node.getKeys(false)) {\n if (!node.isConfigurationSection(k) && attributes.hasAttribute(k)) {\n setAttribute(k, node.getString(k));\n }\n }\n\n List<Map<String, Object>> items = (List<Map<String, Object>>) node.getList(\"items\");\n if (items != null) {\n for (Map<String, Object> item : items) {\n MemoryConfiguration itemNode = new MemoryConfiguration();\n // need to expand here because the item may contain a usesRemaining object - item could contain a nested map\n SMSPersistence.expandMapIntoConfig(itemNode, item);\n SMSMenuItem menuItem = new SMSMenuItem(this, itemNode);\n SMSMenuItem actual = menuItem.uniqueItem();\n if (!actual.getLabel().equals(menuItem.getLabel()))\n LogUtils.warning(\"Menu '\" + getName() + \"': duplicate item '\" + menuItem.getLabelStripped() + \"' renamed to '\" + actual.getLabelStripped() + \"'\");\n addItem(actual);\n }\n }\n\n inThaw = false;\n autosave = true;\n }\n\n public void setAttribute(String k, String val) {\n SMSValidate.isTrue(attributes.contains(k), \"No such view attribute: \" + k);\n attributes.set(k, val);\n }\n\n private void registerAttributes() {\n attributes.registerAttribute(AUTOSORT, false, \"Always keep the menu sorted?\");\n attributes.registerAttribute(DEFAULT_CMD, \"\", \"Default command to run if item has no command\");\n attributes.registerAttribute(OWNER, \"\", \"Player who owns this menu\");\n attributes.registerAttribute(GROUP, \"\", \"Permission group for this menu\");\n attributes.registerAttribute(TITLE, \"\", \"The menu's displayed title\");\n attributes.registerAttribute(ACCESS, SMSAccessRights.ANY, \"Who may use this menu\");\n attributes.registerAttribute(REPORT_USES, true, \"Tell the player when remaining uses have changed?\");\n }\n\n public Map<String, Object> freeze() {\n HashMap<String, Object> map = new HashMap<String, Object>();\n\n List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();\n for (SMSMenuItem item : items) {\n l.add(item.freeze());\n }\n for (String key : attributes.listAttributeKeys(false)) {\n if (key.equals(TITLE)) {\n map.put(key, SMSUtil.escape(attributes.get(key).toString()));\n } else {\n map.put(key, attributes.get(key).toString());\n }\n }\n map.put(\"name\", getName());\n map.put(\"items\", l);\n map.put(\"usesRemaining\", uses.freeze());\n map.put(\"owner_id\", getOwnerId() == null ? \"\" : getOwnerId().toString());\n\n return map;\n }\n\n public AttributeCollection getAttributes() {\n return attributes;\n }\n\n /**\n * Get the menu's unique name\n *\n * @return Name of this menu\n */\n public String getName() {\n return name;\n }\n\n /**\n * Get the menu's title string\n *\n * @return The title string\n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Set the menu's title string\n *\n * @param newTitle The new title string\n */\n public void setTitle(String newTitle) {\n attributes.set(TITLE, newTitle);\n }\n\n /**\n * Get the menu's owner string\n *\n * @return Name of the menu's owner\n */\n public String getOwner() {\n return attributes.get(OWNER).toString();\n }\n\n /**\n * Set the menu's owner string.\n *\n * @param owner Name of the menu's owner\n */\n public void setOwner(String owner) {\n attributes.set(OWNER, owner);\n }\n\n /**\n * Get the menu's permission group.\n *\n * @return the group\n */\n public String getGroup() {\n return attributes.get(GROUP).toString();\n }\n\n /**\n * Set the menu's permission group.\n *\n * @param group Name of the menu's group\n */\n public void setGroup(String group) {\n attributes.set(GROUP, group);\n }\n\n public UUID getOwnerId() {\n return ownerId;\n }\n\n public void setOwnerId(UUID ownerId) {\n this.ownerId = ownerId;\n }\n\n /**\n * Get the menu's autosave status - will menus be automatically saved to disk when modified?\n *\n * @return true or false\n */\n public boolean isAutosave() {\n return autosave;\n }\n\n /**\n * Set the menu's autosave status - will menus be automatically saved to disk when modified?\n *\n * @param autosave true or false\n * @return the previous autosave status - true or false\n */\n public boolean setAutosave(boolean autosave) {\n boolean prevAutosave = this.autosave;\n this.autosave = autosave;\n if (autosave) {\n autosave();\n }\n return prevAutosave;\n }\n\n /**\n * Get the menu's autosort status - will menu items be automatically sorted when added?\n *\n * @return true or false\n */\n public boolean isAutosort() {\n return (Boolean) attributes.get(AUTOSORT);\n }\n\n /**\n * Set the menu's autosort status - will menu items be automatically sorted when added?\n *\n * @param autosort true or false\n */\n public void setAutosort(boolean autosort) {\n setAttribute(AUTOSORT, Boolean.toString(autosort));\n }\n\n /**\n * Get the menu's default command. This command will be used if the menu item\n * being executed has a missing command.\n *\n * @return The default command string\n */\n public String getDefaultCommand() {\n return attributes.get(DEFAULT_CMD).toString();\n }\n\n /**\n * Set the menu's default command. This command will be used if the menu item\n * being executed has a missing command.\n *\n * @param defaultCommand the default command to set\n */\n public void setDefaultCommand(String defaultCommand) {\n setAttribute(DEFAULT_CMD, defaultCommand);\n }\n\n /**\n * Get a list of all the items in the menu\n *\n * @return A list of the items\n */\n public List<SMSMenuItem> getItems() {\n return items;\n }\n\n /**\n * Get the number of items in the menu\n *\n * @return The number of items\n */\n public int getItemCount() {\n return items.size();\n }\n\n /**\n * Get the item at the given numeric index\n *\n * @param index 1-based numeric index\n * @return The menu item at that index or null if out of range and mustExist is false\n * @throws SMSException if the index is out of range and mustExist is true\n */\n public SMSMenuItem getItemAt(int index, boolean mustExist) {\n if (index < 1 || index > items.size()) {\n if (mustExist) {\n throw new SMSException(\"Index \" + index + \" out of range.\");\n } else {\n return null;\n }\n } else {\n return items.get(index - 1);\n }\n }\n\n /**\n * Get the item at the given numeric index.\n *\n * @param index 1-based numeric index\n * @return the menu item at that index or null if out of range\n */\n public SMSMenuItem getItemAt(int index) {\n return getItemAt(index, false);\n }\n\n /**\n * Get the menu item matching the given label.\n *\n * @param wanted the label to match (case-insensitive)\n * @return the menu item with that label, or null if no matching item\n */\n public SMSMenuItem getItem(String wanted) {\n return getItem(wanted, false);\n }\n\n /**\n * Get the menu item matching the given label\n *\n * @param wanted The label to match (case-insensitive)\n * @param mustExist If true and the label is not in the menu, throw an exception\n * @return The menu item with that label, or null if no matching item and mustExist is false\n * @throws SMSException if no matching item and mustExist is true\n */\n public SMSMenuItem getItem(String wanted, boolean mustExist) {\n if (items.size() != itemMap.size())\n rebuildItemMap(); // workaround for Heroes 1.4.8 which calls menu.getItems().clear\n\n Integer idx = itemMap.get(ChatColor.stripColor(wanted.replace(FAKE_SPACE, \" \")));\n if (idx == null) {\n if (mustExist) {\n throw new SMSException(\"No such item '\" + wanted + \"' in menu \" + getName());\n } else {\n return null;\n }\n }\n return getItemAt(idx);\n }\n\n /**\n * Get the index of the item matching the given label\n *\n * @param wanted The label to match (case-insensitive)\n * @return 1-based item index, or -1 if no matching item\n */\n public int indexOfItem(String wanted) {\n if (items.size() != itemMap.size())\n rebuildItemMap(); // workaround for Heroes 1.4.8 which calls menu.getItems().clear\n\n int index = -1;\n try {\n index = Integer.parseInt(wanted);\n } catch (NumberFormatException e) {\n String l = ChatColor.stripColor(wanted.replace(FAKE_SPACE, \" \"));\n if (itemMap.containsKey(l))\n index = itemMap.get(l);\n }\n return index;\n }\n\n /**\n * Append a new item to the menu\n *\n * @param label Label of the item to add\n * @param command Command to be run when the item is selected\n * @param message Feedback text to be shown when the item is selected\n * @deprecated use {@link #addItem(SMSMenuItem)}\n */\n @Deprecated\n public void addItem(String label, String command, String message) {\n addItem(new SMSMenuItem(this, label, command, message));\n }\n\n /**\n * Append a new item to the menu\n *\n * @param item The item to be added\n */\n public void addItem(SMSMenuItem item) {\n insertItem(items.size() + 1, item);\n }\n\n /**\n * Insert new item in the menu, at the given position.\n *\n * @param pos the position to insert at\n * @param label label of the new item\n * @param command command to be run\n * @param message feedback message text\n * @deprecated use {@link #insertItem(int, SMSMenuItem)}\n */\n @Deprecated\n public void insertItem(int pos, String label, String command, String message) {\n insertItem(pos, new SMSMenuItem(this, label, command, message));\n }\n\n /**\n * Insert a new item in the menu, at the given position.\n *\n * @param item The item to insert\n * @param pos The position to insert (1-based index)\n */\n public void insertItem(int pos, SMSMenuItem item) {\n if (items.size() != itemMap.size())\n rebuildItemMap(); // workaround for Heroes 1.4.8 which calls menu.getItems().clear\n\n if (item == null)\n throw new NullPointerException();\n String l = item.getLabelStripped();\n if (itemMap.containsKey(l)) {\n throw new SMSException(\"Duplicate label '\" + l + \"' not allowed in menu '\" + getName() + \"'.\");\n }\n\n if (pos > items.size()) {\n items.add(item);\n itemMap.put(l, items.size());\n } else {\n items.add(pos - 1, item);\n rebuildItemMap();\n }\n\n if (isAutosort()) {\n Collections.sort(items);\n if (pos <= items.size()) rebuildItemMap();\n }\n\n setChanged();\n autosave();\n }\n\n /**\n * Replace an existing menu item. The label must already be present in the menu,\n * or an exception will be thrown.\n *\n * @param label Label of the menu item\n * @param command The command to be run\n * @param message The feedback message\n * @throws SMSException if the label isn't present in the menu\n * @deprecated use {@link #replaceItem(SMSMenuItem)}\n */\n @Deprecated\n public void replaceItem(String label, String command, String message) {\n replaceItem(new SMSMenuItem(this, label, command, message));\n }\n\n /**\n * Replace an existing menu item. The new item's label must already be present in\n * the menu.\n *\n * @param item the replacement menu item\n * @throws SMSException if the new item's label isn't present in the menu\n */\n public void replaceItem(SMSMenuItem item) {\n if (items.size() != itemMap.size())\n rebuildItemMap(); // workaround for Heroes 1.4.8 which calls menu.getItems().clear\n\n String l = item.getLabelStripped();\n if (!itemMap.containsKey(l)) {\n throw new SMSException(\"Label '\" + l + \"' is not in the menu.\");\n }\n int idx = itemMap.get(l);\n items.set(idx - 1, item);\n itemMap.put(l, idx);\n\n setChanged();\n autosave();\n }\n\n /**\n * Replace the menu item at the given 1-based position. The new label must not already be\n * present in the menu or an exception will be thrown - duplicates are not allowed.\n *\n * @param pos the position to replace at\n * @param label label of the replacement item\n * @param command command for the replacement item\n * @param message feedback message text for the replacement item\n * @deprecated use {@link #replaceItem(int, SMSMenuItem)}\n */\n @Deprecated\n public void replaceItem(int pos, String label, String command, String message) {\n replaceItem(pos, new SMSMenuItem(this, label, command, message));\n }\n\n /**\n * Replace the menu item at the given 1-based position. The new label must not already be\n * present in the menu or an exception will be thrown - duplicates are not allowed.\n *\n * @param pos the position to replace at\n * @param item the new menu item\n * @throws SMSException if the new menu item's label already exists in this menu\n */\n public void replaceItem(int pos, SMSMenuItem item) {\n if (items.size() != itemMap.size())\n rebuildItemMap(); // workaround for Heroes 1.4.8 which calls menu.getItems().clear\n\n String l = item.getLabelStripped();\n if (pos < 1 || pos > items.size()) {\n throw new SMSException(\"Index \" + pos + \" out of range.\");\n }\n if (itemMap.containsKey(l) && pos != itemMap.get(l)) {\n throw new SMSException(\"Duplicate label '\" + l + \"' not allowed in menu '\" + getName() + \"'.\");\n }\n itemMap.remove(items.get(pos - 1).getLabelStripped());\n items.set(pos - 1, item);\n itemMap.put(l, pos);\n\n setChanged();\n autosave();\n }\n\n /**\n * Rebuild the label->index mapping for the menu. Needed if the menu order changes\n * (insertion, removal, sorting...)\n */\n private void rebuildItemMap() {\n itemMap.clear();\n for (int i = 0; i < items.size(); i++) {\n itemMap.put(items.get(i).getLabelStripped(), i + 1);\n }\n }\n\n /**\n * Sort the menu's items by label text - see {@link SMSMenuItem#compareTo(SMSMenuItem)}\n */\n public void sortItems() {\n Collections.sort(items);\n rebuildItemMap();\n setChanged();\n autosave();\n }\n\n /**\n * Remove an item from the menu by matching label. If the label string is\n * just an integer value, remove the item at that 1-based numeric index.\n *\n * @param indexStr The label to search for and remove\n * @throws IllegalArgumentException if the label does not exist in the menu\n */\n public void removeItem(String indexStr) {\n if (StringUtils.isNumeric(indexStr)) {\n removeItem(Integer.parseInt(indexStr));\n } else {\n String stripped = ChatColor.stripColor(indexStr);\n SMSValidate.isTrue(itemMap.containsKey(stripped), \"No such label '\" + indexStr + \"' in menu '\" + getName() + \"'.\");\n removeItem(itemMap.get(stripped));\n }\n }\n\n /**\n * Remove an item from the menu by numeric index\n *\n * @param index 1-based index of the item to remove\n */\n public void removeItem(int index) {\n // Java lists are 0-indexed, our signs are 1-indexed\n items.remove(index - 1);\n rebuildItemMap();\n setChanged();\n autosave();\n }\n\n /**\n * Remove all items from a menu\n */\n public void removeAllItems() {\n items.clear();\n itemMap.clear();\n setChanged();\n autosave();\n }\n\n /**\n * Permanently delete a menu, dereferencing the object and removing saved data from disk.\n */\n void deletePermanent() {\n try {\n setChanged();\n notifyObservers(new MenuDeleteAction(null, true));\n ScrollingMenuSign.getInstance().getMenuManager().unregisterMenu(getName());\n SMSPersistence.unPersist(this);\n } catch (SMSException e) {\n // Should not get here\n LogUtils.warning(\"Impossible: deletePermanent got SMSException?\" + e.getMessage());\n }\n }\n\n /**\n * Temporarily delete a menu. The menu object is dereferenced but saved menu data is not\n * deleted from disk.\n */\n void deleteTemporary() {\n try {\n setChanged();\n notifyObservers(new MenuDeleteAction(null, false));\n ScrollingMenuSign.getInstance().getMenuManager().unregisterMenu(getName());\n } catch (SMSException e) {\n // Should not get here\n LogUtils.warning(\"Impossible: deleteTemporary got SMSException? \" + e.getMessage());\n }\n }\n\n public void autosave() {\n // we only save menus which have been registered via SMSMenu.addMenu()\n if (isAutosave() && ScrollingMenuSign.getInstance().getMenuManager().checkForMenu(getName())) {\n SMSPersistence.save(this);\n }\n }\n\n /**\n * Check if the given player has access right for this menu.\n *\n * @param player The player to check\n * @return True if the player may use this view, false if not\n */\n public boolean hasOwnerPermission(Player player) {\n SMSAccessRights access = (SMSAccessRights) getAttributes().get(ACCESS);\n return access.isAllowedToUse(player, ownerId, getOwner(), getGroup());\n }\n\n /**\n * Get the usage limit details for this menu.\n *\n * @return The usage limit details\n */\n public SMSRemainingUses getUseLimits() {\n return uses;\n }\n\n @Override\n public String getLimitableName() {\n return getName();\n }\n\n /**\n * Returns a printable representation of the number of uses remaining for this item.\n *\n * @return Formatted usage information\n */\n String formatUses() {\n return uses.toString();\n }\n\n /**\n * Returns a printable representation of the number of uses remaining for this item, for the given player.\n *\n * @param sender Command sender to retrieve the usage information for\n * @return Formatted usage information\n */\n @Override\n public String formatUses(CommandSender sender) {\n if (sender instanceof Player) {\n return uses.toString((Player) sender);\n } else {\n return formatUses();\n }\n }\n\n @Override\n public File getSaveFolder() {\n return DirectoryStructure.getMenusFolder();\n }\n\n @Override\n public String getDescription() {\n return \"menu\";\n }\n\n @Override\n public Object onConfigurationValidate(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.equals(ACCESS)) {\n SMSAccessRights access = (SMSAccessRights) newVal;\n if (access != SMSAccessRights.ANY && ownerId == null && !inThaw) {\n throw new SMSException(\"View must be owned by a player to change access control to \" + access);\n } else if (access == SMSAccessRights.GROUP && ScrollingMenuSign.permission == null) {\n throw new SMSException(\"Cannot use GROUP access control (no permission group support available)\");\n }\n } else if (key.equals(TITLE)) {\n return SMSUtil.unEscape(newVal.toString());\n } else if (key.equals(OWNER) && newVal.toString().equals(\"&console\")) {\n // migration of owner field from pre-2.0.0: \"&console\" => \"[console]\"\n return ScrollingMenuSign.CONSOLE_OWNER;\n }\n\n return newVal;\n }\n\n @Override\n public void onConfigurationChanged(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.equals(AUTOSORT) && (Boolean) newVal) {\n sortItems();\n } else if (key.equals(TITLE)) {\n title = newVal.toString();\n setChanged();\n notifyObservers(new TitleAction(null, oldVal.toString(), newVal.toString()));\n } else if (key.equals(OWNER) && !inThaw) {\n final String owner = newVal.toString();\n if (owner.isEmpty() || owner.equals(ScrollingMenuSign.CONSOLE_OWNER)) {\n ownerId = ScrollingMenuSign.CONSOLE_UUID;\n } else if (MiscUtil.looksLikeUUID(owner)) {\n ownerId = UUID.fromString(owner);\n String name = Bukkit.getOfflinePlayer(ownerId).getName();\n setAttribute(OWNER, name == null ? \"?\" : name);\n } else if (!owner.equals(\"?\")) {\n @SuppressWarnings(\"deprecation\") Player p = Bukkit.getPlayer(owner);\n if (p != null) {\n ownerId = p.getUniqueId();\n } else {\n updateOwnerAsync(owner);\n }\n }\n }\n\n autosave();\n }\n\n private void updateOwnerAsync(final String owner) {\n final UUIDFetcher uf = new UUIDFetcher(Arrays.asList(owner));\n Bukkit.getScheduler().runTaskAsynchronously(ScrollingMenuSign.getInstance(), new Runnable() {\n @Override\n public void run() {\n try {\n Map<String,UUID> res = uf.call();\n if (res.containsKey(owner)) {\n ownerId = res.get(owner);\n } else {\n LogUtils.warning(\"Menu [\" + getName() + \"]: no known UUID for player: \" + owner);\n ownerId = ScrollingMenuSign.CONSOLE_UUID;\n }\n } catch (Exception e) {\n LogUtils.warning(\"Menu [\" + getName() + \"]: can't retrieve UUID for player: \" + owner + \": \" + e.getMessage());\n }\n }\n });\n }\n\n /**\n * Check if this menu is owned by the given player.\n *\n * @param player the player to check\n * @return true if the menu is owned by the given player, false otherwise\n */\n public boolean isOwnedBy(Player player) {\n return player.getUniqueId().equals(ownerId);\n }\n\n /**\n * Require that the given command sender is allowed to modify this menu, and throw a SMSException if not.\n *\n * @param sender The command sender to check\n */\n public void ensureAllowedToModify(CommandSender sender) {\n if (sender instanceof Player) {\n Player player = (Player) sender;\n if (!isOwnedBy(player) && !PermissionUtils.isAllowedTo(player, \"scrollingmenusign.edit.any\")) {\n throw new SMSException(\"You don't have permission to modify that menu.\");\n }\n }\n }\n\n @Override\n public int compareTo(SMSMenu o) {\n return getName().compareTo(o.getName());\n }\n\n public void forceUpdate(ViewUpdateAction action) {\n setChanged();\n notifyObservers(action);\n }\n}", "public class ScrollingMenuSign extends JavaPlugin implements ConfigurationListener {\n\n public static final int BLOCK_TARGET_DIST = 4;\n public static final String CONSOLE_OWNER = \"[console]\";\n public static final UUID CONSOLE_UUID = new UUID(0, 0);\n\n private static ScrollingMenuSign instance = null;\n\n public static Economy economy = null;\n public static Permission permission = null;\n\n private final CommandManager cmds = new CommandManager(this);\n private final CommandletManager cmdlets = new CommandletManager(this);\n private final ViewManager viewManager = new ViewManager(this);\n private final LocationManager locationManager = new LocationManager();\n private final VariablesManager variablesManager = new VariablesManager(this);\n private final MenuManager menuManager = new MenuManager(this);\n private final SMSHandlerImpl handler = new SMSHandlerImpl(this);\n private final ConfigCache configCache = new ConfigCache();\n\n private boolean spoutEnabled = false;\n\n private ConfigurationManager configManager;\n\n public final ResponseHandler responseHandler = new ResponseHandler(this);\n private boolean protocolLibEnabled = false;\n private MetaFaker faker;\n private boolean vaultLegacyMode = false;\n private boolean holoAPIEnabled;\n\n @Override\n public void onLoad() {\n ConfigurationSerialization.registerClass(PersistableLocation.class);\n }\n\n @Override\n public void onEnable() {\n setInstance(this);\n\n LogUtils.init(this);\n\n DirectoryStructure.setupDirectoryStructure();\n\n configManager = new ConfigurationManager(this, this);\n configManager.setPrefix(\"sms\");\n\n configCleanup();\n\n configCache.processConfig(getConfig());\n\n MiscUtil.init(this);\n MiscUtil.setColouredConsole(getConfig().getBoolean(\"sms.coloured_console\"));\n\n Debugger.getInstance().setPrefix(\"[SMS] \");\n Debugger.getInstance().setLevel(getConfig().getInt(\"sms.debug_level\"));\n Debugger.getInstance().setTarget(getServer().getConsoleSender());\n\n PluginManager pm = getServer().getPluginManager();\n setupSpout(pm);\n setupVault(pm);\n setupProtocolLib(pm);\n setupHoloAPI(pm);\n if (protocolLibEnabled) {\n ItemGlow.init(this);\n setupItemMetaFaker();\n }\n\n setupCustomFonts();\n\n new SMSPlayerListener(this);\n new SMSBlockListener(this);\n new SMSEntityListener(this);\n new SMSWorldListener(this);\n if (spoutEnabled) {\n new SMSSpoutKeyListener(this);\n }\n\n registerCommands();\n registerCommandlets();\n\n MessagePager.setPageCmd(\"/sms page [#|n|p]\");\n MessagePager.setDefaultPageSize(getConfig().getInt(\"sms.pager.lines\", 0));\n\n SMSScrollableView.setDefaultScrollType(SMSScrollableView.ScrollType.valueOf(getConfig().getString(\"sms.scroll_type\").toUpperCase()));\n\n loadPersistedData();\n variablesManager.checkForUUIDMigration();\n\n if (spoutEnabled) {\n SpoutUtils.precacheTextures();\n }\n\n setupMetrics();\n\n Debugger.getInstance().debug(getDescription().getName() + \" version \" + getDescription().getVersion() + \" is enabled!\");\n\n UUIDMigration.migrateToUUID(this);\n }\n\n @Override\n public void onDisable() {\n SMSPersistence.saveMenusAndViews();\n SMSPersistence.saveMacros();\n SMSPersistence.saveVariables();\n for (SMSMenu menu : getMenuManager().listMenus()) {\n // this also deletes all the menu's views...\n menu.deleteTemporary();\n }\n for (SMSMacro macro : SMSMacro.listMacros()) {\n macro.deleteTemporary();\n }\n\n if (faker != null) {\n faker.shutdown();\n }\n\n economy = null;\n permission = null;\n setInstance(null);\n\n Debugger.getInstance().debug(getDescription().getName() + \" version \" + getDescription().getVersion() + \" is disabled!\");\n }\n\n @Override\n public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {\n return cmds.dispatch(sender, command, label, args);\n }\n\n @Override\n public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {\n return cmds.onTabComplete(sender, command, label, args);\n }\n\n public SMSHandler getHandler() {\n return handler;\n }\n\n public boolean isSpoutEnabled() {\n return spoutEnabled;\n }\n\n public boolean isProtocolLibEnabled() {\n return protocolLibEnabled;\n }\n\n public boolean isHoloAPIEnabled() {\n return holoAPIEnabled;\n }\n\n public static ScrollingMenuSign getInstance() {\n return instance;\n }\n\n public CommandletManager getCommandletManager() {\n return cmdlets;\n }\n\n public ConfigurationManager getConfigManager() {\n return configManager;\n }\n\n /**\n * @return the viewManager\n */\n public ViewManager getViewManager() {\n return viewManager;\n }\n\n /**\n * @return the locationManager\n */\n public LocationManager getLocationManager() {\n return locationManager;\n }\n\n private void setupMetrics() {\n if (!getConfig().getBoolean(\"sms.mcstats\")) {\n return;\n }\n\n try {\n Metrics metrics = new Metrics(this);\n\n Graph graphM = metrics.createGraph(\"Menu/View/Macro count\");\n graphM.addPlotter(new Plotter(\"Menus\") {\n @Override\n public int getValue() {\n return getMenuManager().listMenus().size();\n }\n });\n graphM.addPlotter(new Plotter(\"Views\") {\n @Override\n public int getValue() {\n return viewManager.listViews().size();\n }\n });\n graphM.addPlotter(new Plotter(\"Macros\") {\n @Override\n public int getValue() {\n return SMSMacro.listMacros().size();\n }\n });\n\n Graph graphV = metrics.createGraph(\"View Types\");\n for (final Entry<String, Integer> e : viewManager.getViewCounts().entrySet()) {\n graphV.addPlotter(new Plotter(e.getKey()) {\n @Override\n public int getValue() {\n return e.getValue();\n }\n });\n }\n metrics.start();\n } catch (IOException e) {\n LogUtils.warning(\"Can't submit metrics data: \" + e.getMessage());\n }\n }\n\n private static void setInstance(ScrollingMenuSign plugin) {\n instance = plugin;\n }\n\n private void setupHoloAPI(PluginManager pm) {\n Plugin holoAPI = pm.getPlugin(\"HoloAPI\");\n if (holoAPI != null && holoAPI.isEnabled()) {\n holoAPIEnabled = true;\n Debugger.getInstance().debug(\"Hooked HoloAPI v\" + holoAPI.getDescription().getVersion());\n }\n }\n\n private void setupSpout(PluginManager pm) {\n Plugin spout = pm.getPlugin(\"Spout\");\n if (spout != null && spout.isEnabled()) {\n spoutEnabled = true;\n Debugger.getInstance().debug(\"Hooked Spout v\" + spout.getDescription().getVersion());\n }\n }\n\n private void setupVault(PluginManager pm) {\n Plugin vault = pm.getPlugin(\"Vault\");\n if (vault != null && vault.isEnabled()) {\n int ver = PluginVersionChecker.getRelease(vault.getDescription().getVersion());\n Debugger.getInstance().debug(\"Hooked Vault v\" + vault.getDescription().getVersion());\n vaultLegacyMode = ver < 1003000; // Vault 1.3.0\n if (vaultLegacyMode) {\n LogUtils.warning(\"Detected an older version of Vault. Proper UUID functionality requires Vault 1.4.1 or later.\");\n }\n setupEconomy();\n setupPermission();\n } else {\n LogUtils.warning(\"Vault not loaded: no economy command costs & no permission group support\");\n }\n }\n\n private void setupEconomy() {\n RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(Economy.class);\n economy = economyProvider.getProvider();\n if (economyProvider == null) {\n LogUtils.warning(\"No economy plugin detected - economy command costs not available\");\n }\n }\n\n private void setupPermission() {\n RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(Permission.class);\n permission = permissionProvider.getProvider();\n if (permission == null) {\n LogUtils.warning(\"No permissions plugin detected - no permission group support\");\n }\n }\n\n public boolean isVaultLegacyMode() {\n return vaultLegacyMode;\n }\n\n private void setupProtocolLib(PluginManager pm) {\n Plugin pLib = pm.getPlugin(\"ProtocolLib\");\n if (pLib != null && pLib instanceof ProtocolLibrary && pLib.isEnabled()) {\n protocolLibEnabled = true;\n Debugger.getInstance().debug(\"Hooked ProtocolLib v\" + pLib.getDescription().getVersion());\n }\n }\n\n private void setupItemMetaFaker() {\n faker = new MetaFaker(this, new MetadataFilter() {\n @Override\n public ItemMeta filter(ItemMeta itemMeta, Player player) {\n if (player.getGameMode() == GameMode.CREATIVE) {\n // messing with item meta in creative mode can have unwanted consequences\n return null;\n }\n if (!ActiveItem.isActiveItem(itemMeta)) {\n String[] f = PopupItem.getPopupItemFields(itemMeta);\n if (f == null) {\n return null;\n }\n }\n // strip the last line from the lore for active items & popup items\n List<String> newLore = new ArrayList<String>(itemMeta.getLore());\n newLore.remove(newLore.size() - 1);\n ItemMeta newMeta = itemMeta.clone();\n newMeta.setLore(newLore);\n return newMeta;\n }\n });\n }\n\n private void registerCommands() {\n cmds.registerCommand(new AddItemCommand());\n cmds.registerCommand(new AddMacroCommand());\n cmds.registerCommand(new AddViewCommand());\n cmds.registerCommand(new CreateMenuCommand());\n cmds.registerCommand(new DeleteMenuCommand());\n cmds.registerCommand(new EditMenuCommand());\n cmds.registerCommand(new FontCommand());\n cmds.registerCommand(new GetConfigCommand());\n cmds.registerCommand(new GiveCommand());\n cmds.registerCommand(new ItemUseCommand());\n cmds.registerCommand(new ListMacroCommand());\n cmds.registerCommand(new ListMenusCommand());\n cmds.registerCommand(new MenuCommand());\n cmds.registerCommand(new PageCommand());\n cmds.registerCommand(new ReloadCommand());\n cmds.registerCommand(new RemoveItemCommand());\n cmds.registerCommand(new RemoveMacroCommand());\n cmds.registerCommand(new RemoveViewCommand());\n cmds.registerCommand(new RepaintCommand());\n cmds.registerCommand(new SaveCommand());\n cmds.registerCommand(new SetConfigCommand());\n cmds.registerCommand(new UndeleteMenuCommand());\n cmds.registerCommand(new VarCommand());\n cmds.registerCommand(new ViewCommand());\n }\n\n private void registerCommandlets() {\n cmdlets.registerCommandlet(new AfterCommandlet());\n cmdlets.registerCommandlet(new CooldownCommandlet());\n cmdlets.registerCommandlet(new PopupCommandlet());\n cmdlets.registerCommandlet(new SubmenuCommandlet());\n cmdlets.registerCommandlet(new CloseSubmenuCommandlet());\n cmdlets.registerCommandlet(new ScriptCommandlet());\n cmdlets.registerCommandlet(new QuickMessageCommandlet());\n }\n\n private void loadPersistedData() {\n SMSPersistence.loadMacros();\n SMSPersistence.loadVariables();\n SMSPersistence.loadMenus();\n SMSPersistence.loadViews();\n }\n\n public static URL makeImageURL(String path) throws MalformedURLException {\n if (path == null || path.isEmpty()) {\n throw new MalformedURLException(\"file must be non-null and not an empty string\");\n }\n\n return makeImageURL(ScrollingMenuSign.getInstance().getConfig().getString(\"sms.resource_base_url\"), path);\n }\n\n public static URL makeImageURL(String base, String path) throws MalformedURLException {\n if (path == null || path.isEmpty()) {\n throw new MalformedURLException(\"file must be non-null and not an empty string\");\n }\n if ((base == null || base.isEmpty()) && !path.startsWith(\"http:\")) {\n throw new MalformedURLException(\"base URL must be set (use /sms setcfg resource_base_url ...\");\n }\n if (path.startsWith(\"http:\") || base == null) {\n return new URL(path);\n } else {\n return new URL(new URL(base), path);\n }\n }\n\n @Override\n public Object onConfigurationValidate(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.equals(\"scroll_type\")) {\n try {\n SMSScrollableView.ScrollType t = SMSGlobalScrollableView.ScrollType.valueOf(newVal.toString().toUpperCase());\n DHValidate.isTrue(t != SMSGlobalScrollableView.ScrollType.DEFAULT, \"Scroll type must be one of SCROLL/PAGE\");\n } catch (IllegalArgumentException e) {\n throw new DHUtilsException(\"Scroll type must be one of SCROLL/PAGE\");\n }\n } else if (key.equals(\"debug_level\")) {\n DHValidate.isTrue((Integer) newVal >= 0, \"Debug level must be >= 0\");\n } else if (key.equals(\"submenus.back_item.material\") || key.equals(\"inv_view.default_icon\")) {\n try {\n SMSUtil.parseMaterialSpec(newVal.toString());\n } catch (IllegalArgumentException e) {\n throw new DHUtilsException(\"Invalid material specification: \" + newVal.toString());\n }\n }\n return newVal;\n }\n\n @Override\n public void onConfigurationChanged(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.startsWith(\"actions.spout\") && isSpoutEnabled()) {\n // reload & re-cache spout key definitions\n SpoutUtils.loadKeyDefinitions();\n } else if (key.startsWith(\"spout.\") && isSpoutEnabled()) {\n // settings which affects how spout views are drawn\n repaintViews(\"spout\");\n } else if (key.equalsIgnoreCase(\"command_log_file\")) {\n CommandParser.setLogFile(newVal.toString());\n } else if (key.equalsIgnoreCase(\"debug_level\")) {\n Debugger.getInstance().setLevel((Integer) newVal);\n } else if (key.startsWith(\"item_prefix.\") || key.endsWith(\"_justify\") || key.equals(\"max_title_lines\") || key.startsWith(\"submenus.\")) {\n // settings which affect how all views are drawn\n if (key.equals(\"item_prefix.selected\")) {\n configCache.setPrefixSelected(newVal.toString());\n } else if (key.equals(\"item_prefix.not_selected\")) {\n configCache.setPrefixNotSelected(newVal.toString());\n } else if (key.equals(\"submenus.back_item.label\")) {\n configCache.setSubmenuBackLabel(newVal.toString());\n } else if (key.equals(\"submenus.back_item.material\")) {\n configCache.setSubmenuBackIcon(newVal.toString());\n } else if (key.equals(\"submenus.title_prefix\")) {\n configCache.setSubmenuTitlePrefix(newVal.toString());\n }\n repaintViews(null);\n } else if (key.equals(\"coloured_console\")) {\n MiscUtil.setColouredConsole((Boolean) newVal);\n } else if (key.equals(\"scroll_type\")) {\n SMSScrollableView.setDefaultScrollType(SMSGlobalScrollableView.ScrollType.valueOf(newVal.toString().toUpperCase()));\n repaintViews(null);\n } else if (key.equals(\"no_physics\")) {\n configCache.setPhysicsProtected((Boolean) newVal);\n } else if (key.equals(\"no_break_signs\")) {\n configCache.setBreakProtected((Boolean) newVal);\n } else if (key.equals(\"inv_view.default_icon\")) {\n configCache.setDefaultInventoryViewIcon(newVal.toString());\n } else if (key.equals(\"user_variables.fallback_sub\")) {\n configCache.setFallbackUserVarSub(newVal.toString());\n }\n }\n\n public ConfigCache getConfigCache() {\n return configCache;\n }\n\n private void repaintViews(String type) {\n for (SMSView v : viewManager.listViews()) {\n if (type == null || v.getType().equals(type)) {\n v.update(null, new RepaintAction());\n }\n }\n }\n\n public void setupCustomFonts() {\n GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\n\n //noinspection ConstantConditions\n for (File f : DirectoryStructure.getFontsFolder().listFiles()) {\n String n = f.getName().toLowerCase();\n int type;\n if (n.endsWith(\".ttf\")) {\n type = Font.TRUETYPE_FONT;\n } else if (n.endsWith(\".pfa\") || n.endsWith(\".pfb\") || n.endsWith(\".pfm\") || n.endsWith(\".afm\")) {\n type = Font.TYPE1_FONT;\n } else {\n continue;\n }\n try {\n ge.registerFont(Font.createFont(type, f));\n Debugger.getInstance().debug(\"registered font: \" + f.getName());\n } catch (Exception e) {\n LogUtils.warning(\"can't load custom font \" + f + \": \" + e.getMessage());\n }\n }\n }\n\n private void configCleanup() {\n String[] obsolete = new String[]{\n \"sms.maps.break_block_id\", \"sms.autosave\", \"sms.menuitem_separator\",\n \"sms.persistent_user_vars\", \"uservar\",\n };\n\n boolean changed = false;\n Configuration config = getConfig();\n for (String k : obsolete) {\n if (config.contains(k)) {\n config.set(k, null);\n LogUtils.info(\"removed obsolete config item: \" + k);\n changed = true;\n }\n }\n if (changed) {\n saveConfig();\n }\n }\n\n public VariablesManager getVariablesManager() {\n return variablesManager;\n }\n\n public MenuManager getMenuManager() {\n return menuManager;\n }\n}", "public class HexColor {\n private final Color color;\n\n public HexColor(String s) {\n color = new Color(s);\n }\n\n public Color getColor() {\n return color;\n }\n\n @Override\n public String toString() {\n return String.format(\"%02x%02x%02x\", color.getRedI(), color.getGreenI(), color.getBlueI());\n }\n}", "public class SMSSpoutKeyMap implements ConfigurationSerializable {\n private final Set<Keyboard> keys;\n\n public SMSSpoutKeyMap(String definition) {\n keys = new HashSet<Keyboard>();\n\n if (definition == null || definition.isEmpty()) {\n return;\n }\n String[] wanted = definition.split(\"\\\\+\");\n for (String w : wanted) {\n w = w.toUpperCase();\n if (!w.startsWith(\"KEY_\"))\n w = \"KEY_\" + w;\n keys.add(Keyboard.valueOf(w));\n }\n }\n\n public SMSSpoutKeyMap() {\n this(null);\n }\n\n public void add(Keyboard key) {\n keys.add(key);\n }\n\n public void remove(Keyboard key) {\n keys.remove(key);\n }\n\n public void clear() {\n keys.clear();\n }\n\n public int keysPressed() {\n return keys.size();\n }\n\n @Override\n public String toString() {\n return Joiner.on(\"+\").join(keys);\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((keys == null) ? 0 : keys.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 SMSSpoutKeyMap other = (SMSSpoutKeyMap) obj;\n if (keys == null) {\n if (other.keys != null)\n return false;\n } else if (!keys.equals(other.keys))\n return false;\n return true;\n }\n\n @Override\n public Map<String, Object> serialize() {\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"keymap\", this.toString());\n return map;\n }\n\n public static SMSSpoutKeyMap deserialize(Map<String, Object> map) {\n return new SMSSpoutKeyMap((String) map.get(\"keymap\"));\n }\n}", "public class SpoutViewPopup extends SMSGenericPopup implements SMSPopup {\n private static final int LIST_WIDTH_HEIGHT = 200;\n private static final int TITLE_HEIGHT = 15;\n private static final int TITLE_WIDTH = 100;\n\n private final Label title;\n private final SMSSpoutView view;\n private final SMSListWidget listWidget;\n private final SMSListTexture texture;\n private final SpoutPlayer sp;\n\n private boolean poppedUp;\n\n public SpoutViewPopup(SpoutPlayer sp, SMSSpoutView view) {\n this.sp = sp;\n this.view = view;\n this.poppedUp = false;\n\n Screen mainScreen = sp.getMainScreen();\n\n title = new GenericLabel(view.doVariableSubstitutions(sp, view.getActiveMenu(sp).getTitle()));\n title.setX((mainScreen.getWidth() - TITLE_WIDTH) / 2).setY(15).setWidth(TITLE_WIDTH).setHeight(TITLE_HEIGHT);\n title.setAnchor(WidgetAnchor.TOP_LEFT);\n title.setAuto(false);\n rejustify();\n\n int listX = (mainScreen.getWidth() - LIST_WIDTH_HEIGHT) / 2;\n int listY = 5 + 2 + TITLE_HEIGHT;\n\n texture = new SMSListTexture(this);\n\n listWidget = new SMSListWidget(sp, view);\n listWidget.setX(listX).setY(listY).setWidth(LIST_WIDTH_HEIGHT).setHeight(LIST_WIDTH_HEIGHT);\n\n this.attachWidget(ScrollingMenuSign.getInstance(), title);\n texture.setX(listX).setY(listY).setWidth(LIST_WIDTH_HEIGHT).setHeight(LIST_WIDTH_HEIGHT);\n this.attachWidget(ScrollingMenuSign.getInstance(), texture);\n this.attachWidget(ScrollingMenuSign.getInstance(), listWidget);\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#getView()\n */\n @Override\n public SMSSpoutView getView() {\n return view;\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#isPoppedUp()\n */\n @Override\n public boolean isPoppedUp() {\n return poppedUp;\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#repaint()\n */\n @Override\n public void repaint() {\n title.setText(view.doVariableSubstitutions(sp, view.getActiveMenuTitle(sp)));\n rejustify();\n texture.updateURL();\n listWidget.repaint();\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#popup()\n */\n @Override\n public void popup() {\n poppedUp = true;\n sp.getMainScreen().attachPopupScreen(this);\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#popdown()\n */\n @Override\n public void popdown() {\n poppedUp = false;\n sp.getMainScreen().closePopup();\n }\n\n private void rejustify() {\n switch (getView().getTitleJustification()) {\n case LEFT:\n title.setAlign(WidgetAnchor.CENTER_LEFT);\n break;\n case RIGHT:\n title.setAlign(WidgetAnchor.CENTER_LEFT);\n break;\n case CENTER:\n default:\n title.setAlign(WidgetAnchor.CENTER_LEFT);\n break;\n }\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#scrollTo(int)\n */\n public void scrollTo(int scrollPos) {\n listWidget.setSelection(scrollPos - 1);\n\n Debugger.getInstance().debug(\"Spout view \" + getView().getName() + \": scroll to \" + scrollPos + \": \" + listWidget.getSelectedItem().getTitle());\n }\n\n /**\n * This is used when the view is scrolled by a Spout keypress. When that happens a new item\n * becomes selected; we need to distinguish that from an item being selected by a mouse click.\n */\n public void ignoreNextSelection() {\n listWidget.ignoreNextSelection(true);\n }\n}", "public class TextEntryPopup extends SMSGenericPopup {\n private static final Map<UUID, TextEntryPopup> allPopups = new HashMap<UUID, TextEntryPopup>();\n private static final Set<UUID> visiblePopups = new HashSet<UUID>();\n\n private static final String LABEL_COLOUR = ChatColor.YELLOW.toString();\n private static final int BUTTON_HEIGHT = 20;\n\n private final SpoutPlayer sp;\n private final Label label;\n private final TextField textField;\n private final TextEntryButton okButton, cancelButton;\n\n public TextEntryPopup(SpoutPlayer sp, String prompt) {\n this.sp = sp;\n Screen mainScreen = sp.getMainScreen();\n\n int width = mainScreen.getWidth() / 2;\n int x = (mainScreen.getWidth() - width) / 2;\n int y = mainScreen.getHeight() / 2 - 20;\n\n label = new GenericLabel(LABEL_COLOUR + prompt);\n label.setX(x).setY(y).setWidth(width).setHeight(10);\n y += label.getHeight() + 2;\n\n textField = new GenericTextField();\n textField.setX(x).setY(y).setWidth(width).setHeight(20);\n textField.setFocus(true);\n textField.setMaximumCharacters(0);\n y += textField.getHeight() + 5;\n\n okButton = new TextEntryButton(\"OK\");\n okButton.setX(x).setY(y).setHeight(BUTTON_HEIGHT);\n cancelButton = new TextEntryButton(\"Cancel\");\n cancelButton.setX(x + okButton.getWidth() + 5).setY(y).setHeight(BUTTON_HEIGHT);\n\n ScrollingMenuSign plugin = ScrollingMenuSign.getInstance();\n this.attachWidget(plugin, label);\n this.attachWidget(plugin, textField);\n this.attachWidget(plugin, okButton);\n this.attachWidget(plugin, cancelButton);\n }\n\n public void setPasswordField(boolean isPassword) {\n textField.setPasswordField(isPassword);\n }\n\n private void setPrompt(String prompt) {\n label.setText(LABEL_COLOUR + prompt);\n textField.setText(\"\");\n }\n\n public void confirm() {\n ScrollingMenuSign plugin = ScrollingMenuSign.getInstance();\n\n if (plugin.responseHandler.isExpecting(sp, ExpectCommandSubstitution.class)) {\n try {\n ExpectCommandSubstitution cs = plugin.responseHandler.getAction(sp, ExpectCommandSubstitution.class);\n cs.setSub(textField.getText());\n cs.handleAction(sp);\n } catch (DHUtilsException e) {\n MiscUtil.errorMessage(sp, e.getMessage());\n }\n }\n\n close();\n visiblePopups.remove(sp.getUniqueId());\n }\n\n private void cancel() {\n ScrollingMenuSign.getInstance().responseHandler.cancelAction(sp, ExpectCommandSubstitution.class);\n\n close();\n visiblePopups.remove(sp.getUniqueId());\n }\n\n public static void show(SpoutPlayer sp, String prompt) {\n TextEntryPopup popup;\n if (!allPopups.containsKey(sp.getUniqueId())) {\n popup = new TextEntryPopup(sp, prompt);\n allPopups.put(sp.getUniqueId(), popup);\n } else {\n popup = allPopups.get(sp.getUniqueId());\n popup.setPrompt(prompt);\n }\n\n ScrollingMenuSign plugin = ScrollingMenuSign.getInstance();\n if (plugin.responseHandler.isExpecting(sp, ExpectCommandSubstitution.class)) {\n ExpectCommandSubstitution cs = plugin.responseHandler.getAction(sp, ExpectCommandSubstitution.class);\n popup.setPasswordField(cs.isPassword());\n }\n\n sp.getMainScreen().attachPopupScreen(popup);\n visiblePopups.add(sp.getUniqueId());\n }\n\n public static boolean hasActivePopup(UUID playerName) {\n return visiblePopups.contains(playerName);\n }\n\n private class TextEntryButton extends GenericButton {\n TextEntryButton(String text) {\n super(text);\n }\n\n @Override\n public void onButtonClick(ButtonClickEvent event) {\n if (event.getButton() == okButton) {\n confirm();\n } else if (event.getButton() == cancelButton) {\n cancel();\n }\n }\n }\n}", "public abstract class ViewUpdateAction {\n// private final SMSMenuAction action;\n private final CommandSender sender;\n\n public ViewUpdateAction(CommandSender sender) {\n// this.action = action;\n this.sender = sender;\n }\n\n public ViewUpdateAction() {\n// this.action = action;\n this.sender = null;\n }\n//\n// public SMSMenuAction getAction() {\n// return action;\n// }\n\n public CommandSender getSender() {\n return sender;\n }\n\n public static ViewUpdateAction getAction(Object o) {\n if (o instanceof SMSMenuAction) {\n switch ((SMSMenuAction) o) {\n// return new ViewUpdateAction((SMSMenuAction) o, null);\n case SCROLLED: return new ScrollAction(null, ScrollAction.ScrollDirection.UNKNOWN);\n case REPAINT: return new RepaintAction();\n default: return null;\n }\n } else if (o instanceof ViewUpdateAction) {\n return (ViewUpdateAction) o;\n } else {\n throw new IllegalArgumentException(\"Expecting a ViewUpdateAction or SMSMenuAction object\");\n }\n }\n}" ]
import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Observable; import java.util.UUID; import me.desht.dhutils.ConfigurationManager; import me.desht.dhutils.Debugger; import me.desht.dhutils.LogUtils; import me.desht.dhutils.PermissionUtils; import me.desht.scrollingmenusign.SMSException; import me.desht.scrollingmenusign.SMSMenu; import me.desht.scrollingmenusign.ScrollingMenuSign; import me.desht.scrollingmenusign.spout.HexColor; import me.desht.scrollingmenusign.spout.SMSSpoutKeyMap; import me.desht.scrollingmenusign.spout.SpoutViewPopup; import me.desht.scrollingmenusign.spout.TextEntryPopup; import me.desht.scrollingmenusign.views.action.ViewUpdateAction; import org.bukkit.Bukkit; import org.bukkit.configuration.Configuration; import org.bukkit.entity.Player; import org.getspout.spoutapi.SpoutManager; import org.getspout.spoutapi.gui.PopupScreen; import org.getspout.spoutapi.player.SpoutPlayer;
package me.desht.scrollingmenusign.views; /** * This view draws menus on a popped-up Spout view. */ public class SMSSpoutView extends SMSScrollableView implements PoppableView { // attributes public static final String AUTOPOPDOWN = "autopopdown"; public static final String SPOUTKEYS = "spoutkeys"; public static final String BACKGROUND = "background"; public static final String ALPHA = "alpha"; public static final String TEXTURE = "texture"; // list of all popups which have been created for this view, keyed by player ID private final Map<UUID, SpoutViewPopup> popups = new HashMap<UUID, SpoutViewPopup>(); // map a set of keypresses to the view which handles them private static final Map<String, String> keyMap = new HashMap<String, String>(); /** * Construct a new SMSSPoutView object * * @param name The view name * @param menu The menu to attach the object to * @throws SMSException */ public SMSSpoutView(String name, SMSMenu menu) throws SMSException { super(name, menu); setWrap(false); if (!ScrollingMenuSign.getInstance().isSpoutEnabled()) { throw new SMSException("Spout view cannot be created - server does not have Spout enabled"); } Configuration config = ScrollingMenuSign.getInstance().getConfig(); String defColor = config.getString("sms.spout.list_background"); Double defAlpha = config.getDouble("sms.spout.list_alpha"); registerAttribute(SPOUTKEYS, new SMSSpoutKeyMap(), "Key(s) to toggle view visibility"); registerAttribute(AUTOPOPDOWN, true, "Auto-popdown after item click?"); registerAttribute(BACKGROUND, new HexColor(defColor), "Background colour of view"); registerAttribute(ALPHA, defAlpha, "Transparency of view"); registerAttribute(TEXTURE, "", "Image to use as view background"); } public SMSSpoutView(SMSMenu menu) throws SMSException { this(null, menu); } // NOTE: explicit freeze() and thaw() methods not needed. No new object fields which are not attributes. /** * Show the given player's GUI for this view. * * @param player The player object */ @Override public void showGUI(Player player) { SpoutPlayer sp = SpoutManager.getPlayer(player); if (!sp.isSpoutCraftEnabled()) return; Debugger.getInstance().debug("showing Spout GUI for " + getName() + " to " + sp.getDisplayName()); if (!popups.containsKey(sp.getUniqueId())) { // create a new gui for this player popups.put(sp.getUniqueId(), new SpoutViewPopup(sp, this)); } SpoutViewPopup gui = popups.get(sp.getUniqueId()); gui.popup(); } /** * Hide the given player's GUI for this view. * * @param player The player object */ @Override public void hideGUI(Player player) { SpoutPlayer sp = SpoutManager.getPlayer(player); if (!sp.isSpoutCraftEnabled()) return; if (!popups.containsKey(sp.getUniqueId())) { return; } Debugger.getInstance().debug("hiding Spout GUI for " + getName() + " from " + sp.getDisplayName()); popups.get(sp.getUniqueId()).popdown(); // decision: destroy the gui object or not? // popups.remove(sp.getName()); } /** * Check if the given player has an active GUI (for any Spout view, not * necessarily this one). * * @param player the player to check for * @return true if a GUI is currently popped up, false otherwise */ @Override public boolean hasActiveGUI(Player player) { final SpoutPlayer sp = SpoutManager.getPlayer(player); if (!sp.isSpoutCraftEnabled()) return false; PopupScreen popup = sp.getMainScreen().getActivePopup(); return popup != null && popup instanceof SpoutViewPopup; } /** * Get the active GUI for the given player, if any (for any Spout view, not * necessarily this one). * * @param player the player to check for * @return the GUI object if one is currently popped up, null otherwise */ @Override public SMSPopup getActiveGUI(Player player) { final SpoutPlayer sp = SpoutManager.getPlayer(player); if (!sp.isSpoutCraftEnabled()) return null; PopupScreen popup = sp.getMainScreen().getActivePopup(); return popup instanceof SpoutViewPopup ? (SMSPopup) popup : null; } /** * Toggle the given player's visibility of the GUI for this view. If a GUI for a different view * is currently showing, pop that one down, and pop this one up. * * @param player The player object */ @Override public void toggleGUI(Player player) { final SpoutPlayer sp = SpoutManager.getPlayer(player); if (!sp.isSpoutCraftEnabled()) return; if (hasActiveGUI(sp)) { SMSPopup gui = getActiveGUI(sp); SMSSpoutView poppedUpView = (SMSSpoutView) gui.getView(); if (poppedUpView == this) { // the player has an active GUI from this view - just pop it down hideGUI(sp); } else { // the player has an active GUI, but it belongs to a different spout view, so pop down // that one and pop up the GUI for this view poppedUpView.hideGUI(sp); // just popping the GUI up immediately doesn't appear to work - we need to defer it by a few ticks Bukkit.getScheduler().scheduleSyncDelayedTask(ScrollingMenuSign.getInstance(), new Runnable() { @Override public void run() { showGUI(sp); } }, 3L); } } else { // no GUI shown right now - just pop this one up showGUI(sp); } } /* (non-Javadoc) * @see me.desht.scrollingmenusign.views.SMSScrollableView#update(java.util.Observable, java.lang.Object) */ @Override public void update(Observable menu, Object arg1) { super.update(menu, arg1);
ViewUpdateAction vu = ViewUpdateAction.getAction(arg1);
7
panhainan/BookHouse
src/main/java/com/phn/bookhouse/service/impl/OrderServiceImpl.java
[ "public interface AddressDao {\n\n\t/**\n\t * @author pan\n\t * @param addressid\n\t * @return\n\t */\n\tpublic Address selectAddressById(long addressid);\n\n\t/**\n\t * @author pan\n\t * @param addressid\n\t * @return\n\t */\n\tpublic int deleteAddress(long addressid);\n\n\t/**\n\t * @author pan\n\t * @param address\n\t * @return\n\t */\n\tpublic int updateAddress(Address address);\n\n\t/**\n\t * @author pan\n\t * @param address\n\t * @return\n\t */\n\tpublic int insertAddress(Address address);\n\n\t/**\n\t * @author pan\n\t * @param user_id\n\t * @return\n\t */\n\tpublic List<Address> selectAddressByUserId(long user_id);\n\n}", "public interface BookDao {\n\tpublic int insertBook(Book book);\n\tpublic int deleteBookById(long bookid);\n\tpublic Book selectBookById(long bookid);\n\tpublic List<Book> selectBookByName(Book book);\n\tpublic List<Book> selectBookByHouseId(long bookuserid);\n\tpublic int upBookImg(Book book);\n\tpublic int updateBook(Book book);\n\t/**\n\t * @author pan\n\t * @param book_status \n\t * @return\n\t */\n\tpublic List<Book> selectBookListPage(boolean book_status);\n\t/**\n\t * @author pan\n\t * @param bookisbn\n\t * @return\n\t */\n\tpublic Book selectBookByISBN(String bookisbn);\n\t/**\n\t * @author pan\n\t * @param book\n\t * @return\n\t */\n\tpublic int updownBookStatus(Book book);\n\t/**\n\t * @author pan\n\t * @param param\n\t * @return\n\t */\n\tpublic List<Book> selectHouseBookListPage(Map<String, Object> map);\n\t/**\n\t * @author pan\n\t * @param book_id\n\t */\n\tpublic void updateBookSaleSum(Map<String, Object> map);\n\t/**\n\t * @author pan\n\t * @param book\n\t */\n\tpublic void updateBookScore(Book book);\n\t/**\n\t * @author pan\n\t * @param book\n\t * @return\n\t */\n\tpublic List<Book> selectBookByType(Book book);\n\t/**\n\t * @author pan\n\t * @return\n\t */\n\tpublic List<Book> selectBookBySale();\n}", "public interface OrderDao {\n\n\t/**\n\t * @author pan\n\t * @param order\n\t * @return\n\t */\n\tpublic int insertOrder(Order order);\n\n\t/**\n\t * @author pan\n\t * @param param\n\t * @return\n\t */\n\tpublic List<Order> selectUserOrderListPage(Map<String, Object> param);\n\n\t/**\n\t * @author pan\n\t * @param user_id\n\t * @return\n\t */\n\tpublic List<Order> select5UserOrderListPage(long user_id);\n\n\t/**\n\t * @author pan\n\t * @param orderid\n\t * @return\n\t */\n\tpublic Order selectOrderById(long orderid);\n\n\t/**\n\t * @author pan\n\t * @param order\n\t */\n\tpublic void updateOrderStatus(Order order);\n\n\t/**\n\t * @author pan\n\t * @param hosu_id\n\t * @return\n\t */\n\tpublic List<Order> select5HouseOrderListPage(long hosu_id);\n\n\t/**\n\t * @author pan\n\t * @param param\n\t * @return\n\t */\n\tpublic List<Order> selectHouseOrderListPage(Map<String, Object> param);\n\n\n\tpublic List<Order> findOrderByStatusHouseId(Map<String, Object> param);\n\n\t/**\n\t * @author pan\n\t * @param hosu_id\n\t * @return\n\t */\n\tpublic List<Order> findOrderByStatus5HouseId(long hosu_id);\n\n\t/**\n\t * @author pan\n\t * @param order\n\t */\n\tpublic void updateOrderComment(Order order);\n\n\t/**\n\t * @author pan\n\t * @param order\n\t */\n\tpublic void updateOrderWithAddr(Order order);\n\t\n\tpublic List<Order> selectOrderByBookidStatus(Order order);\n\n}", "public class Address {\n\tprivate long addr_id;\n\n\tprivate String addr_user_name;\n\n\tprivate String addr_name;\n\n\tprivate String addr_phone;\n\n\t// private long addr_user_id;\n\tprivate User user;\n\n\tpublic long getAddr_id() {\n\t\treturn addr_id;\n\t}\n\n\tpublic void setAddr_id(long addr_id) {\n\t\tthis.addr_id = addr_id;\n\t}\n\n\tpublic String getAddr_user_name() {\n\t\treturn addr_user_name;\n\t}\n\n\tpublic void setAddr_user_name(String addr_user_name) {\n\t\tthis.addr_user_name = addr_user_name;\n\t}\n\n\tpublic String getAddr_name() {\n\t\treturn addr_name;\n\t}\n\n\tpublic void setAddr_name(String addr_name) {\n\t\tthis.addr_name = addr_name;\n\t}\n\n\tpublic String getAddr_phone() {\n\t\treturn addr_phone;\n\t}\n\n\tpublic void setAddr_phone(String addr_phone) {\n\t\tthis.addr_phone = addr_phone;\n\t}\n\n\t// public long getAddr_user_id() {\n\t// return addr_user_id;\n\t// }\n\t//\n\t// public void setAddr_user_id(long addr_user_id) {\n\t// this.addr_user_id = addr_user_id;\n\t// }\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Address [addr_id=\" + addr_id + \", user=\" + user\n\t\t\t\t+ \", addr_name=\" + addr_name + \", addr_user_name=\"\n\t\t\t\t+ addr_user_name + \",addr_phone=\"+addr_phone+\"]\";\n\t}\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n}", "public class Book {\n\tprivate long book_id;\n\tprivate String book_name;\n\tprivate String book_author;\n\tprivate String book_isbn;\n\tprivate String book_publish_company;\n\tprivate String book_publish_datetime;\n\tprivate String book_author_introduce;\n\tprivate String book_catalogue;\n\tprivate String book_picture;\n\tprivate String book_parameter;\n\tprivate String book_content_introduce;\n\tprivate double book_price;\n\tprivate long book_hous_id;\n\tprivate String book_type;\n\tprivate int book_sum;\n\tprivate boolean book_status;\n\tprivate int book_sale_sum;\n\tprivate double book_score;\n\tprivate int book_sale_comment_sum;\n\n\tpublic long getBook_id() {\n\t\treturn book_id;\n\t}\n\n\tpublic void setBook_id(long book_id) {\n\t\tthis.book_id = book_id;\n\t}\n\n\tpublic String getBook_name() {\n\t\treturn book_name;\n\t}\n\n\tpublic void setBook_name(String book_name) {\n\t\tthis.book_name = book_name;\n\t}\n\n\tpublic String getBook_author() {\n\t\treturn book_author;\n\t}\n\n\tpublic void setBook_author(String book_author) {\n\t\tthis.book_author = book_author;\n\t}\n\n\tpublic String getBook_isbn() {\n\t\treturn book_isbn;\n\t}\n\n\tpublic void setBook_isbn(String book_isbn) {\n\t\tthis.book_isbn = book_isbn;\n\t}\n\n\tpublic String getBook_publish_company() {\n\t\treturn book_publish_company;\n\t}\n\n\tpublic void setBook_publish_company(String book_publish_company) {\n\t\tthis.book_publish_company = book_publish_company;\n\t}\n\n\tpublic String getBook_publish_datetime() {\n\t\treturn book_publish_datetime;\n\t}\n\n\tpublic void setBook_publish_datetime(String book_publish_datetime) {\n\t\tthis.book_publish_datetime = book_publish_datetime;\n\t}\n\n\tpublic String getBook_author_introduce() {\n\t\treturn book_author_introduce;\n\t}\n\n\tpublic void setBook_author_introduce(String book_author_introduce) {\n\t\tthis.book_author_introduce = book_author_introduce;\n\t}\n\n\tpublic String getBook_catalogue() {\n\t\treturn book_catalogue;\n\t}\n\n\tpublic void setBook_catalogue(String book_catalogue) {\n\t\tthis.book_catalogue = book_catalogue;\n\t}\n\n\tpublic String getBook_picture() {\n\t\treturn book_picture;\n\t}\n\n\tpublic void setBook_picture(String book_picture) {\n\t\tthis.book_picture = book_picture;\n\t}\n\n\tpublic String getBook_parameter() {\n\t\treturn book_parameter;\n\t}\n\n\tpublic void setBook_parameter(String book_parameter) {\n\t\tthis.book_parameter = book_parameter;\n\t}\n\n\tpublic String getBook_content_introduce() {\n\t\treturn book_content_introduce;\n\t}\n\n\tpublic void setBook_content_introduce(String book_content_introduce) {\n\t\tthis.book_content_introduce = book_content_introduce;\n\t}\n\n\tpublic double getBook_price() {\n\t\treturn book_price;\n\t}\n\n\tpublic void setBook_price(double book_price) {\n\t\tthis.book_price = book_price;\n\t}\n\n\tpublic long getBook_hous_id() {\n\t\treturn book_hous_id;\n\t}\n\n\tpublic void setBook_hous_id(long book_hous_id) {\n\t\tthis.book_hous_id = book_hous_id;\n\t}\n\n\tpublic int getBook_sum() {\n\t\treturn book_sum;\n\t}\n\n\tpublic void setBook_sum(int book_sum) {\n\t\tthis.book_sum = book_sum;\n\t}\n\n\tpublic boolean isBook_status() {\n\t\treturn book_status;\n\t}\n\n\tpublic void setBook_status(boolean book_status) {\n\t\tthis.book_status = book_status;\n\t}\n\n\tpublic String getBook_type() {\n\t\treturn book_type;\n\t}\n\n\tpublic void setBook_type(String book_type) {\n\t\tthis.book_type = book_type;\n\t}\n\n\tpublic int getBook_sale_sum() {\n\t\treturn book_sale_sum;\n\t}\n\n\tpublic void setBook_sale_sum(int book_sale_sum) {\n\t\tthis.book_sale_sum = book_sale_sum;\n\t}\n\n\tpublic double getBook_score() {\n\t\treturn book_score;\n\t}\n\n\tpublic void setBook_score(double book_score) {\n\t\tthis.book_score = book_score;\n\t}\n\n\tpublic int getBook_sale_comment_sum() {\n\t\treturn book_sale_comment_sum;\n\t}\n\n\tpublic void setBook_sale_comment_sum(int book_sale_comment_sum) {\n\t\tthis.book_sale_comment_sum = book_sale_comment_sum;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Book [book_id=\" + book_id + \",book_name=\" + book_name\n\t\t\t\t+ \", book_hous_id=\" + book_hous_id + \"]\";\n\t}\n}", "public class Order {\n\tprivate long orde_id;\n\n\tprivate String orde_number;\n\n\t// private long orde_book_id;\n\n\tprivate Book orde_book;\n\t// private long orde_user_id;\n\tprivate User orde_user;\n\tprivate int orde_book_amount;\n\n\t/**\n\t * 订单状态:0:未下单;1:已下单未发货;2:已下单已发货未收货;3:已下单已发货已收货未评价;4:已下单已发货已收货已付款已评价\n\t * 3和4都表示已完成订单\n\t */\n\tprivate int orde_status;\n\n\tprivate Date orde_datetime;\n\n\tprivate double orde_price;\n\n\tprivate String orde_user_comment;\n\tprivate String orde_addr_name;\n\tprivate String orde_addr_user_name;\n\tprivate String orde_addr_phone;\n\tprivate double orde_user_score;\n\n\tpublic long getOrde_id() {\n\t\treturn orde_id;\n\t}\n\n\tpublic void setOrde_id(long orde_id) {\n\t\tthis.orde_id = orde_id;\n\t}\n\n\tpublic String getOrde_number() {\n\t\treturn orde_number;\n\t}\n\n\tpublic void setOrde_number(String orde_number) {\n\t\tthis.orde_number = orde_number;\n\t}\n\n\tpublic Book getOrde_book() {\n\t\treturn orde_book;\n\t}\n\n\tpublic void setOrde_book(Book orde_book) {\n\t\tthis.orde_book = orde_book;\n\t}\n\n\tpublic User getOrde_user() {\n\t\treturn orde_user;\n\t}\n\n\tpublic void setOrde_user(User orde_user) {\n\t\tthis.orde_user = orde_user;\n\t}\n\n\tpublic int getOrde_book_amount() {\n\t\treturn orde_book_amount;\n\t}\n\n\tpublic void setOrde_book_amount(int orde_book_amount) {\n\t\tthis.orde_book_amount = orde_book_amount;\n\t}\n\n\tpublic int getOrde_status() {\n\t\treturn orde_status;\n\t}\n\n\tpublic void setOrde_status(int orde_status) {\n\t\tthis.orde_status = orde_status;\n\t}\n\n\tpublic Date getOrde_datetime() {\n\t\treturn orde_datetime;\n\t}\n\n\tpublic void setOrde_datetime(Date orde_datetime) {\n\t\tthis.orde_datetime = orde_datetime;\n\t}\n\n\tpublic double getOrde_price() {\n\t\treturn orde_price;\n\t}\n\n\tpublic void setOrde_price(double orde_price) {\n\t\tthis.orde_price = orde_price;\n\t}\n\n\tpublic String getOrde_user_comment() {\n\t\treturn orde_user_comment;\n\t}\n\n\tpublic void setOrde_user_comment(String orde_user_comment) {\n\t\tthis.orde_user_comment = orde_user_comment;\n\t}\n\n\tpublic String getOrde_addr_name() {\n\t\treturn orde_addr_name;\n\t}\n\n\tpublic void setOrde_addr_name(String orde_addr_name) {\n\t\tthis.orde_addr_name = orde_addr_name;\n\t}\n\n\tpublic String getOrde_addr_user_name() {\n\t\treturn orde_addr_user_name;\n\t}\n\n\tpublic void setOrde_addr_user_name(String orde_addr_user_name) {\n\t\tthis.orde_addr_user_name = orde_addr_user_name;\n\t}\n\n\tpublic String getOrde_addr_phone() {\n\t\treturn orde_addr_phone;\n\t}\n\n\tpublic void setOrde_addr_phone(String orde_addr_phone) {\n\t\tthis.orde_addr_phone = orde_addr_phone;\n\t}\n\n\tpublic double getOrde_user_score() {\n\t\treturn orde_user_score;\n\t}\n\n\tpublic void setOrde_user_score(double orde_user_score) {\n\t\tthis.orde_user_score = orde_user_score;\n\t}\n\n}", "public interface OrderService {\n\tpublic int addOrder(Order order);\n\n\t/**\n\t * @author pan\n\t * @param orderid\n\t * @return\n\t */\n\tpublic Order findOrderById(long orderid);\n\n\t/**\n\t * @author pan\n\t * @param order\n\t */\n\tpublic void assertOrder(Order order);\n\n\tpublic void commentOrder(Order order,double book_score, long book_id, int book_sale_sum, int book_sale_comment_sum);\n\n\t/**\n\t * @author pan\n\t * @param user_id\n\t * @return\n\t */\n\tpublic List<Address> findOrderUserAddress(long user_id);\n\n\t/**\n\t * @author pan\n\t * @param order\n\t */\n\tpublic void assertOrderWithAddr(Order order);\n\n\t/**\n\t * @author pan\n\t * @param order\n\t */\n\tpublic void assertOrderAndBook(Order order);\n}" ]
import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.phn.bookhouse.dao.AddressDao; import com.phn.bookhouse.dao.BookDao; import com.phn.bookhouse.dao.OrderDao; import com.phn.bookhouse.entity.Address; import com.phn.bookhouse.entity.Book; import com.phn.bookhouse.entity.Order; import com.phn.bookhouse.service.OrderService;
/** * */ package com.phn.bookhouse.service.impl; /** * @file OrderServiceImpl.java * @author pan * @date 2014年11月17日 * @email [email protected] */ @Service("orderService") public class OrderServiceImpl implements OrderService { @Autowired
private OrderDao orderDao;
2
TechzoneMC/NPCLib
nms-v1_7_R4/src/main/java/net/techcable/npclib/nms/versions/v1_7_R4/HumanNPCHook.java
[ "@RequiredArgsConstructor\npublic enum Animation {\n /**\n * Makes the npc act hurt\n * <p/>\n * Only applicable to living entities\n */\n HURT,\n /**\n * Makes the npc lie on the ground\n * <p/>\n * Only applicable to living entities\n */\n DEAD,\n\n // Human Animations\n\n /**\n * Makes the npc swing its arm\n * <p/>\n * Only applicable to human entities\n */\n ARM_SWING(HumanNPC.class),\n /**\n * Makes the npc eat the item it is holding\n * <p/>\n * Only applicable to human entities\n */\n EAT(HumanNPC.class),\n /**\n * A critical hit animation\n * <p/>\n * Only applicable to human entities\n */\n CRITICAL(HumanNPC.class),\n /**\n * A 'magic' critical hit animation\n * <p/>\n * Only applicable to human entities\n */\n MAGIC_CRITICAL(HumanNPC.class);\n\n\n private final Class<? extends NPC> appliesTo;\n\n /**\n * Get the type of npc this animation can be applied to\n *\n * @return the type of npc this animation can be applied to\n */\n public Class<? extends NPC> getAppliesTo() {\n return appliesTo;\n }\n\n private Animation() {\n this(LivingNPC.class);\n }\n}", "public interface HumanNPC extends LivingNPC {\r\n\r\n /**\r\n * Return this npc's skin\r\n * <p/>\r\n * A value of null represents a steve skin\r\n *\r\n * @return this npc's skin\r\n */\r\n public UUID getSkin();\r\n\r\n /**\r\n * Set the npc's skin\r\n * <p/>\r\n * A value of null represents a steve skin\r\n *\r\n * @param skin the player id with the skin you want\r\n *\r\n * @throws UnsupportedOperationException if skins aren't supported\r\n */\r\n public void setSkin(UUID skin);\r\n\r\n /**\r\n * Set the npc's skin\r\n * <p/>\r\n * A value of null represents a steve skin\r\n *\r\n * @param skin the player name with the skin you want\r\n *\r\n * @throws UnsupportedOperationException if skins aren't supported\r\n */\r\n public void setSkin(String skin);\r\n\r\n /**\r\n * Get the nmsEntity associated with this npc\r\n *\r\n * @return the nmsEntity\r\n */\r\n @Override\r\n public Player getEntity();\r\n\r\n /**\r\n * Set if the npc is shown in the tab list\r\n *\r\n * @param show whether or not to show this npc in the tab list\r\n *\r\n * @throws java.lang.IllegalStateException if the npcc is not spawned\r\n */\r\n public void setShowInTabList(boolean show);\r\n\r\n /**\r\n * Return if the npc is shown in the tab list\r\n *\r\n * @return true if the npc is shown in the tab list\r\n */\r\n public boolean isShownInTabList();\r\n}\r", "public interface IHumanNPCHook extends ILivingNPCHook {\r\n\r\n public void setSkin(UUID id); //Remember to do this while despawned\r\n\r\n public void showInTablist();\r\n\r\n public void hideFromTablist();\r\n}\r", "@Getter\npublic class EntityNPCPlayer extends EntityPlayer {\n\n private final HumanNPC npc;\n @Setter\n private HumanNPCHook hook;\n\n public EntityNPCPlayer(HumanNPC npc, Location location) {\n super(NMS.getServer(), NMS.getHandle(location.getWorld()), makeProfile(npc), new PlayerInteractManager(NMS.getHandle(location.getWorld())));\n playerInteractManager.b(EnumGamemode.SURVIVAL); //MCP = initializeGameType ---- SRG=func_73077_b\n this.npc = npc;\n playerConnection = new NPCConnection(this);\n\n setPosition(location.getX(), location.getY(), location.getZ());\n }\n\n @Override\n public boolean damageEntity(DamageSource source, float damage) {\n if (npc.isProtected()) {\n return false;\n }\n return super.damageEntity(source, damage);\n }\n\n private static GameProfile makeProfile(HumanNPC npc) {\n GameProfile profile = new GameProfile(UUID.randomUUID(), npc.getName());\n NMS.setSkin(profile, npc.getSkin());\n return profile;\n }\n}", "public class Reflection {\n\n public static Class<?> getNmsClass(String name) {\n String className = \"net.minecraft.server.\" + getVersion() + \".\" + name;\n return getClass(className);\n }\n\n public static Class<?> getCbClass(String name) {\n String className = \"org.bukkit.craftbukkit.\" + getVersion() + \".\" + name;\n return getClass(className);\n }\n\n public static Class<?> getUtilClass(String name) {\n try {\n return Class.forName(name); //Try before 1.8 first\n } catch (ClassNotFoundException ex) {\n try {\n return Class.forName(\"net.minecraft.util.\" + name); //Not 1.8\n } catch (ClassNotFoundException ex2) {\n return null;\n }\n }\n }\n\n public static String getVersion() {\n String packageName = Bukkit.getServer().getClass().getPackage().getName();\n return packageName.substring(packageName.lastIndexOf('.') + 1);\n }\n\n public static Object getHandle(Object wrapper) {\n Method getHandle = makeMethod(wrapper.getClass(), \"getHandle\");\n return callMethod(getHandle, wrapper);\n }\n\n //Utils\n public static Method makeMethod(Class<?> clazz, String methodName, Class<?>... paramaters) {\n try {\n return clazz.getDeclaredMethod(methodName, paramaters);\n } catch (NoSuchMethodException ex) {\n return null;\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> T callMethod(Method method, Object instance, Object... paramaters) {\n if (method == null) throw new RuntimeException(\"No such method\");\n method.setAccessible(true);\n try {\n return (T) method.invoke(instance, paramaters);\n } catch (InvocationTargetException ex) {\n throw new RuntimeException(ex.getCause());\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> Constructor<T> makeConstructor(Class<?> clazz, Class<?>... paramaterTypes) {\n try {\n return (Constructor<T>) clazz.getConstructor(paramaterTypes);\n } catch (NoSuchMethodException ex) {\n return null;\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n\n public static <T> T callConstructor(Constructor<T> constructor, Object... paramaters) {\n if (constructor == null) throw new RuntimeException(\"No such constructor\");\n constructor.setAccessible(true);\n try {\n return (T) constructor.newInstance(paramaters);\n } catch (InvocationTargetException ex) {\n throw new RuntimeException(ex.getCause());\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n\n public static Field makeField(Class<?> clazz, String name) {\n try {\n return clazz.getDeclaredField(name);\n } catch (NoSuchFieldException ex) {\n return null;\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> T getField(Field field, Object instance) {\n if (field == null) throw new RuntimeException(\"No such field\");\n field.setAccessible(true);\n try {\n return (T) field.get(instance);\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n\n public static void setField(Field field, Object instance, Object value) {\n if (field == null) throw new RuntimeException(\"No such field\");\n field.setAccessible(true);\n try {\n field.set(instance, value);\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n\n public static Class<?> getClass(String name) {\n try {\n return Class.forName(name);\n } catch (ClassNotFoundException ex) {\n return null;\n }\n }\n\n public static <T> Class<? extends T> getClass(String name, Class<T> superClass) {\n try {\n return Class.forName(name).asSubclass(superClass);\n } catch (ClassCastException | ClassNotFoundException ex) {\n return null;\n }\n }\n}" ]
import java.lang.reflect.Field; import java.util.List; import java.util.UUID; import net.minecraft.server.v1_7_R4.EntityPlayer; import net.minecraft.server.v1_7_R4.Packet; import net.minecraft.server.v1_7_R4.PacketPlayOutAnimation; import net.minecraft.server.v1_7_R4.PacketPlayOutPlayerInfo; import net.minecraft.util.com.mojang.authlib.GameProfile; import net.techcable.npclib.Animation; import net.techcable.npclib.HumanNPC; import net.techcable.npclib.nms.IHumanNPCHook; import net.techcable.npclib.nms.versions.v1_7_R4.entity.EntityNPCPlayer; import net.techcable.npclib.utils.Reflection; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import com.google.common.base.Preconditions;
package net.techcable.npclib.nms.versions.v1_7_R4; public class HumanNPCHook extends LivingNPCHook implements IHumanNPCHook { public HumanNPCHook(HumanNPC npc, Location toSpawn) { super(npc, toSpawn, EntityType.PLAYER); getNmsEntity().setHook(this); getNmsEntity().getWorld().players.remove(getNmsEntity()); } @Override public void setSkin(UUID id) { NMS.setSkin(getNmsEntity().getProfile(), id); respawn(); } private boolean shownInTabList; @Override public void showInTablist() { if (shownInTabList) return; if (ProtocolHack.isProtocolHack()) { Packet packet18 = ProtocolHack.newPlayerInfoDataAdd(getNmsEntity()); NMS.sendToAll(packet18); } else { PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(getNmsEntity().getProfile().getName(), true, 0); NMS.sendToAll(packet); } shownInTabList = true; } @Override public void hideFromTablist() { if (!shownInTabList) return; if (ProtocolHack.isProtocolHack()) { Packet packet18 = ProtocolHack.newPlayerInfoDataRemove(getNmsEntity()); NMS.sendToAll(packet18); } else { PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(getNmsEntity().getProfile().getName(), false, 0); NMS.sendToAll(packet); } shownInTabList = false; }
public EntityNPCPlayer getNmsEntity() {
3
Integreight/1Sheeld-Android-App
oneSheeld/src/main/java/com/integreight/onesheeld/appFragments/SheeldsList.java
[ "public class MainActivity extends FragmentActivity {\n public static final int PREMISSION_REQUEST_CODE = 1;\n public static final int DRAW_OVER_APPS_REQUEST_CODE = 2;\n public static final String IS_CONTEXT_MENU_BUTTON_TUTORIAL_SHOWN_SP = \"com.integreight.onesheeld.IS_CONTEXT_MENU_BUTTON_TUTORIAL_SHOWN_SP\";\n public static String currentShieldTag = null;\n public static MainActivity thisInstance;\n public AppSlidingLeftMenu appSlidingMenu;\n public boolean isForground = false;\n private boolean isBackPressed = false;\n TextView oneSheeldLogo;\n\n private CopyOnWriteArrayList<OnSlidingMenueChangeListner> onChangeSlidingLockListeners = new CopyOnWriteArrayList<>();\n\n public OneSheeldApplication getThisApplication() {\n return (OneSheeldApplication) getApplication();\n }\n\n // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)\n @Override\n public void onCreate(Bundle savedInstance) {\n super.onCreate(savedInstance);\n handleNotificationWithUrlIntent(getIntent());\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n Window window = getWindow();\n window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);\n window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);\n window.setStatusBarColor(Color.parseColor(\"#CC3a3a3a\"));\n }\n setContentView(R.layout.one_sheeld_main);\n oneSheeldLogo = (TextView) findViewById(R.id.currentViewTitle);\n initLooperThread();\n if (savedInstance == null || getThisApplication().isConnectedToBluetooth()) {\n// if (savedInstance != null) {\n// int count = getSupportFragmentManager().getBackStackEntryCount();\n// while (count > 0) {\n// getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().getFragments().get(count)).commit();\n// count --;\n// }\n// }\n replaceCurrentFragment(R.id.appTransitionsContainer,\n SheeldsList.getInstance(), \"base\", true, false);\n }\n postConfigChange();\n resetSlidingMenu();\n thisInstance = this;\n if (getThisApplication().getShowTutAgain()\n && getThisApplication().getTutShownTimes() < 6)\n startActivity(new Intent(MainActivity.this, Tutorial.class));\n AppRate.with(this)\n .setInstallDays(7)\n .setLaunchTimes(5)\n .setRemindInterval(2)\n .setOnClickButtonListener(new OnClickButtonListener() { // callback listener.\n @Override\n public void onClickButton(int which) {\n Map<String, String> hit = null;\n switch (which) {\n case Dialog.BUTTON_NEGATIVE:\n hit = new HitBuilders.EventBuilder()\n .setCategory(\"App Rating Dialog\")\n .setAction(\"No\")\n .build();\n break;\n case Dialog.BUTTON_NEUTRAL:\n hit = new HitBuilders.EventBuilder()\n .setCategory(\"App Rating Dialog\")\n .setAction(\"Later\")\n .build();\n break;\n case Dialog.BUTTON_POSITIVE:\n hit = new HitBuilders.EventBuilder()\n .setCategory(\"App Rating Dialog\")\n .setAction(\"Yes\")\n .build();\n break;\n }\n if (hit != null) getThisApplication()\n .getTracker()\n .send(hit);\n }\n })\n .monitor();\n }\n\n public Thread looperThread;\n public Handler backgroundThreadHandler;\n Handler versionHandling = new Handler();\n public OneSheeldVersionQueryCallback versionQueryCallback = new OneSheeldVersionQueryCallback() {\n ValidationPopup popub;\n\n @Override\n public void onFirmwareVersionQueryResponse(OneSheeldDevice device, FirmwareVersion firmwareVersion) {\n super.onFirmwareVersionQueryResponse(device, firmwareVersion);\n final int minorVersion = firmwareVersion.getMinorVersion();\n final int majorVersion = firmwareVersion.getMajorVersion();\n versionHandling.post(new Runnable() {\n\n @Override\n public void run() {\n Log.d(\"Onesheeld\", minorVersion + \" \" + majorVersion);\n if (getThisApplication().getMinorVersion() != -1\n && getThisApplication().getMajorVersion() != -1) {\n if (majorVersion == getThisApplication()\n .getMajorVersion()\n && minorVersion != getThisApplication()\n .getMinorVersion()) {\n String msg = \"\";\n try {\n JSONObject obj = new JSONObject(\n ((OneSheeldApplication) getApplication())\n .getVersionWebResult());\n try {\n msg += obj.getString(\"name\") + \"\\n\";\n } catch (Exception e) {\n // TODO: handle exception\n }\n try {\n msg += obj.getString(\"description\") + \"\\n\";\n } catch (Exception e) {\n // TODO: handle exception\n }\n try {\n msg += obj.getString(\"date\");\n } catch (Exception e) {\n // TODO: handle exception\n }\n } catch (JSONException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n popub = new ValidationPopup(\n MainActivity.this,\n getString(R.string.firmware_upgrade_decision_dialog_optional_firmware_upgrade),\n msg,\n new ValidationPopup.ValidationAction(getString(R.string.firmware_upgrade_decision_dialog_now_button),\n new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n new FirmwareUpdatingPopup(\n MainActivity.this/*\n * ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * false\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t */)\n .show();\n }\n }, true),\n new ValidationPopup.ValidationAction(\n getString(R.string.firmware_upgrade_decision_dialog_not_now_button),\n new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n // TODO Auto-generated\n // method\n // stub\n\n }\n }, true));\n if (!isFinishing())\n popub.show();\n } else if (majorVersion != getThisApplication()\n .getMajorVersion()) {\n String msg = \"\";\n try {\n JSONObject obj = new JSONObject(\n ((OneSheeldApplication) getApplication())\n .getVersionWebResult());\n try {\n msg += obj.getString(\"name\") + \"\\n\";\n } catch (Exception e) {\n // TODO: handle exception\n }\n try {\n msg += obj.getString(\"description\") + \"\\n\";\n } catch (Exception e) {\n // TODO: handle exception\n }\n try {\n msg += obj.getString(\"date\");\n } catch (Exception e) {\n // TODO: handle exception\n }\n } catch (JSONException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n popub = new ValidationPopup(MainActivity.this,\n getString(R.string.firmware_upgrade_decision_dialog_required_firmware_upgrade), msg,\n new ValidationPopup.ValidationAction(\n getString(R.string.firmware_upgrade_decision_dialog_start),\n new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n FirmwareUpdatingPopup fup = new FirmwareUpdatingPopup(\n MainActivity.this/*\n * ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t * false\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t */\n );\n fup.setCancelable(false);\n fup.show();\n }\n }, true));\n if (!isFinishing())\n popub.show();\n }\n }\n }\n });\n getThisApplication().getTracker().send(\n new HitBuilders.ScreenViewBuilder().setCustomDimension(1,\n majorVersion + \".\" + minorVersion).build());\n }\n\n @Override\n public void onLibraryVersionQueryResponse(OneSheeldDevice device, final int libraryVersion) {\n super.onLibraryVersionQueryResponse(device, libraryVersion);\n versionHandling.post(new Runnable() {\n\n @Override\n public void run() {\n if (libraryVersion < OneSheeldApplication.ARDUINO_LIBRARY_VERSION) {\n popub = new ValidationPopup(\n MainActivity.this,\n getString(R.string.library_upgrade_dialog_arduino_library_update),\n getString(R.string.library_upgrade_dialog_theres_a_new_version_of_1sheelds_arduino_library_available_on_our_website),\n new ValidationPopup.ValidationAction(getString(R.string.library_upgrade_dialog_ok_button),\n new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n popub.dismiss();\n }\n }, true));\n if (!isFinishing())\n popub.show();\n }\n getThisApplication().getTracker().send(\n new HitBuilders.ScreenViewBuilder()\n .setCustomDimension(2, libraryVersion + \"\")\n .build());\n }\n });\n }\n };\n boolean isConfigChanged = false;\n long pausingTime = 0;\n private onConnectedToBluetooth onConnectToBlueTooth = null;\n private Looper backgroundHandlerLooper;\n private BackOnconnectionLostHandler backOnConnectionLostHandler;\n\n private void stopLooperThread() {\n if (looperThread != null && looperThread.isAlive()) {\n looperThread.interrupt();\n backgroundHandlerLooper.quit();\n looperThread = null;\n }\n }\n\n public void initLooperThread() {\n stopLooperThread();\n looperThread = new Thread(new Runnable() {\n\n @Override\n public void run() {\n // TODO Auto-generated method stub\n Looper.prepare();\n backgroundHandlerLooper = Looper.myLooper();\n backgroundThreadHandler = new Handler();\n Looper.loop();\n }\n });\n looperThread.start();\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n thisInstance = this;\n }\n\n public BackOnconnectionLostHandler getOnConnectionLostHandler() {\n if (backOnConnectionLostHandler == null) {\n backOnConnectionLostHandler = new BackOnconnectionLostHandler(this);\n }\n return backOnConnectionLostHandler;\n }\n\n @Override\n public void onBackPressed() {\n Log.d(\"Test\", \"Back Pressed\");\n ///// Camera Preview\n if (getThisApplication().getRunningShields().get(UIShield.CAMERA_SHIELD.name()) != null)\n try {\n ((CameraShield) getThisApplication().getRunningShields().get(UIShield.CAMERA_SHIELD.name())).hidePreview();\n } catch (RemoteException e) {\n e.printStackTrace();\n }\n if (getThisApplication().getRunningShields().get(UIShield.COLOR_DETECTION_SHIELD.name()) != null)\n try {\n ((ColorDetectionShield) getThisApplication().getRunningShields().get(UIShield.COLOR_DETECTION_SHIELD.name())).hidePreview();\n } catch (RemoteException e) {\n e.printStackTrace();\n }\n if (getThisApplication().getRunningShields().get(UIShield.FACE_DETECTION.name()) != null)\n try {\n ((FaceDetectionShield) getThisApplication().getRunningShields().get(UIShield.FACE_DETECTION.name())).hidePreview();\n } catch (RemoteException e) {\n e.printStackTrace();\n }\n resetSlidingMenu();\n MultiDirectionSlidingDrawer pinsView = (MultiDirectionSlidingDrawer) findViewById(R.id.pinsViewSlidingView);\n MultiDirectionSlidingDrawer settingsView = (MultiDirectionSlidingDrawer) findViewById(R.id.settingsSlidingView);\n if ((pinsView == null || (pinsView != null && !pinsView.isOpened()))\n && (settingsView == null || (settingsView != null && !settingsView\n .isOpened()))) {\n if (appSlidingMenu.isOpen()) {\n appSlidingMenu.closePane();\n } else {\n if (getSupportFragmentManager().getBackStackEntryCount() > 1) {\n findViewById(R.id.getAvailableDevices).setOnClickListener(\n new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n }\n });\n if (findViewById(R.id.isMenuOpening) != null)\n ((CheckBox) findViewById(R.id.isMenuOpening))\n .setChecked(false);\n getSupportFragmentManager().popBackStack();// (\"operations\",FragmentManager.POP_BACK_STACK_INCLUSIVE);\n getSupportFragmentManager().executePendingTransactions();\n } else {\n moveTaskToBack(true);\n }\n }\n } else {\n if (pinsView.isOpened())\n pinsView.animateOpen();\n else if (settingsView.isOpened())\n settingsView.animateOpen();\n }\n }\n\n private void killAllProcesses() {\n Process.killProcess(Process.myPid());\n }\n\n public void replaceCurrentFragment(int container, Fragment targetFragment,\n String tag, boolean addToBackStack, boolean animate) {\n if (!isFinishing()) {\n FragmentManager manager = getSupportFragmentManager();\n boolean fragmentPopped = manager.popBackStackImmediate(tag, 0);\n\n if (!fragmentPopped && manager.findFragmentByTag(tag) == null) {\n FragmentTransaction ft = manager.beginTransaction();\n if (animate)\n ft.setCustomAnimations(R.anim.slide_out_right,\n R.anim.slide_in_left, R.anim.slide_out_left,\n R.anim.slide_in_right);\n ft.replace(container, targetFragment, tag);\n if (addToBackStack) {\n ft.addToBackStack(tag);\n }\n ft.commit();\n }\n }\n }\n\n public void stopService() {\n this.stopService(new Intent(this, OneSheeldService.class));\n }\n\n public void finishManually() {\n isBackPressed = true;\n finish();\n destroyIt();\n }\n\n private void preConfigChange() {\n Enumeration<String> enumKey = ((OneSheeldApplication)\n getApplication()).getRunningShields().keys();\n while (enumKey.hasMoreElements()) {\n String key = enumKey.nextElement();\n ((OneSheeldApplication) getApplication())\n .getRunningShields().get(key).preConfigChangeThis();\n }\n }\n\n private void postConfigChange() {\n Enumeration<String> enumKey = ((OneSheeldApplication)\n getApplication()).getRunningShields().keys();\n while (enumKey.hasMoreElements()) {\n String key = enumKey.nextElement();\n ((OneSheeldApplication) getApplication())\n .getRunningShields().get(key).updateActivty(this);\n ((OneSheeldApplication) getApplication())\n .getRunningShields().get(key).postConfigChangeThis();\n }\n }\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n isConfigChanged = true;\n preConfigChange();\n super.onConfigurationChanged(newConfig);\n postConfigChange();\n }\n\n private void destroyIt() {\n if (!isConfigChanged) {\n getThisApplication().getTracker().send(\n new HitBuilders.EventBuilder().setCategory(\"App lifecycle\")\n .setAction(\"Finished the app manually\").build());\n ArduinoConnectivityPopup.isOpened = false;\n stopService();\n stopLooperThread();\n moveTaskToBack(true);\n OneSheeldSdk.getManager().disconnectAll();\n // // unExpeted\n if (!isBackPressed) {\n Enumeration<String> enumKey = ((OneSheeldApplication)\n getApplication()).getRunningShields().keys();\n while (enumKey.hasMoreElements()) {\n String key = enumKey.nextElement();\n ((OneSheeldApplication) getApplication())\n .getRunningShields().get(key).resetThis();\n ((OneSheeldApplication) getApplication())\n .getRunningShields().remove(key);\n }\n Intent in = new Intent(getIntent());\n PendingIntent intent = PendingIntent.getActivity(\n getBaseContext(), 0, in, getIntent().getFlags());\n AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n mgr.setExact(AlarmManager.RTC, System.currentTimeMillis() + 100,\n intent);\n } else {\n mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100,\n intent);\n }\n killAllProcesses();\n } else\n killAllProcesses();\n }\n isConfigChanged = false;\n isBackPressed = false;\n }\n\n @Override\n protected void onDestroy() {\n ArduinoConnectivityPopup.isOpened = false;\n super.onDestroy();\n }\n\n public void openMenu() {\n resetSlidingMenu();\n appSlidingMenu.openPane();\n }\n\n public boolean isMenuOpened() {\n resetSlidingMenu();\n return appSlidingMenu.isOpen();\n }\n\n public void closeMenu() {\n resetSlidingMenu();\n appSlidingMenu.closePane();\n }\n\n public void enableMenu() {\n resetSlidingMenu();\n appSlidingMenu.setCanSlide(true);\n }\n\n public void disableMenu() {\n resetSlidingMenu();\n appSlidingMenu.closePane();\n appSlidingMenu.setCanSlide(false);\n }\n\n private void resetSlidingMenu() {\n if (appSlidingMenu == null) {\n appSlidingMenu = (AppSlidingLeftMenu) findViewById(R.id.sliding_pane_layout);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)\n appSlidingMenu.setFitsSystemWindows(true);\n appSlidingMenu.setPanelSlideListener(new SlidingPaneLayout.PanelSlideListener() {\n @Override\n public void onPanelSlide(View panel, float slideOffset) {\n\n }\n\n @Override\n public void onPanelOpened(View panel) {\n\n }\n\n @Override\n public void onPanelClosed(View panel) {\n if (onChangeSlidingLockListeners != null && onChangeSlidingLockListeners.size() > 0) {\n for (OnSlidingMenueChangeListner onChangeListener : onChangeSlidingLockListeners) {\n onChangeListener.onMenuClosed();\n }\n }\n }\n });\n }\n }\n\n public void setOnConnectToBluetooth(onConnectedToBluetooth listener) {\n this.onConnectToBlueTooth = listener;\n }\n\n @Override\n public void onActivityResult(int requestCode, int resultCode, Intent data) {\n switch (requestCode) {\n case SheeldsList.REQUEST_CONNECT_DEVICE:\n break;\n case SheeldsList.REQUEST_ENABLE_BT:\n // When the request to enable Bluetooth returns\n if (resultCode != Activity.RESULT_OK) {\n Toast.makeText(this, R.string.general_toasts_bluetooth_was_not_enabled_toast,\n Toast.LENGTH_SHORT).show();\n } else {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {\n if (onConnectToBlueTooth != null\n && ArduinoConnectivityPopup.isOpened && !((OneSheeldApplication) getApplication()).getIsDemoMode())\n onConnectToBlueTooth.onConnect();\n } else {\n checkAndAskForLocationPermission();\n }\n }\n break;\n case DRAW_OVER_APPS_REQUEST_CODE:\n if (canDrawOverApps()) {\n showToast(getString(R.string.main_activity_draw_over_apps_enabled_you_can_select_the_shield));\n } else {\n showToast(getString(R.string.main_activity_draw_over_apps_was_not_enabled));\n }\n break;\n default:\n break;\n }\n super.onActivityResult(requestCode, resultCode, data);\n }\n\n public Boolean checkForLocationPermission() {\n return (ContextCompat.checkSelfPermission(thisInstance,\n Manifest.permission.ACCESS_FINE_LOCATION)\n == PackageManager.PERMISSION_GRANTED);\n }\n\n public void checkAndAskForLocationPermission() {\n if (ContextCompat.checkSelfPermission(thisInstance,\n Manifest.permission.ACCESS_FINE_LOCATION)\n != PackageManager.PERMISSION_GRANTED) {\n if (ActivityCompat.shouldShowRequestPermissionRationale(thisInstance,\n Manifest.permission.ACCESS_FINE_LOCATION)) {\n\n // Show an expanation to the user *asynchronously* -- don't block\n // this thread waiting for the user's response! After the user\n // sees the explanation, try again to request the permission.\n AlertDialog.Builder locationPremissionExplanationDialog = new AlertDialog.Builder(thisInstance);\n locationPremissionExplanationDialog.setMessage(R.string.main_activity_bluetooth_scan_needs_location_permission).setPositiveButton(R.string.main_activity_allow_button, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n ActivityCompat.requestPermissions(thisInstance,\n new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},\n MainActivity.PREMISSION_REQUEST_CODE);\n }\n }).setNegativeButton(R.string.main_activity_deny_button, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n showToast(getString(R.string.main_activity_location_permission_denied));\n }\n }).create();\n locationPremissionExplanationDialog.show();\n\n } else {\n\n // No explanation needed, we can request the permission.\n\n ActivityCompat.requestPermissions(thisInstance,\n new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.LOCATION_HARDWARE},\n MainActivity.PREMISSION_REQUEST_CODE);\n }\n } else {\n if (onConnectToBlueTooth != null\n && ArduinoConnectivityPopup.isOpened)\n onConnectToBlueTooth.onConnect();\n }\n }\n\n @Override\n protected void onResumeFragments() {\n thisInstance = this;\n isForground = true;\n CrashlyticsUtils.setString(\"isBackground\", \"No\");\n new Thread(new Runnable() {\n\n @Override\n public void run() {\n ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);\n List<RunningAppProcessInfo> appProcesses = activityManager\n .getRunningAppProcesses();\n if(appProcesses!=null) {\n String apps = \"\";\n for (int i = 0; i < appProcesses.size(); i++) {\n Log.d(\"Executed app\", \"Application executed : \"\n + appProcesses.get(i).processName + \"\\t\\t ID: \"\n + appProcesses.get(i).pid + \"\");\n apps += appProcesses.get(i).processName + \"\\n\";\n }\n CrashlyticsUtils.setString(\"Running apps\", apps);\n }\n }\n }).start();\n\n super.onResumeFragments();\n resumeNfcMainActivityFragments();\n }\n\n private void resumeNfcMainActivityFragments() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {\n if (((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name()) != null) {\n PackageManager packageManager = getApplicationContext().getPackageManager();\n packageManager.setComponentEnabledSetting(new ComponentName(\"com.integreight.onesheeld\", \"com.integreight.onesheeld.NFCUtils-alias\"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);\n ((NfcShield) ((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name())).setupForegroundDispatch();\n }\n }\n }\n\n @Override\n protected void onPause() {\n isForground = false;\n pausingTime = System.currentTimeMillis();\n float hours = TimeUnit.MILLISECONDS.toSeconds(System\n .currentTimeMillis() - pausingTime);\n float minutes = TimeUnit.MILLISECONDS.toMinutes(System\n .currentTimeMillis() - pausingTime);\n float seconds = TimeUnit.MILLISECONDS.toHours(System\n .currentTimeMillis() - pausingTime);\n CrashlyticsUtils.setString(\"isBackground\", \"since \" + hours + \" hours - \"\n + minutes + \" minutes - \" + seconds + \" seconds\");\n new Thread(new Runnable() {\n\n @Override\n public void run() {\n ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);\n List<RunningAppProcessInfo> appProcesses = activityManager\n .getRunningAppProcesses();\n String apps = \"\";\n for (int i = 0; i < appProcesses.size(); i++) {\n Log.d(\"Executed app\", \"Application executed : \"\n + appProcesses.get(i).processName + \"\\t\\t ID: \"\n + appProcesses.get(i).pid + \"\");\n apps += appProcesses.get(i).processName + \" |||||| \";\n }\n CrashlyticsUtils.setString(\"Running apps\", apps);\n }\n }).start();\n pauseMainActivityNfc();\n super.onPause();\n }\n\n private void pauseMainActivityNfc() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {\n if (((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name()) != null) {\n PackageManager packageManager = getApplicationContext().getPackageManager();\n packageManager.setComponentEnabledSetting(new ComponentName(\"com.integreight.onesheeld\", \"com.integreight.onesheeld.NFCUtils-alias\"), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);\n ((NfcShield) ((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name())).stopForegroundDispatch();\n }\n }\n }\n\n @Override\n protected void onStart() {\n super.onStart();\n }\n\n @Override\n protected void onStop() {\n super.onStop();\n }\n\n @Override\n protected void onNewIntent(final Intent intent) {\n if (intent!=null && intent.getStringExtra(\"url\")!=null && intent.getStringExtra(\"url\").length()>0){\n handleNotificationWithUrlIntent(intent);\n }\n else if (getThisApplication().getRunningShields().get(UIShield.NFC_SHIELD.name()) != null) {\n if (findViewById(R.id.progressShieldInit) != null && getSupportFragmentManager().findFragmentByTag(ShieldsOperations.class.getName()) == null) {\n findViewById(R.id.progressShieldInit)\n .setVisibility(View.VISIBLE);\n findViewById(R.id.operationsLogo)\n .setVisibility(View.INVISIBLE);\n findViewById(R.id.operationsLogo).postDelayed(new Runnable() {\n @Override\n public void run() {\n findViewById(R.id.progressShieldInit)\n .setVisibility(View.INVISIBLE);\n findViewById(R.id.operationsLogo)\n .setVisibility(View.VISIBLE);\n }\n }, 1000);\n }\n }\n backgroundThreadHandler.post(new Runnable() {\n @Override\n public void run() {\n getNfcIntent(intent);\n }\n });\n super.onNewIntent(intent);\n }\n\n private void getNfcIntent(Intent intent) {\n if (intent != null) {\n String action = intent.getAction();\n if (action != null)\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {\n if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {\n if (getThisApplication().getRunningShields().get(UIShield.NFC_SHIELD.name()) != null) {\n ((NfcShield) ((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name())).handleIntent(intent);\n }\n }\n }\n }\n }\n\n public void showToast(String msg) {\n Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();\n }\n\n public void showToast(int msgId) {\n Toast.makeText(this, msgId, Toast.LENGTH_SHORT).show();\n }\n\n public void hideSoftKeyboard() {\n if (getCurrentFocus() != null) {\n InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n inputMethodManager.hideSoftInputFromWindow(getCurrentFocus()\n .getWindowToken(), 0);\n }\n }\n\n public void registerSlidingMenuListner(OnSlidingMenueChangeListner listner) {\n if (!onChangeSlidingLockListeners.contains(listner))\n onChangeSlidingLockListeners.add(listner);\n }\n\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n// super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n if (requestCode == PREMISSION_REQUEST_CODE) {\n if (permissions.length > 0) {\n switch (permissions[0]) {\n case Manifest.permission.ACCESS_FINE_LOCATION:\n if (grantResults.length > 0\n && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n if (onConnectToBlueTooth != null\n && ArduinoConnectivityPopup.isOpened)\n onConnectToBlueTooth.onConnect();\n } else {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION))\n showToast(getString(R.string.main_activity_location_permission_denied));\n else\n showToast(getString(R.string.main_activity_please_turn_on_location_permission));\n }\n }\n break;\n default:\n Boolean isEnabled = true;\n for (int permissionsCount = 0; permissionsCount < grantResults.length; permissionsCount++) {\n if (grantResults[permissionsCount] != PackageManager.PERMISSION_GRANTED)\n isEnabled = false;\n }\n if (isEnabled) {\n showToast(getString(R.string.general_toasts_you_can_select_the_shield_now_toast));\n // permission was granted, yay! Do the\n // contacts-related task you need to do.\n } else {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n Boolean isShouldShowRequestPermissionRationale = true;\n for (int permissionsCount = 0; permissionsCount < permissions.length; permissionsCount++) {\n if (shouldShowRequestPermissionRationale(permissions[permissionsCount]) && grantResults[permissionsCount] != PackageManager.PERMISSION_GRANTED)\n isShouldShowRequestPermissionRationale = false;\n }\n if (!isShouldShowRequestPermissionRationale)\n showToast(getString(R.string.main_activity_this_shield_needs_some_permissions));\n else\n showToast(getString(R.string.main_activity_your_device_didnt_allow_this_shield_permissions));\n } else {\n showToast(getString(R.string.main_activity_this_shield_needs_some_permissions));\n }\n }\n break;\n }\n }\n return;\n }\n }\n\n public void showMenuButtonTutorialOnce() {\n if (Build.VERSION.SDK_INT >= 11 && oneSheeldLogo != null) {\n ViewTarget target = new ViewTarget(oneSheeldLogo);\n if (!getThisApplication().getAppPreferences().getBoolean(IS_CONTEXT_MENU_BUTTON_TUTORIAL_SHOWN_SP, false)) {\n new ShowcaseView.Builder(this)\n .setTarget(target)\n .withMaterialShowcase()\n .setContentTitle(getString(R.string.context_menu_tutorial_open_context_menu))\n .setContentText(getString(R.string.context_menu_tutorial_upgrade_the_firmware_clear_the_automatic_connection_and_see_the_tutorial_again_after_opening_the_context_menu_by_clicking_on_1sheeld_logo))\n .setStyle(R.style.CustomShowcaseTheme)\n .hideOnTouchOutside()\n .build().hideButton();\n getThisApplication().getAppPreferences().edit().putBoolean(IS_CONTEXT_MENU_BUTTON_TUTORIAL_SHOWN_SP, true).commit();\n }\n }\n }\n\n public boolean canDrawOverApps() {\n if (Build.VERSION.SDK_INT >= 23) {\n return Settings.canDrawOverlays(this);\n }\n return true;\n }\n\n public void requestDrawOverApps() {\n if (!canDrawOverApps()) {\n Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,\n Uri.parse(\"package:\" + getPackageName()));\n startActivityForResult(intent, DRAW_OVER_APPS_REQUEST_CODE);\n }\n }\n\n public interface OnSlidingMenueChangeListner {\n public void onMenuClosed();\n }\n\n private void handleNotificationWithUrlIntent(Intent intent) {\n if (intent != null && intent.getStringExtra(\"url\") != null && intent.getStringExtra(\"url\").length() > 0) {\n String url = intent.getStringExtra(\"url\");\n if (!url.startsWith(\"http://\") && !url.startsWith(\"https://\")) {\n url = \"http://\" + url;\n }\n Intent notificationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));\n notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n startActivity(notificationIntent);\n// finish();\n }\n }\n\n public class BackOnconnectionLostHandler extends Handler {\n public boolean canInvokeOnCloseConnection = true,\n connectionLost = false;\n\n private final WeakReference<MainActivity> mTarget;\n\n public BackOnconnectionLostHandler(MainActivity activity) {\n this.mTarget = new WeakReference<>(activity);\n }\n\n @Override\n public void handleMessage(Message msg) {\n final MainActivity activity = mTarget.get();\n if (activity != null) {\n if (!((OneSheeldApplication) activity.getApplication()).getIsDemoMode() && !getThisApplication().isConnectedToBluetooth()) {\n if (connectionLost) {\n if (!ArduinoConnectivityPopup.isOpened\n && !activity.isFinishing())\n activity.runOnUiThread(new Runnable() {\n public void run() {\n if (!ArduinoConnectivityPopup.isOpened\n && !activity.isFinishing()) {\n new ArduinoConnectivityPopup(\n activity).show();\n }\n }\n });\n if (activity.getSupportFragmentManager()\n .getBackStackEntryCount() > 1) {\n activity.getSupportFragmentManager().beginTransaction()\n .setCustomAnimations(0, 0, 0, 0)\n .commitAllowingStateLoss();\n activity.getSupportFragmentManager().popBackStack();// (\"operations\",FragmentManager.POP_BACK_STACK_INCLUSIVE);\n activity.getSupportFragmentManager()\n .executePendingTransactions();\n }\n }\n connectionLost = false;\n }\n }\n super.handleMessage(msg);\n }\n }\n}", "public class OneSheeldApplication extends Application {\n private SharedPreferences appPreferences;\n public static int ARDUINO_LIBRARY_VERSION = 17;\n private final String APP_PREF_NAME = \"oneSheeldPreference\";\n private final String LAST_DEVICE = \"lastConnectedDevice\";\n private final String MAJOR_VERSION = \"majorVersion\";\n private final String MINOR_VERSION = \"minorVersion\";\n private final String VERSION_WEB_RESULT = \"versionWebResult\";\n private final String BUZZER_SOUND_KEY = \"buzerSound\";\n private final String TUTORIAL_SHOWN_TIME = \"tutShownTime\";\n private final String SHOWTUTORIALS_AGAIN = \"showTutAgain\";\n private final String TASKER_CONDITION_PIN = \"taskerConditionPin\";\n private final String TASKER_CONDITION_STATUS = \"taskerConditionStatus\";\n private final String CAMERA_CAPTURING = \"cameraCapturing\";\n private final String REMEMBER_SHIELDS = \"rememberedShields\";\n private OneSheeldDevice connectedDevice;\n private Hashtable<String, ControllerParent<?>> runningSheelds = new Hashtable<String, ControllerParent<?>>();\n public Typeface appFont;\n // private GoogleAnalytics googleAnalyticsInstance;\n // private Tracker appGaTracker;\n public TaskerShield taskerController;\n public SparseArray<Boolean> taskerPinsStatus;\n private boolean isLocatedInTheUs = false;\n\n public static final String FIRMWARE_UPGRADING_URL = \"https://raw.githubusercontent.com/Integreight/1Sheeld-Firmware/master/version.json\";\n\n private static boolean isDebuggable = true;\n\n private static boolean isDemoMode = false;\n\n private Tracker gaTracker;\n\n private long connectionTime;\n\n private static Context context;\n\n public static Context getContext() {\n return context;\n }\n\n public void startConnectionTimer() {\n connectionTime = SystemClock.elapsedRealtime();\n }\n\n public void endConnectionTimerAndReport() {\n if (connectionTime == 0)\n return;\n Map<String, String> hit = new HitBuilders.TimingBuilder()\n .setCategory(\"Connection Timing\")\n .setValue(SystemClock.elapsedRealtime() - connectionTime)\n .setVariable(\"Connection\").build();\n // hit.put(\"&sc\", \"end\");\n getTracker().send(hit);\n connectionTime = 0;\n }\n\n public long getConnectionTime() {\n return connectionTime;\n }\n\n public synchronized Tracker getTracker() {\n if (gaTracker != null)\n return gaTracker;\n GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);\n analytics.setAppOptOut(isDebuggable);\n if (isDebuggable)\n analytics.getLogger().setLogLevel(LogLevel.VERBOSE);\n gaTracker = analytics.newTracker(ApiObjects.analytics\n .get(\"property_id\"));\n gaTracker.enableAdvertisingIdCollection(true);\n gaTracker.setSessionTimeout(-1);\n return gaTracker;\n }\n\n public static boolean isDebuggable() {\n return isDebuggable;\n }\n\n @Override\n public void onCreate() {\n OneSheeldSdk.init(this);\n context = getApplicationContext();\n setAppPreferences(getSharedPreferences(APP_PREF_NAME, MODE_PRIVATE));\n appFont = Typeface.createFromAsset(getAssets(), \"Roboto-Light.ttf\");\n parseSocialKeys();\n initTaskerPins();\n isDebuggable = (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));\n if (isDebuggable() && !FirebaseApp.getApps(this).isEmpty())\n FirebaseMessaging.getInstance().subscribeToTopic(\"dev\");\n OneSheeldSdk.setDebugging(isDebuggable);\n connectionTime = 0;\n AppShields.getInstance().init(getRememberedShields());\n initCrashlyticsAndUncaughtThreadHandler();\n detectIfLocatedInTheUs();\n super.onCreate();\n }\n\n private void initCrashlyticsAndUncaughtThreadHandler() {\n Thread.UncaughtExceptionHandler myHandler = new Thread.UncaughtExceptionHandler() {\n\n @Override\n public void uncaughtException(Thread arg0, final Throwable arg1) {\n arg1.printStackTrace();\n ArduinoConnectivityPopup.isOpened = false;\n MainActivity.thisInstance.moveTaskToBack(true);\n\n Enumeration<String> enumKey = getRunningShields().keys();\n while (enumKey.hasMoreElements()) {\n String key = enumKey.nextElement();\n getRunningShields().get(key).resetThis();\n getRunningShields().remove(key);\n }\n OneSheeldSdk.getManager().disconnectAll();\n if (MainActivity.thisInstance != null)\n MainActivity.thisInstance.stopService();\n Intent in = MainActivity.thisInstance != null ? new Intent(MainActivity.thisInstance.getIntent()) : new Intent();\n PendingIntent intent = PendingIntent\n .getActivity(getBaseContext(), 0, in,\n MainActivity.thisInstance != null ? MainActivity.thisInstance.getIntent().getFlags() : 0);\n\n AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n mgr.setExact(AlarmManager.RTC, System.currentTimeMillis() + 1000,\n intent);\n } else {\n mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,\n intent);\n }\n setTutShownTimes(\n getTutShownTimes() + 1);\n android.os.Process.killProcess(android.os.Process.myPid());\n }\n };\n Thread.setDefaultUncaughtExceptionHandler(myHandler);\n try {\n Fabric.with(this, new Crashlytics());\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @SuppressLint(\"UseSparseArrays\")\n public void initTaskerPins() {\n ArduinoPin[] pins = ArduinoPin.values();\n taskerPinsStatus = new SparseArray<Boolean>(pins.length);\n for (ArduinoPin pin : pins) {\n taskerPinsStatus.put(pin.microHardwarePin, false);\n }\n }\n\n private void parseSocialKeys() {\n String metaData = \"\";\n try {\n metaData = loadData(\"dev_meta_data.json\");\n } catch (Exception e) {\n try {\n metaData = loadData(\"meta_data.json\");\n } catch (Exception e1) {\n }\n }\n try {\n JSONObject socialKeysObject = new JSONObject(metaData);\n JSONObject facebook = new JSONObject();\n JSONObject twitter = new JSONObject();\n JSONObject foursquare = new JSONObject();\n JSONObject analytics = new JSONObject();\n if (socialKeysObject.has(\"facebook\")) {\n facebook = socialKeysObject.getJSONObject(\"facebook\");\n if (facebook.has(\"app_id\"))\n ApiObjects.facebook.add(\"app_id\",\n facebook.getString(\"app_id\"));\n }\n if (socialKeysObject.has(\"twitter\")) {\n twitter = socialKeysObject.getJSONObject(\"twitter\");\n if (twitter.has(\"consumer_key\")\n && twitter.has(\"consumer_secret\")) {\n ApiObjects.twitter.add(\"consumer_key\",\n twitter.getString(\"consumer_key\"));\n ApiObjects.twitter.add(\"consumer_secret\",\n twitter.getString(\"consumer_secret\"));\n }\n }\n if (socialKeysObject.has(\"foursquare\")) {\n foursquare = socialKeysObject.getJSONObject(\"foursquare\");\n if (foursquare.has(\"client_key\")\n && foursquare.has(\"client_secret\")) {\n ApiObjects.foursquare.add(\"client_key\",\n foursquare.getString(\"client_key\"));\n ApiObjects.foursquare.add(\"client_secret\",\n foursquare.getString(\"client_secret\"));\n }\n }\n if (socialKeysObject.has(\"analytics\")) {\n analytics = socialKeysObject.getJSONObject(\"analytics\");\n if (analytics.has(\"property_id\"))\n ApiObjects.analytics.add(\"property_id\",\n analytics.getString(\"property_id\"));\n }\n } catch (JSONException e) {\n }\n }\n\n public String loadData(String inFile) throws IOException {\n String tContents = \"\";\n InputStream stream = getAssets().open(inFile);\n int size = stream.available();\n byte[] buffer = new byte[size];\n stream.read(buffer);\n stream.close();\n tContents = new String(buffer);\n return tContents;\n }\n\n public SharedPreferences getAppPreferences() {\n return appPreferences;\n }\n\n public void setAppPreferences(SharedPreferences appPreferences) {\n this.appPreferences = appPreferences;\n }\n\n public String getLastConnectedDevice() {\n return appPreferences.getString(LAST_DEVICE, null);\n }\n\n public void setLastConnectedDevice(String lastConnectedDevice) {\n appPreferences.edit().putString(LAST_DEVICE, lastConnectedDevice)\n .commit();\n }\n\n public int getMajorVersion() {\n return appPreferences.getInt(MAJOR_VERSION, -1);\n }\n\n public void setMajorVersion(int majorVersion) {\n appPreferences.edit().putInt(MAJOR_VERSION, majorVersion).commit();\n }\n\n public int getMinorVersion() {\n return appPreferences.getInt(MINOR_VERSION, -1);\n }\n\n public void setMinorVersion(int minorVersion) {\n appPreferences.edit().putInt(MINOR_VERSION, minorVersion).commit();\n }\n\n public void setVersionWebResult(String json) {\n appPreferences.edit().putString(VERSION_WEB_RESULT, json).commit();\n }\n\n public String getVersionWebResult() {\n return appPreferences.getString(VERSION_WEB_RESULT, null);\n }\n\n public void setBuzzerSound(String uri) {\n appPreferences.edit().putString(BUZZER_SOUND_KEY, uri).commit();\n }\n\n public String getBuzzerSound() {\n return appPreferences.getString(BUZZER_SOUND_KEY, null);\n }\n\n public void setTutShownTimes(int times) {\n appPreferences.edit().putInt(TUTORIAL_SHOWN_TIME, times).commit();\n }\n\n public int getTutShownTimes() {\n return appPreferences.getInt(TUTORIAL_SHOWN_TIME, 0);\n }\n\n public void setTaskerConditionPin(int pin) {\n appPreferences.edit().putInt(TASKER_CONDITION_PIN, pin).commit();\n }\n\n public int getTaskerConditionPin() {\n return appPreferences.getInt(TASKER_CONDITION_PIN, -1);\n }\n\n public void setTaskerConditionStatus(boolean flag) {\n appPreferences.edit().putBoolean(TASKER_CONDITION_STATUS, flag)\n .commit();\n }\n\n public boolean getTaskConditionStatus() {\n return appPreferences.getBoolean(TASKER_CONDITION_STATUS, true);\n }\n// public void setCameraCapturing(boolean flag) {\n// appPreferences.edit().putBoolean(CAMERA_CAPTURING, flag)\n// .commit();\n// }\n//\n// public boolean isCameraCapturing() {\n// return appPreferences.getBoolean(CAMERA_CAPTURING, false);\n// }\n\n public void setShownTutAgain(boolean flag) {\n appPreferences.edit().putBoolean(SHOWTUTORIALS_AGAIN, !flag).commit();\n }\n\n public boolean getShowTutAgain() {\n return appPreferences.getBoolean(SHOWTUTORIALS_AGAIN, true);\n }\n\n public void setRememberedShields(String shields) {\n appPreferences.edit().putString(REMEMBER_SHIELDS, shields).commit();\n Toast.makeText(this, getString(shields == null || shields.trim().length() == 0 ? R.string.general_toasts_shields_selection_has_been_cleared_toast : R.string.general_toasts_shields_selection_has_been_saved_toast), Toast.LENGTH_SHORT).show();\n }\n\n public String getRememberedShields() {\n return appPreferences.getString(REMEMBER_SHIELDS, null);\n }\n\n public Hashtable<String, ControllerParent<?>> getRunningShields() {\n return runningSheelds;\n }\n\n public void setRunningSheelds(\n Hashtable<String, ControllerParent<?>> runningSheelds) {\n this.runningSheelds = runningSheelds;\n }\n\n public boolean getIsDemoMode() {\n return isDemoMode;\n }\n\n public void setIsDemoMode(boolean isDemoMode) {\n OneSheeldApplication.isDemoMode = isDemoMode;\n }\n\n public OneSheeldDevice getConnectedDevice() {\n return connectedDevice;\n }\n\n public void setConnectedDevice(OneSheeldDevice connectedDevice) {\n// if (this.connectedDevice != null) {\n// while (isConnectedToBluetooth())\n// this.connectedDevice.disconnect();\n// }\n this.connectedDevice = connectedDevice;\n }\n\n public boolean isConnectedToBluetooth() {\n return connectedDevice != null && connectedDevice.isConnected();\n }\n\n public static int getNotificationIcon() {\n boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);\n return useWhiteIcon ? R.drawable.notification_icon : R.drawable.white_ee_icon;\n }\n\n private void detectIfLocatedInTheUs() {\n if (ConnectionDetector.isConnectingToInternet(this)) {\n HttpRequest.getInstance().get(\"http://ip-api.com/json/?fields=3\", new JsonHttpResponseHandler() {\n @Override\n public void onSuccess(int statusCode, Header[] headers, JSONObject response) {\n if (response != null) {\n if (response.has(\"countryCode\")) try {\n isLocatedInTheUs = response.getString(\"countryCode\").toLowerCase().equals(\"us\");\n } catch (JSONException e) {\n }\n }\n }\n });\n }\n }\n\n public boolean isLocatedInTheUs(){\n return isLocatedInTheUs;\n }\n}", "public enum UIShield {\n LED_SHIELD((byte) 0x02, R.string.led_shield_name, 0xff03d203, R.drawable.shields_list_led_symbol, false, LedShield.class, LedFragment.class),\n NOTIFICATION_SHIELD((byte) 0x06, R.string.notifications_shield_name, 0xffd4d903, R.drawable.shields_list_notifications_symbol, false, NotificationShield.class, NotificationFragment.class),\n SEVENSEGMENT_SHIELD((byte) 0x07, R.string.seven_segment_shield_name, 0xffe28203, R.drawable.shields_list_seven_segment_symbol, false, SevenSegmentShield.class, SevenSegmentFragment.class),\n BUZZER_SHIELD((byte) 0x08, R.string.buzzer_shield_name, 0xffe93f03, R.drawable.shields_list_buzzer_symbol, false, SpeakerShield.class, BuzzerFragment.class),\n MIC_SHIELD((byte) 0x18, R.string.mic_shield_name, 0xff0362c0, R.drawable.shields_list_mic_symbol, false, MicShield.class, MicFragment.class, 1),\n KEYPAD_SHIELD((byte) 0x09, R.string.keypad_shield_name, 0xff03c0ae, R.drawable.shields_list_keypad_symbol, false, KeypadShield.class, KeypadFragment.class),\n SLIDER_SHIELD((byte) 0x01, R.string.slider_shield_name, 0xffc0034c, R.drawable.shields_list_slider_symbol, false, SliderShield.class, SliderFragment.class),\n LCD_SHIELD((byte) 0x17, R.string.lcd_shield_name, 0xff99bd03, R.drawable.shields_list_lcd_symbol, false, LcdShield.class, LcdFragment.class, true),\n MAGNETOMETER_SHIELD((byte) 0x0A, R.string.magnetometer_shield_name, 0xff40039f, R.drawable.shields_list_magnetometer_symbol, false, MagnetometerShield.class, MagnetometerFragment.class, 1),\n PUSHBUTTON_SHIELD((byte) 0x03, R.string.push_button_shield_name, 0xffb97547, R.drawable.shields_list_push_button_symbol, false, PushButtonShield.class, PushButtonFragment.class),\n TOGGLEBUTTON_SHIELD((byte) 0x04, R.string.toggle_button_shield_name, 0xffc0039d, R.drawable.shields_list_push_button_symbol, false, ToggleButtonShield.class, ToggleButtonFragment.class),\n ACCELEROMETER_SHIELD((byte) 0x0B, R.string.accelerometer_shield_name, 0xff266a5d, R.drawable.shields_list_accelerometer_symbol, false, AccelerometerShield.class, AccelerometerFragment.class, 1),\n FACEBOOK_SHIELD((byte) 0x19, R.string.facebook_shield_name, 0xff039dc0, R.drawable.shields_list_facebook_symbol, false, FacebookShield.class, FacebookFragment.class, 1),\n TWITTER_SHIELD((byte) 0x1A, R.string.twitter_shield_name, 0xffa14c4c, R.drawable.shields_list_twitter_symbol, false, TwitterShield.class, TwitterFragment.class, 1),\n GAMEDPAD_SHIELD((byte) 0x0C, R.string.game_pad_shield_name, 0xff658f08, R.drawable.shields_list_gamepad_symbol, false, GamepadShield.class, GamepadFragment.class),\n FOURSQUARE_SHIELD((byte) 0x1B, R.string.foursquare_shield_name, 0xff061179, R.drawable.shields_list_foursquare_symbol, false, FoursquareShield.class, FoursquareFragment.class),\n GPS_SHIELD((byte) 0x1C, R.string.gps_shield_name, 0xffa10b07, R.drawable.shields_list_gps_symbol, false, GpsShield.class, GpsFragment.class, 1),\n SMS_SHIELD((byte) 0x0D, R.string.sms_shield_name, 0xffdb7f40, R.drawable.shields_list_sms_symbol, false, SmsShield.class, SmsFragment.class, 1),\n MUSICPLAYER_SHIELD((byte) 0x1D, R.string.music_player_shield_name, 0xffb950e9, R.drawable.shields_list_musicplayer_symbol, false, MusicShield.class, MusicPlayerFragment.class, 1),\n GYROSCOPE_SHIELD((byte) 0x0E, R.string.gyroscope_shield_name, 0xff4c84e9, R.drawable.shields_list_gyroscope_symbol, false, GyroscopeShield.class, GyroscopeFragment.class, 1),\n SKYPE_SHIELD((byte) 0x1F, R.string.skype_shield_name, 0xff08c473, R.drawable.shields_list_skype_symbol, false, SkypeShield.class, SkypeFragment.class),\n PROXIMITY_SHIELD((byte) 0x13, R.string.proximity_shield_name, 0xff543c8d, R.drawable.shields_list_proximity_symbol, false, ProximityShield.class, ProximityFragment.class, 1),\n GRAVITY_SHIELD((byte) 0x14, R.string.gravity_shield_name, 0xffd95342, R.drawable.shields_list_gravity_symbol, false, GravityShield.class, GravityFragment.class, 1),\n ORIENTATION_SHIELD((byte) 0x0F, R.string.orientation_shield_name, 0xff58844f, R.drawable.shields_list_orientation_symbol, false, OrientationShield.class, OrientationFragment.class, 1),\n LIGHT_SHIELD((byte) 0x10, R.string.light_shield_name, 0xff8b268d, R.drawable.shields_list_light_sensor_symbol, false, LightShield.class, LightFragment.class, 1),\n PRESSURE_SHIELD((byte) 0x11, R.string.pressure_shield_name, 0xff67584d, R.drawable.shields_list_pressure_symbol, false, PressureShield.class, PressureFragment.class, 1),\n TEMPERATURE_SHIELD((byte) 0x12, R.string.temperature_shield_name, 0xff999f45, R.drawable.shields_list_temperature_symbol, false, TemperatureShield.class, TemperatureFragment.class, 1),\n CAMERA_SHIELD((byte) 0x15, R.string.camera_shield_name, 0xff6d0347, R.drawable.shields_list_camera_symbol, false, CameraShield.class, CameraFragment.class, 1),\n PHONE_SHIELD((byte) 0x20, R.string.phone_shield_name, 0xffe9bd03, R.drawable.shields_list_phone_symbol, false, PhoneShield.class, PhoneFragment.class, 1),\n EMAIL_SHIELD((byte) 0x1E, R.string.email_shield_name, 0xff114540, R.drawable.shields_list_email_symbol, false, EmailShield.class, EmailFragment.class, 1),\n CLOCK_SHIELD((byte) 0x21, R.string.clock_shield_name, 0xffc45527, R.drawable.shields_list_clock_symbol, false, ClockShield.class, ClockFragment.class),\n KEYBOARD_SHIELD((byte) 0x22, R.string.keyboard_shield_name, 0xffde1f26, R.drawable.shields_list_keyboard_symbol, false, KeyboardShield.class, KeyboardFragment.class),\n TEXT_TO_SPEECH_SHIELD((byte) 0x23, R.string.text_to_speech_shield_name, 0xffde1f26, R.drawable.shields_list_tts_symbol, false, TextToSpeechShield.class, TextToSpeechFragment.class),\n SPEECH_RECOGNIZER_SHIELD((byte) 0x24, R.string.voice_recognizer_shield_name, 0xffde1f26, R.drawable.shields_list_voice_recognition_symbol, false, SpeechRecognitionShield.class, SpeechRecognitionFragment.class, 1),\n DATA_LOGGER((byte) 0x25, R.string.data_logger_shield_name, 0xffde1f26, R.drawable.shields_list_data_logger_symbol, false, DataLoggerShield.class, DataLoggerFragment.class, 1),\n TERMINAL_SHIELD((byte) 0x26, R.string.terminal_shield_name, 0xffde1f26, R.drawable.shields_list_terminal_symbol, false, TerminalShield.class, TerminalFragment.class),\n TASKER_SHIELD((byte) 0x0, R.string.tasker_shield_name, 0xff0b4c8d, R.drawable.shields_list_flashlight_symbol, false, TaskerShield.class, EmptyShieldFragment.class, false),\n PATTERN_SHIELD((byte) 0x27, R.string.pattern_shield_name, 0xffde1f26, R.drawable.shields_list_pattern_symbol, false, PatternShield.class, PatternFragment.class),\n INTERNET_SHIELD((byte) 0x29, R.string.internet_shield_name, 0xffde1f26, R.drawable.shields_list_internet_symbol, false, InternetShield.class, InternetFragment.class, 1),\n NFC_SHIELD((byte) 0x16, R.string.nfc_shield_name, 0xff03d203, R.drawable.shields_list_nfc_symbol, false, NfcShield.class, NfcFragment.class, 1),\n GLCD_SHIELD((byte) 0x28, R.string.glcd_shield_name, 0xff03d203, R.drawable.shields_list_glcd_symbol, false, GlcdShield.class, GlcdFragment.class),\n COLOR_DETECTION_SHIELD((byte) 0x05, R.string.color_detector_shield_name, 0xffde1f26, R.drawable.shields_list_color_detector_symbol, false, ColorDetectionShield.class, ColorDetectionFragment.class, 1),\n VIBRATION_SHIELD((byte) 0x2A, R.string.vibration_shield_name, 0xffde1f26, R.drawable.shields_list_vibration_symbol, false, VibrationShield.class, VibrationFragment.class, 1),\n FACE_DETECTION((byte) 0x2D, R.string.face_detection_shield_name, 0xff0b4c8d, R.drawable.shields_list_face_detection_symbol, false, FaceDetectionShield.class, FaceDetectionFragment.class, 1);\n public static int[] colors = new int[]{0xff03d203, 0xffd4d903,\n 0xffe28203, 0xffe93f03, 0xff0362c0, 0xff03c0ae, 0xffc0034c,\n 0xff99bd03, 0xff40039f, 0xffb97547, 0xffc0039d, 0xff266a5d,\n 0xff039dc0, 0xffa14c4c, 0xff658f08, 0xff061179, 0xffa10b07,\n 0xffdb7f40, 0xffb950e9, 0xff4c84e9, 0xff0b4c8d, 0xff08c473,\n 0xff543c8d, 0xffd95342, 0xff58844f, 0xff8b268d, 0xff67584d,\n 0xff999f45, 0xff6d0347, 0xffe9bd03, 0xff127303, 0xff08bbb2,\n 0xff5a0303, 0xff988564, 0xff114540, 0xffc45527, 0xffde1f26,\n 0xff142218, 0xffc9a302, 0xffa57378, 0xff3354af, 0xff282742,\n 0xff381616, 0xff0b4c8d};\n public static UIShield shieldsActivitySelection;\n public static boolean isConnected = false;\n private byte id;\n private int shieldNameStringResource;\n private int itemBackgroundColor;\n private int symbolId;\n private boolean mainActivitySelection;\n private boolean isReleasable = true;\n private int isInvalidatable = 0;\n private Class<? extends ControllerParent<?>> shieldType;\n private Class<? extends ShieldFragmentParent<?>> shieldFragment;\n private int position = 0;\n\n UIShield(byte id, int shieldNameStringResource, int mainImageStripId, int symbolId,\n boolean mainActivitySelection,\n Class<? extends ControllerParent<?>> shieldType, Class<? extends ShieldFragmentParent<?>> shieldFragment) {\n this.id = id;\n this.shieldNameStringResource = shieldNameStringResource;\n this.itemBackgroundColor = mainImageStripId;\n this.symbolId = symbolId;\n this.mainActivitySelection = mainActivitySelection;\n this.shieldType = shieldType;\n this.shieldFragment = shieldFragment;\n }\n\n UIShield(byte id, int shieldNameStringResource, int mainImageStripId, int symbolId,\n boolean mainActivitySelection,\n Class<? extends ControllerParent<?>> shieldType, Class<? extends ShieldFragmentParent<?>> shieldFragment, int isInvalidatable) {\n this.id = id;\n this.shieldNameStringResource = shieldNameStringResource;\n this.itemBackgroundColor = mainImageStripId;\n this.symbolId = symbolId;\n this.mainActivitySelection = mainActivitySelection;\n this.shieldType = shieldType;\n this.shieldFragment = shieldFragment;\n this.isInvalidatable = isInvalidatable;\n }\n\n UIShield(byte id, int shieldNameStringResource, int mainImageStripId, int symbolId,\n boolean mainActivitySelection,\n Class<? extends ControllerParent<?>> shieldType, Class<? extends ShieldFragmentParent<?>> shieldFragment,\n boolean isReleasable) {\n this.id = id;\n this.shieldNameStringResource = shieldNameStringResource;\n this.itemBackgroundColor = mainImageStripId;\n this.symbolId = symbolId;\n this.mainActivitySelection = mainActivitySelection;\n this.shieldType = shieldType;\n this.shieldFragment = shieldFragment;\n this.isReleasable = isReleasable;\n }\n\n public static UIShield getShieldsActivitySelection() {\n return shieldsActivitySelection;\n }\n\n public static void setConnected(boolean isConnected) {\n UIShield.isConnected = isConnected;\n }\n\n public static synchronized List<UIShield> valuesFiltered() {\n UIShield[] vals = values();\n List<UIShield> valsFiltered = new ArrayList<UIShield>();\n for (int i = 0; i < vals.length; i++) {\n UIShield cur = vals[i];\n if (cur.isReleasable) {\n cur.position = valsFiltered.size();\n valsFiltered.add(cur);\n }\n }\n Collections.sort(valsFiltered, new Comparator<UIShield>() {\n\n @Override\n public int compare(UIShield lhs, UIShield rhs) {\n return lhs.getName().compareToIgnoreCase(rhs.getName());\n }\n });\n vals = null;\n final ArrayList<UIShield> ret = new ArrayList<UIShield>();\n for (UIShield uiShield : valsFiltered) {\n uiShield.itemBackgroundColor = colors[ret.size()];\n ret.add(uiShield);\n }\n valsFiltered.clear();\n valsFiltered = null;\n return ret;\n }\n\n public String getName() {\n return OneSheeldApplication.getContext().getString(shieldNameStringResource);\n }\n\n public byte getId() {\n return id;\n }\n\n public int getItemBackgroundColor() {\n return itemBackgroundColor;\n }\n\n public int getSymbolId() {\n return symbolId;\n }\n\n public boolean isMainActivitySelection() {\n return mainActivitySelection;\n }\n\n public int getIsInvalidatable() {\n return isInvalidatable;\n }\n\n public int getPosition() {\n return position;\n }\n\n public Class<? extends ControllerParent<?>> getShieldType() {\n return shieldType;\n }\n\n public Class<? extends ShieldFragmentParent<?>> getShieldFragment() {\n return shieldFragment;\n }\n\n public boolean isReleasable() {\n return isReleasable;\n }\n}", "public class ArduinoConnectivityPopup extends Dialog {\n private Activity activity;\n public static ArduinoConnectivityPopup thisInstance;\n private float scale;\n private boolean isConnecting = false;\n private Hashtable<String, OneSheeldDevice> foundDevicesTable;\n public static String EXTRA_DEVICE_NAME = \"device_name\";\n public static final String IS_BUY_TEXT_ENABLED_SP = \"com.integreight.onesheeld.IS_BUY_TEXT_ENABLED_SP\";\n\n\n public ArduinoConnectivityPopup(Activity context) {\n super(context, android.R.style.Theme_Translucent_NoTitleBar);\n this.activity = context;\n scale = activity.getResources().getDisplayMetrics().density;\n foundDevicesTable = new Hashtable<>();\n thisInstance = this;\n }\n\n // Member fields\n private RelativeLayout deviceListCont;\n private LinearLayout devicesList;\n private ProgressBar loading, smallLoading;\n private Button scanOrTryAgain;\n private OneSheeldTextView statusText;\n private OneSheeldTextView buy1SheeldBoardTextView;\n private OneSheeldButton skipScan;\n private RelativeLayout transactionSlogan;\n public static boolean isOpened = false, backPressed = false;\n private boolean isScanningFinishedManually = false;\n\n @Override\n public void onBackPressed() {\n if (OneSheeldSdk.getManager().isScanning()) {\n isScanningFinishedManually = true;\n OneSheeldSdk.getManager().cancelScanning();\n setScanButtonReady();\n } else if (OneSheeldSdk.getManager().isConnecting()) {\n isConnecting = false;\n OneSheeldSdk.getManager().cancelConnecting();\n setDevicesListReady();\n changeSlogan(\n activity.getResources()\n .getString(R.string.connectivity_popup_select_your_device), COLOR.YELLOW);\n findViewById(R.id.skip_scan).setVisibility(View.VISIBLE);\n } else if (scanOrTryAgain.getVisibility() != View.VISIBLE\n || !scanOrTryAgain\n .getText()\n .toString()\n .equalsIgnoreCase(\n activity.getResources()\n .getString(R.string.connectivity_popup_scan_button)))\n setScanButtonReady();\n else {\n ((MainActivity) activity).finishManually();\n dismiss();\n cancel();\n }\n backPressed = true;\n // super.onBackPressed();\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n Window window = getWindow();\n window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);\n window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);\n window.setStatusBarColor(Color.parseColor(\"#CC000000\"));\n }\n setContentView(R.layout.initialization_view);\n setCancelable(false);\n ((OneSheeldApplication)activity.getApplication()).setIsDemoMode(false);\n deviceListCont = (RelativeLayout) findViewById(R.id.devicesListContainer);\n loading = (ProgressBar) findViewById(R.id.progress);\n smallLoading = (ProgressBar) findViewById(R.id.small_progress);\n scanOrTryAgain = (Button) findViewById(R.id.scanOrTryAgain);\n statusText = (OneSheeldTextView) findViewById(R.id.statusText);\n skipScan = (OneSheeldButton) findViewById(R.id.skip_scan);\n transactionSlogan = (RelativeLayout) findViewById(R.id.transactionSlogan);\n devicesList = (LinearLayout) findViewById(R.id.devicesList);\n buy1SheeldBoardTextView = (OneSheeldTextView) findViewById(R.id.buy_1sheeld_board_text_view);\n buy1SheeldBoardTextView.setMovementMethod(LinkMovementMethod.getInstance());\n tempHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n buy1SheeldBoardTextView.setText(((OneSheeldApplication) activity.getApplication()).isLocatedInTheUs()?\n R.string.connectivity_popup_dont_have_the_board_get_it_now_US:\n R.string.connectivity_popup_dont_have_the_board_get_it_now);\n }\n },1000);\n URLSpanNoUnderline.stripUnderlines(buy1SheeldBoardTextView);\n setScanButtonReady();\n getWindow().setBackgroundDrawable(new ColorDrawable(0));\n setOnCancelListener(new OnCancelListener() {\n\n @Override\n public void onCancel(DialogInterface dialog) {\n isOpened = false;\n // Make sure we're not doing discovery anymore\n if (OneSheeldSdk.getManager().isScanning()) {\n isScanningFinishedManually = true;\n OneSheeldSdk.getManager().cancelScanning();\n }\n OneSheeldSdk.getManager().removeConnectionCallback(connectionCallback);\n OneSheeldSdk.getManager().removeErrorCallback(errorCallback);\n OneSheeldSdk.getManager().removeScanningCallback(scanningCallback);\n // Unregister broadcast listeners\n try {\n activity.unregisterReceiver(mReceiver);\n } catch (Exception e) {\n Log.e(\"TAG\", \"Exception\", e);\n }\n }\n });\n skipScan.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n ((OneSheeldApplication) activity.getApplication()).setIsDemoMode(true);\n ArduinoConnectivityPopup.isOpened = false;\n if (OneSheeldSdk.getManager().isScanning()) {\n isScanningFinishedManually = true;\n OneSheeldSdk.getManager().cancelScanning();\n setScanButtonReady();\n }\n ArduinoConnectivityPopup.thisInstance.cancel();\n ((ViewGroup) activity.findViewById(R.id.cancelConnection)).getChildAt(1).setBackgroundResource(R.drawable.scan_button);\n }\n });\n ((PullToRefreshScrollView) findViewById(R.id.scrollingDevices))\n .setOnRefreshListener(new OnRefreshListener<ScrollView>() {\n\n @Override\n public void onRefresh(\n PullToRefreshBase<ScrollView> refreshView) {\n ((PullToRefreshScrollView) findViewById(R.id.scrollingDevices))\n .onRefreshComplete();\n if (OneSheeldSdk.getManager().isScanning()) {\n isScanningFinishedManually = true;\n OneSheeldSdk.getManager().cancelScanning();\n }\n try {\n activity.unregisterReceiver(mReceiver);\n } catch (Exception e) {\n Log.e(\"TAG\", \"Exception\", e);\n }\n if (BluetoothAdapter.getDefaultAdapter()!=null &&!BluetoothAdapter.getDefaultAdapter().isEnabled()) {\n ((MainActivity) activity)\n .setOnConnectToBluetooth(new onConnectedToBluetooth() {\n\n @Override\n public void onConnect() {\n addingDevicesHandler\n .post(new Runnable() {\n\n @Override\n public void run() {\n backPressed = false;\n showProgress();\n changeSlogan(\n activity.getResources()\n .getString(\n R.string.connectivity_popup_searching) + \"......\",\n COLOR.RED);\n findViewById(R.id.skip_scan).setVisibility(View.INVISIBLE);\n scanDevices();\n doDiscovery();\n }\n });\n }\n });\n Intent enableIntent = new Intent(\n BluetoothAdapter.ACTION_REQUEST_ENABLE);\n activity.startActivityForResult(enableIntent,\n SheeldsList.REQUEST_ENABLE_BT);\n } else {\n showProgress();\n changeSlogan(\n activity.getResources().getString(\n R.string.connectivity_popup_searching) + \"......\", COLOR.RED);\n findViewById(R.id.skip_scan).setVisibility(View.INVISIBLE);\n scanDevices();\n doDiscovery();\n }\n }\n });\n HttpRequest.getInstance().get(\n OneSheeldApplication.FIRMWARE_UPGRADING_URL,\n new JsonHttpResponseHandler() {\n\n @Override\n public void onFinish() {\n super.onFinish();\n }\n\n @Override\n public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, String responseString, Throwable throwable) {\n\n ((OneSheeldApplication) activity.getApplication())\n .setMajorVersion(-1);\n ((OneSheeldApplication) activity.getApplication())\n .setMinorVersion(-1);\n super.onFailure(statusCode, headers, responseString, throwable);\n }\n\n @Override\n public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {\n try {\n System.err.println(response);\n ((OneSheeldApplication) activity.getApplication())\n .setMajorVersion(Integer.parseInt(response\n .getString(\"major\")));\n ((OneSheeldApplication) activity.getApplication())\n .setMinorVersion(Integer.parseInt(response\n .getString(\"minor\")));\n ((OneSheeldApplication) activity.getApplication())\n .setVersionWebResult(response.toString());\n } catch (NumberFormatException e) {\n // TODO Auto-generated catch block\n Log.e(\"TAG\", \"Exception\", e);\n } catch (JSONException e) {\n // TODO Auto-generated catch block\n Log.e(\"TAG\", \"Exception\", e);\n }\n super.onSuccess(statusCode, headers, response);\n }\n });\n OneSheeldSdk.getManager().addConnectionCallback(connectionCallback);\n OneSheeldSdk.getManager().addErrorCallback(errorCallback);\n OneSheeldSdk.getManager().addScanningCallback(scanningCallback);\n handleBuyLinkVisibility();\n super.onCreate(savedInstanceState);\n }\n\n @Override\n protected void onStart() {\n isOpened = true;\n super.onStart();\n }\n\n @Override\n protected void onStop() {\n isOpened = false;\n super.onStop();\n }\n\n private void setScanButtonReady() {\n changeSlogan(activity.getString(R.string.connectivity_popup_scan_for_1sheeld), COLOR.RED);\n findViewById(R.id.skip_scan).setVisibility(View.VISIBLE);\n isConnecting = false;\n deviceListCont.setVisibility(View.INVISIBLE);\n handleBuyLinkVisibility();\n loading.setVisibility(View.INVISIBLE);\n smallLoading.setVisibility(View.INVISIBLE);\n scanOrTryAgain.setVisibility(View.VISIBLE);\n scanOrTryAgain.setText(R.string.connectivity_popup_scan_button);\n scanOrTryAgain.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n if (BluetoothAdapter.getDefaultAdapter()!=null && !BluetoothAdapter.getDefaultAdapter().isEnabled()) {\n ((MainActivity) activity)\n .setOnConnectToBluetooth(new onConnectedToBluetooth() {\n\n @Override\n public void onConnect() {\n addingDevicesHandler.post(new Runnable() {\n\n @Override\n public void run() {\n backPressed = false;\n showProgress();\n changeSlogan(\n activity.getResources()\n .getString(\n R.string.connectivity_popup_searching) + \"......\",\n COLOR.RED);\n findViewById(R.id.skip_scan).setVisibility(View.INVISIBLE);\n scanDevices();\n doDiscovery();\n }\n });\n }\n });\n Intent enableIntent = new Intent(\n BluetoothAdapter.ACTION_REQUEST_ENABLE);\n activity.startActivityForResult(enableIntent,\n SheeldsList.REQUEST_ENABLE_BT);\n } else {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {\n backPressed = false;\n if (OneSheeldSdk.getManager().isScanning()) {\n isScanningFinishedManually = true;\n OneSheeldSdk.getManager().cancelScanning();\n }\n showProgress();\n changeSlogan(\n activity.getResources().getString(\n R.string.connectivity_popup_searching) + \"......\", COLOR.RED);\n findViewById(R.id.skip_scan).setVisibility(View.VISIBLE);\n scanDevices();\n doDiscovery();\n } else {\n if (((MainActivity) activity).checkForLocationPermission()) {\n backPressed = false;\n if (OneSheeldSdk.getManager().isScanning()) {\n isScanningFinishedManually = true;\n OneSheeldSdk.getManager().cancelScanning();\n }\n showProgress();\n changeSlogan(\n activity.getResources().getString(\n R.string.connectivity_popup_searching) + \"......\", COLOR.RED);\n findViewById(R.id.skip_scan).setVisibility(View.VISIBLE);\n scanDevices();\n doDiscovery();\n } else {\n ((MainActivity) activity)\n .setOnConnectToBluetooth(new onConnectedToBluetooth() {\n\n @Override\n public void onConnect() {\n addingDevicesHandler.post(new Runnable() {\n\n @Override\n public void run() {\n backPressed = false;\n showProgress();\n changeSlogan(\n activity.getResources()\n .getString(\n R.string.connectivity_popup_searching) + \"......\",\n COLOR.RED);\n findViewById(R.id.skip_scan).setVisibility(View.INVISIBLE);\n scanDevices();\n doDiscovery();\n }\n });\n }\n });\n ((MainActivity) activity).checkAndAskForLocationPermission();\n }\n }\n }\n }\n });\n }\n\n private void setRetryButtonReady(final String msg, final View.OnClickListener onClick) {\n loading.post(new Runnable() {\n @Override\n public void run() {\n\n isConnecting = false;\n if (backPressed == false) {\n deviceListCont.setVisibility(View.INVISIBLE);\n handleBuyLinkVisibility();\n loading.setVisibility(View.INVISIBLE);\n smallLoading.setVisibility(View.INVISIBLE);\n scanOrTryAgain.setVisibility(View.VISIBLE);\n changeSlogan(msg, COLOR.ORANGE);\n findViewById(R.id.skip_scan).setVisibility(View.VISIBLE);\n scanOrTryAgain.setText(R.string.connectivity_popup_try_again_button);\n }\n }\n });\n }\n\n private void setDevicesListReady() {\n loading.post(new Runnable() {\n @Override\n public void run() {\n deviceListCont.setVisibility(View.VISIBLE);\n handleBuyLinkVisibility();\n loading.setVisibility(View.INVISIBLE);\n smallLoading.setVisibility(View.INVISIBLE);\n scanOrTryAgain.setVisibility(View.INVISIBLE);\n }\n });\n }\n\n private void handleBuyLinkVisibility(){\n boolean isTheTextViewEnabled = true;\n try{\n isTheTextViewEnabled=((OneSheeldApplication)activity.getApplication()).getAppPreferences().getBoolean(IS_BUY_TEXT_ENABLED_SP, true);\n }catch (Exception ignored){\n ignored.printStackTrace();\n }\n if(deviceListCont.getVisibility()==View.INVISIBLE && !buy1SheeldBoardTextView.getText().equals(\"\") && isTheTextViewEnabled){\n buy1SheeldBoardTextView.setVisibility(View.VISIBLE);\n }\n else{\n buy1SheeldBoardTextView.setVisibility(View.INVISIBLE);\n }\n }\n\n private void showProgress() {\n loading.post(new Runnable() {\n @Override\n public void run() {\n deviceListCont.setVisibility(View.INVISIBLE);\n handleBuyLinkVisibility();\n loading.setVisibility(View.VISIBLE);\n smallLoading.setVisibility(View.INVISIBLE);\n scanOrTryAgain.setVisibility(View.INVISIBLE);\n }\n });\n }\n\n private void changeSlogan(final String text, final int color) {\n loading.post(new Runnable() {\n @Override\n public void run() {\n statusText.setText(text);\n transactionSlogan.setBackgroundColor(color);\n }\n });\n }\n\n Handler tempHandler = new Handler();\n\n\n private void scanDevices() {\n devicesList.removeAllViews();\n backPressed = false;\n foundDevicesTable = new Hashtable<>();\n IntentFilter filter = new IntentFilter();\n filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);\n activity.registerReceiver(mReceiver, filter);\n }\n\n OneSheeldConnectionCallback connectionCallback = new OneSheeldConnectionCallback() {\n @Override\n public void onConnectionRetry(OneSheeldDevice device, int retryCount) {\n super.onConnectionRetry(device, retryCount);\n }\n\n @Override\n public void onDisconnect(OneSheeldDevice device) {\n super.onDisconnect(device);\n ((OneSheeldApplication) activity.getApplication()).setConnectedDevice(null);\n if (isOpened) {\n isConnecting = false;\n setRetryButtonReady(\n activity.getResources()\n .getString(R.string.connectivity_popup_not_connected),\n new View.OnClickListener() {\n\n @Override\n public void onClick(View arg0) {\n scanDevices();\n }\n });\n }\n }\n\n @Override\n public void onConnect(OneSheeldDevice device) {\n super.onConnect(device);\n if (isOpened) {\n isConnecting = false;\n activity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n ((ViewGroup) activity.findViewById(R.id.cancelConnection)).getChildAt(1).setBackgroundResource(R.drawable.bluetooth_disconnect_button);\n }\n });\n cancel();\n }\n try{\n ((OneSheeldApplication)activity.getApplication()).getAppPreferences().edit().putBoolean(IS_BUY_TEXT_ENABLED_SP, false).apply();\n }\n catch (Exception ignored){\n ignored.printStackTrace();\n }\n\n }\n };\n OneSheeldScanningCallback scanningCallback = new OneSheeldScanningCallback() {\n @Override\n public void onScanStart() {\n super.onScanStart();\n addingDevicesHandler.post(new Runnable() {\n\n @Override\n public void run() {\n showProgress();\n changeSlogan(\n activity.getResources().getString(\n R.string.connectivity_popup_searching) + \"......\", COLOR.RED);\n findViewById(R.id.skip_scan).setVisibility(View.INVISIBLE);\n }\n });\n }\n\n @Override\n public void onDeviceFind(final OneSheeldDevice device) {\n super.onDeviceFind(device);\n addingDevicesHandler.post(new Runnable() {\n\n @Override\n public void run() {\n // Get the BluetoothDevice object from the Intent\n foundDevicesTable.put(device.getAddress(), device);\n addFoundDevice(\n device.getName(),\n device.getAddress(),\n device.isPaired());\n }\n });\n }\n\n @Override\n public void onScanFinish(List<OneSheeldDevice> foundDevices) {\n super.onScanFinish(foundDevices);\n if (!isScanningFinishedManually) {\n if (foundDevices.size() == 0) {\n loading.post(new Runnable() {\n\n @Override\n public void run() {\n // TODO Auto-generated method stub\n smallLoading.setVisibility(View.INVISIBLE);\n setRetryButtonReady(activity.getResources()\n .getString(R.string.connectivity_popup_no_devices_found),\n new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n scanDevices();\n }\n });\n }\n });\n } else {\n foundDevicesTable.clear();\n for(OneSheeldDevice device:foundDevices)\n {\n foundDevicesTable.put(device.getAddress(),device);\n }\n loading.post(new Runnable() {\n\n @Override\n public void run() {\n smallLoading.setVisibility(View.INVISIBLE);\n // devicesList.removeAllViews();\n for (int i = 0; i < devicesList.getChildCount(); i++) {\n OneSheeldTextView deviceView = (OneSheeldTextView) devicesList\n .getChildAt(i);\n OneSheeldDevice btDevice = foundDevicesTable\n .get(deviceView.getTag());\n if (btDevice != null) {\n if (btDevice.getName() != null\n && btDevice.getName()\n .toLowerCase()\n .contains(\"1sheeld\")) {\n deviceView\n .setText(foundDevicesTable\n .get(deviceView\n .getTag())\n .getName());\n } else {\n devicesList.removeView(deviceView);\n }\n foundDevicesTable.remove(deviceView\n .getTag());\n }\n }\n final Enumeration<String> enumKey = foundDevicesTable\n .keys();\n addingDevicesHandler\n .removeCallbacksAndMessages(null);\n while (enumKey.hasMoreElements()) {\n final String key = enumKey.nextElement();\n tempHandler.post(new Runnable() {\n\n @Override\n public void run() {\n OneSheeldDevice device = foundDevicesTable\n .get(key);\n if (device != null)\n addFoundDevice(\n device.getName() != null\n && device\n .getName()\n .length() > 0 ? device\n .getName()\n : device.getAddress(),\n key,\n device.isPaired());\n }\n });\n }\n foundDevicesTable.clear();\n if (devicesList.getChildCount() == 0) {\n setRetryButtonReady(activity.getResources()\n .getString(R.string.connectivity_popup_no_devices_found),\n new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n scanDevices();\n }\n });\n }\n }\n });\n }\n }\n isScanningFinishedManually = false;\n }\n };\n OneSheeldErrorCallback errorCallback = new OneSheeldErrorCallback() {\n @Override\n public void onError(OneSheeldDevice device, OneSheeldError error) {\n super.onError(device, error);\n if (isOpened) {\n\n if (error == OneSheeldError.BLUETOOTH_NOT_ENABLED) {\n ((MainActivity) activity)\n .setOnConnectToBluetooth(new onConnectedToBluetooth() {\n\n @Override\n public void onConnect() {\n addingDevicesHandler\n .post(new Runnable() {\n\n @Override\n public void run() {\n backPressed = false;\n showProgress();\n changeSlogan(\n activity.getResources()\n .getString(\n R.string.connectivity_popup_searching) + \"......\",\n COLOR.RED);\n findViewById(R.id.skip_scan).setVisibility(View.INVISIBLE);\n scanDevices();\n doDiscovery();\n }\n });\n }\n });\n Intent enableIntent = new Intent(\n BluetoothAdapter.ACTION_REQUEST_ENABLE);\n activity.startActivityForResult(enableIntent,\n SheeldsList.REQUEST_ENABLE_BT);\n } else {\n isConnecting = false;\n setRetryButtonReady(\n activity.getResources()\n .getString(R.string.connectivity_popup_not_connected),\n new View.OnClickListener() {\n\n @Override\n public void onClick(View arg0) {\n scanDevices();\n }\n });\n }\n }\n }\n };\n\n private void startService(String address, String name) {\n if (!isConnecting) {\n isConnecting = true;\n if (OneSheeldSdk.getManager().isScanning()){\n isScanningFinishedManually = true;\n OneSheeldSdk.getManager().cancelScanning();\n }\n\n // Get the device MAC address, which is the last 17 chars in\n // the\n // View\n showProgress();\n changeSlogan(\n activity.getResources().getString(R.string.connectivity_popup_connecting) + \"......\",\n COLOR.GREEN);\n findViewById(R.id.skip_scan).setVisibility(View.INVISIBLE);\n OneSheeldSdk.getManager().connect(new OneSheeldDevice(address, name));\n isConnecting = true;\n }\n }\n\n /**\n * Start device discover with the BluetoothAdapter\n */\n private synchronized void doDiscovery() {\n // If we're already discovering, stop it\n\n if (OneSheeldSdk.getManager().isScanning()) {\n isScanningFinishedManually = true;\n OneSheeldSdk.getManager().cancelScanning();\n }\n\n // Request discover from BluetoothAdapter\n OneSheeldSdk.getManager().scan();\n }\n\n private void addFoundDevice(String name1, final String address,\n boolean isPaired) {\n if (name1 == null)\n name1 = \"\";\n final String name = name1;\n if (name.trim().length() > 0\n && (name.toLowerCase().contains(\"1sheeld\") || address\n .equals(name))\n && devicesList.findViewWithTag(address) == null) {\n if (((OneSheeldApplication) activity.getApplication())\n .getLastConnectedDevice() != null\n && ((OneSheeldApplication) activity.getApplication())\n .getLastConnectedDevice().equals(address)) {\n startService(address, name);\n } else {\n OneSheeldTextView item = new OneSheeldTextView(activity, null);\n item.setLayoutParams(new LinearLayout.LayoutParams(\n LinearLayout.LayoutParams.WRAP_CONTENT,\n LinearLayout.LayoutParams.WRAP_CONTENT));\n item.setText(name);\n item.setTag(address);\n item.setGravity(Gravity.CENTER_VERTICAL);\n item.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);\n item.setTextColor(Color.WHITE);\n int pdng = (int) (8 * scale - .5f);\n item.setPadding(pdng, pdng, pdng, pdng);\n Drawable img = getContext()\n .getResources()\n .getDrawable(\n isPaired ? R.drawable.arduino_connectivity_activity_onesheeld_small_green_logo\n : R.drawable.arduino_connectivity_activity_onesheeld_small_logo);\n item.setCompoundDrawablesWithIntrinsicBounds(img, null, null,\n null);\n item.setBackgroundResource(R.drawable.devices_list_item_selector);\n item.setCompoundDrawablePadding(pdng);\n item.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n if (BluetoothAdapter.getDefaultAdapter() != null && BluetoothAdapter.getDefaultAdapter().isEnabled()) {\n backPressed = false;\n if (((Checkable) findViewById(R.id.doAutomaticConnectionToThisDeviceCheckBox))\n .isChecked())\n ((OneSheeldApplication) activity\n .getApplication())\n .setLastConnectedDevice(address);\n startService(address, name);\n } else {\n if (OneSheeldSdk.getManager().isScanning()) {\n isScanningFinishedManually = true;\n OneSheeldSdk.getManager().cancelScanning();\n }\n ((MainActivity) activity)\n .setOnConnectToBluetooth(new onConnectedToBluetooth() {\n\n @Override\n public void onConnect() {\n backPressed = false;\n ((OneSheeldApplication) activity.getApplication()).setIsDemoMode(false);\n if (((Checkable) findViewById(R.id.doAutomaticConnectionToThisDeviceCheckBox))\n .isChecked())\n ((OneSheeldApplication) activity\n .getApplication())\n .setLastConnectedDevice(address);\n startService(address, name);\n }\n });\n Intent enableIntent = new Intent(\n BluetoothAdapter.ACTION_REQUEST_ENABLE);\n activity.startActivityForResult(enableIntent,\n SheeldsList.REQUEST_ENABLE_BT);\n }\n }\n }\n\n );\n devicesList.addView(item);\n\n setDevicesListReady();\n\n changeSlogan(\n activity.getResources()\n\n .\n\n getString(\n R.string.connectivity_popup_select_your_device), COLOR\n\n .YELLOW);\n\n findViewById(R.id.skip_scan)\n\n .\n\n setVisibility(View.VISIBLE);\n\n smallLoading.setVisibility(View.VISIBLE);\n }\n }\n }\n\n // The BroadcastReceiver that listens for discovered devices and\n // changes the title when discovery is finished\n Handler addingDevicesHandler = new Handler();\n private final BroadcastReceiver mReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, final Intent intent) {\n String action = intent.getAction();\n\n // When discovery finds a device\n if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action))\n scanDevices();\n }\n };\n\n public interface onConnectedToBluetooth {\n void onConnect();\n }\n\n private final static class COLOR {\n public final static int RED = 0xff9B1201;\n public final static int YELLOW = 0xffE79401;\n public final static int GREEN = 0xff388813;\n public final static int ORANGE = 0xffE74D01;\n }\n}", "public class OneSheeldService extends Service {\n public static boolean isBound = false;\n SharedPreferences sharedPrefs;\n private BluetoothAdapter mBluetoothAdapter = null;\n private String deviceName;\n OneSheeldConnectionCallback connectionCallback = new OneSheeldConnectionCallback() {\n @Override\n public void onDisconnect(OneSheeldDevice device) {\n super.onDisconnect(device);\n stopSelf();\n }\n\n @Override\n public void onConnect(OneSheeldDevice device) {\n super.onConnect(device);\n showNotification();\n }\n };\n OneSheeldErrorCallback errorCallback=new OneSheeldErrorCallback() {\n @Override\n public void onError(OneSheeldDevice device, OneSheeldError error) {\n super.onError(device, error);\n stopSelf();\n }\n };\n\n OneSheeldApplication app;\n\n @Override\n public void onCreate() {\n // TODO Auto-generated method stub\n mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();\n app = (OneSheeldApplication) getApplication();\n sharedPrefs = this.getSharedPreferences(\"com.integreight.onesheeld\",\n Context.MODE_PRIVATE);\n isBound = false;\n super.onCreate();\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n // TODO Auto-generated method stub\n if (intent.getExtras() != null) {\n deviceName = intent.getExtras().getString(\n ArduinoConnectivityPopup.EXTRA_DEVICE_NAME);\n // Attempt to connect to the device\n OneSheeldSdk.getManager().addConnectionCallback(connectionCallback);\n OneSheeldSdk.getManager().addErrorCallback(errorCallback);\n }\n showNotification();\n WakeLocker.acquire(this);\n return START_NOT_STICKY;\n }\n\n @Override\n public IBinder onBind(Intent intent) {\n // TODO Auto-generated method stub\n isBound = true;\n // return mBinder;\n return null;\n }\n\n @Override\n public boolean onUnbind(Intent intent) {\n isBound = false;\n return super.onUnbind(intent);\n }\n\n @Override\n public void onDestroy() {\n // TODO Auto-generated method stub\n OneSheeldSdk.getManager().disconnectAll();\n hideNotifcation();\n isBound = false;\n WakeLocker.release();\n super.onDestroy();\n }\n\n private void showNotification() {\n NotificationCompat.Builder build = new NotificationCompat.Builder(this);\n build.setSmallIcon(OneSheeldApplication.getNotificationIcon());\n build.setContentText(getString(R.string.connection_notification_connected_to)+\": \" + deviceName);\n build.setContentTitle(getString(R.string.connection_notification_1sheeld_is_connected));\n build.setTicker(getString(R.string.connection_notification_1sheeld_is_connected));\n build.setWhen(System.currentTimeMillis());\n Intent notificationIntent = new Intent(this, MainActivity.class);\n notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP\n | Intent.FLAG_ACTIVITY_SINGLE_TOP);\n PendingIntent intent = PendingIntent.getActivity(this, 0,\n notificationIntent, 0);\n build.setContentIntent(intent);\n Notification notification = build.build();\n startForeground(1, notification);\n }\n\n private void hideNotifcation() {\n stopForeground(true);\n }\n\n}", "public class CameraShield extends ControllerParent<CameraShield> {\n public static final int CRASHED = 3;\n public final static int UNBIND_CAMERA_CAPTURE = 4, BIND_CAMERA_CAPTURE = 5, NEXT_CAPTURE = 14, SET_LAST_IMAGE_BUTTON = 17;\n private static final byte CAPTURE_METHOD_ID = (byte) 0x01;\n private static final byte FLASH_METHOD_ID = (byte) 0x02;\n private static final byte QUALITY_METHOD_ID = (byte) 0x04;\n private static final byte FRONT_CAPTURE = (byte) 0x03;\n private static String FLASH_MODE;\n private static int QUALITY_MODE = 0;\n private static String lastImageAbsoultePath = null;\n public Queue<CameraShield.CameraCapture> capturesQueue = new ConcurrentLinkedQueue<>();\n public boolean isBackPreview = true;\n CameraCapture capture;\n int numberOfFrames = 0;\n Handler UIHandler;\n private Messenger cameraBinder;\n private boolean isCameraBound;\n private boolean isCameraCapturing = false;\n private CameraEventHandler eventHandler;\n private boolean hasFrontCamera = false;\n private boolean isChangingPreview = false;\n private Messenger mMessenger = new Messenger(new Handler() {\n public void handleMessage(Message msg) {\n if (msg.what == CRASHED) {\n cameraBinder = null;\n isCameraBound = false;\n if (capturesQueue == null)\n capturesQueue = new ConcurrentLinkedQueue<>();\n bindService();\n } else if (msg.what == NEXT_CAPTURE) {\n if (msg.getData().getBoolean(\"takenSuccessfuly\")) {\n if (capturesQueue != null && !capturesQueue.isEmpty())\n capturesQueue.poll();\n }\n isCameraCapturing = false;\n checkQueue();\n } else if (msg.what == CameraHeadService.SET_CAMERA_PREVIEW_TYPE) {\n isBackPreview = msg.getData().getBoolean(\"isBack\");\n if (eventHandler != null)\n eventHandler.setOnCameraPreviewTypeChanged(isBackPreview);\n isChangingPreview = false;\n } else if (msg.what == SET_LAST_IMAGE_BUTTON) {\n lastImageAbsoultePath = msg.getData().getString(\"absolutePath\");\n CameraUtils.setLastCapturedImagePathFromOneSheeldFolder(lastImageAbsoultePath, activity);\n Log.d(\"LastImage\", lastImageAbsoultePath);\n File img = new File(lastImageAbsoultePath);\n if (img.exists() && eventHandler != null) {\n eventHandler.updatePreviewButton(lastImageAbsoultePath);\n }\n img = null;\n }\n super.handleMessage(msg);\n }\n\n\n });\n private ServiceConnection cameraServiceConnector = new ServiceConnection() {\n\n @Override\n public void onServiceConnected(ComponentName name, IBinder service) {\n isCameraCapturing = false;\n notifyHardwareOfShieldSelection();\n cameraBinder = new Messenger(service);\n Message msg = Message.obtain(null, BIND_CAMERA_CAPTURE);\n msg.replyTo = mMessenger;\n try {\n cameraBinder.send(msg);\n } catch (RemoteException e) {\n }\n isCameraBound = true;\n checkQueue();\n }\n\n @Override\n public void onServiceDisconnected(ComponentName name) {\n cameraBinder = null;\n isCameraBound = false;\n }\n\n };\n\n public CameraShield() {\n\n }\n\n public CameraShield(Activity activity, String tag) {\n super(activity, tag, true);\n }\n\n public static String getLastImageAbsoultePath() {\n return lastImageAbsoultePath;\n }\n\n @Override\n public ControllerParent<CameraShield> init(String tag) {\n UIHandler = new Handler();\n return super.init(tag, true);\n }\n\n void bindService() {\n getApplication().bindService(new Intent(getActivity(), CameraHeadService.class), cameraServiceConnector, Context.BIND_AUTO_CREATE);\n }\n\n @Override\n public ControllerParent<CameraShield> invalidate(\n com.integreight.onesheeld.shields.ControllerParent.SelectionAction selectionAction,\n boolean isToastable) {\n this.selectionAction = selectionAction;\n if (!checkCameraHardware(getApplication().getApplicationContext())) {\n if (selectionAction != null)\n selectionAction.onFailure();\n if (isToastable)\n activity.showToast(R.string.camera_camera_is_unavailable_maybe_its_used_by_another_application_toast);\n } else {\n addRequiredPremission(Manifest.permission.CAMERA);\n addRequiredPremission(Manifest.permission.WRITE_EXTERNAL_STORAGE);\n if (Build.VERSION.SDK_INT >= 16)\n addRequiredPremission(Manifest.permission.READ_EXTERNAL_STORAGE);\n if (checkForPermissions()) {\n if (!activity.canDrawOverApps()) {\n final AlertDialog.Builder builder = new AlertDialog.Builder(\n activity);\n builder.setMessage(\n R.string.camera_we_need_you_to_enable_the_draw_over_apps_permission_in_order_to_show_the_camera_preview_correctly)\n .setCancelable(false)\n .setPositiveButton(R.string.camera_validation_dialog_ok_button,\n new DialogInterface.OnClickListener() {\n public void onClick(final DialogInterface dialog,\n final int id) {\n activity.requestDrawOverApps();\n }\n })\n .setNegativeButton(R.string.camera_validation_dialog_later_button, new DialogInterface.OnClickListener() {\n public void onClick(final DialogInterface dialog,\n final int id) {\n dialog.cancel();\n activity.showToast(R.string.camera_please_enable_the_permission_to_be_able_to_select_this_shield_toast);\n }\n });\n final AlertDialog alert = builder.create();\n alert.show();\n if (this.selectionAction != null) {\n this.selectionAction.onFailure();\n }\n } else {\n if (selectionAction != null)\n selectionAction.onSuccess();\n hasFrontCamera = CameraUtils.checkFrontCamera(activity.getApplicationContext());\n bindService();\n UIHandler = new Handler();\n }\n } else {\n if (this.selectionAction != null) {\n this.selectionAction.onFailure();\n }\n }\n }\n return super.invalidate(selectionAction, isToastable);\n }\n\n public boolean isBackPreview() {\n return isBackPreview;\n }\n\n public boolean setCameraToPreview(boolean isBack) {\n if (!isBack && !CameraUtils.checkFrontCamera(getActivity().getApplicationContext()))\n return false;\n if (isChangingPreview)\n return false;\n isChangingPreview = true;\n Log.d(\"Acc\", isBack + \" **\");\n Message msg = Message.obtain(null, CameraHeadService.SET_CAMERA_PREVIEW_TYPE);\n msg.replyTo = mMessenger;\n Bundle b = new Bundle();\n b.putBoolean(\"isBack\", isBack);\n msg.setData(b);\n if (cameraBinder != null) {\n try {\n cameraBinder.send(msg);\n } catch (RemoteException e) {\n return false;\n }\n } else {\n bindService();\n }\n isBackPreview = isBack;\n return true;\n }\n\n private synchronized void checkQueue() {\n if (capturesQueue != null && !capturesQueue.isEmpty() && !isCameraCapturing) {\n if (isCameraBound) {\n capture = capturesQueue.peek();\n if (capture.isFront()) {\n if (hasFrontCamera)\n sendFrontCaptureImageIntent(capture);\n else {\n Toast.makeText(getActivity(), R.string.camera_your_device_doesnt_have_a_front_camera_toast, Toast.LENGTH_SHORT).show();\n capturesQueue.poll();\n }\n } else {\n sendCaptureImageIntent(capture);\n }\n } else bindService();\n }\n }\n\n /**\n * Check if this device has a camera\n */\n private synchronized boolean checkCameraHardware(Context context) {\n if (context.getPackageManager().hasSystemFeature(\n PackageManager.FEATURE_CAMERA)) {\n // this device has a camera\n return true;\n } else {\n // no camera on this device\n return false;\n }\n }\n\n public void setCameraEventHandler(CameraEventHandler eventHandler) {\n this.eventHandler = eventHandler;\n }\n\n public boolean showPreview() throws RemoteException {\n Message msg = Message.obtain(null, CameraHeadService.SHOW_PREVIEW);\n msg.replyTo = mMessenger;\n if (cameraBinder != null) {\n cameraBinder.send(msg);\n return true;\n } else {\n bindService();\n return false;\n }\n }\n\n public void invalidatePreview() throws RemoteException {\n Message msg = Message.obtain(null, CameraHeadService.INVALIDATE_PREVIEW);\n msg.replyTo = mMessenger;\n if (cameraBinder != null)\n cameraBinder.send(msg);\n else bindService();\n }\n\n public boolean hidePreview() throws RemoteException {\n Message msg = Message.obtain(null, CameraHeadService.HIDE_PREVIEW);\n msg.replyTo = mMessenger;\n if (cameraBinder != null) {\n cameraBinder.send(msg);\n return true;\n } else {\n return false;\n }\n }\n\n @Override\n public void onNewShieldFrameReceived(ShieldFrame frame) {\n\n if (frame.getShieldId() == UIShield.CAMERA_SHIELD.getId()) {\n switch (frame.getFunctionId()) {\n case QUALITY_METHOD_ID:\n byte quality_mode = frame.getArgument(0)[0];\n switch (quality_mode) {\n case 1:\n QUALITY_MODE = 40;\n break;\n case 2:\n QUALITY_MODE = 70;\n break;\n case 3:\n QUALITY_MODE = 100;\n break;\n\n default:\n break;\n }\n break;\n\n case FLASH_METHOD_ID:\n byte flash_mode = frame.getArgument(0)[0];\n switch (flash_mode) {\n case 0:\n FLASH_MODE = \"off\";\n break;\n case 1:\n FLASH_MODE = \"on\";\n break;\n case 2:\n FLASH_MODE = \"auto\";\n break;\n default:\n break;\n }\n break;\n\n case CAPTURE_METHOD_ID:\n\n numberOfFrames++;\n Log.d(\"Camera\", \"Frames number = \" + numberOfFrames);\n CameraCapture camCapture = new CameraCapture(FLASH_MODE, false,\n QUALITY_MODE, new Date().getTime());\n if (capturesQueue == null)\n capturesQueue = new ConcurrentLinkedQueue<>();\n capturesQueue.add(camCapture);\n checkQueue();\n break;\n case FRONT_CAPTURE:\n numberOfFrames++;\n Log.d(\"Camera\", \"Frames number front = \" + numberOfFrames);\n CameraCapture frontCamCapture = new CameraCapture(FLASH_MODE,\n true, QUALITY_MODE, new Date().getTime());\n if (capturesQueue == null)\n capturesQueue = new ConcurrentLinkedQueue<>();\n capturesQueue.add(frontCamCapture);\n checkQueue();\n break;\n\n default:\n break;\n }\n }\n\n }\n\n @Override\n public void reset() {\n Message msg = Message.obtain(null, UNBIND_CAMERA_CAPTURE);\n try {\n if (cameraBinder != null)\n cameraBinder.send(msg);\n } catch (RemoteException e) {\n }\n try {\n getApplication().unbindService(cameraServiceConnector);\n } catch (IllegalArgumentException e) {\n\n }\n capturesQueue = new ConcurrentLinkedQueue<>();\n isCameraBound = false;\n\n }\n\n @Override\n public void preConfigChange() {\n super.preConfigChange();\n }\n\n @Override\n public void postConfigChange() {\n super.postConfigChange();\n }\n\n private void sendCaptureImageIntent(CameraShield.CameraCapture camCapture) {\n if (camCapture != null) {\n if (isCameraBound) {\n isCameraCapturing = true;\n Bundle intent = new Bundle();\n intent.putString(\"FLASH\", camCapture.getFlash());\n intent.putInt(\"Quality_Mode\", camCapture.getQuality());\n Message msg = Message.obtain(null, CameraHeadService.CAPTURE_IMAGE);\n msg.setData(intent);\n try {\n cameraBinder.send(msg);\n } catch (RemoteException e) {\n// capturesQueue.add(camCapture);\n checkQueue();\n }\n } else bindService();\n Log.d(\"ImageTakin\", \"OnTakeBack()\");\n }\n }\n\n private void sendFrontCaptureImageIntent(CameraShield.CameraCapture camCapture) {\n if (camCapture != null) {\n if (isCameraBound) {\n isCameraCapturing = true;\n Bundle intent = new Bundle();\n intent.putInt(\"Quality_Mode\", camCapture.getQuality());\n intent.putBoolean(\"Front_Request\", true);\n Message msg = Message.obtain(null, CameraHeadService.CAPTURE_IMAGE);\n msg.setData(intent);\n try {\n cameraBinder.send(msg);\n } catch (RemoteException e) {\n checkQueue();\n }\n// service.takeImage(front_translucent);\n } else {\n bindService();\n }\n }\n }\n\n public interface CameraEventHandler {\n void OnPictureTaken();\n\n void checkCameraHardware(boolean isHasCamera);\n\n void takePicture();\n\n void setFlashMode(String flash_mode);\n\n void setOnCameraPreviewTypeChanged(boolean isBack);\n\n void updatePreviewButton(String lastImagePath);\n }\n\n public class CameraCapture implements Serializable {\n private String flash;\n private boolean isFrontCamera;\n\n private long tag;\n private int mquality;\n\n public CameraCapture(String flash, boolean isFront, int quality, long tag) {\n this.flash = flash;\n isFrontCamera = isFront;\n mquality = quality;\n this.tag = tag;\n }\n\n public int getQuality() {\n return mquality;\n\n }\n\n public String getFlash() {\n return flash;\n }\n\n public boolean isFront() {\n return isFrontCamera;\n\n }\n\n public long getTag() {\n return tag;\n }\n\n public void setTag(long tag) {\n this.tag = tag;\n }\n }\n\n}", "public class ColorDetectionShield extends\n ControllerParent<ColorDetectionShield> {\n private static final byte SHIELD_ID = (byte) 0x05;\n private static final byte SEND_NORMAL_COLOR = (byte) 0x01;\n private static final byte SEND_FULL_COLORS = (byte) 0x02;\n private static final byte ENABLE_FULL_COLORS = (byte) 0x02;\n private static final byte ENABLE_NORMAL_COLOR = (byte) 0x03;\n private static final byte SET_CALC_MODE = (byte) 0x04;\n private static final byte SET_PATCH_SIZE = (byte) 0x05;\n private static final byte SMALL_PATCH = (byte) 0x01;\n private static final byte MED_PATCH = (byte) 0x02;\n private static final byte AVERAGE_COLOR = (byte) 0x02;\n private static final byte SET_PALLETE = (byte) 0x01;\n private ColorDetectionEventHandler colorEventHandler;\n boolean isCameraBound = false;\n private Messenger mService;\n public static final int UNBIND_COLOR_DETECTOR = 2, SET_COLOR_DETECTION_OPERATION = 10, SET_COLOR_DETECTION_TYPE = 11, SET_COLOR_PATCH_SIZE = 12;\n private RECEIVED_FRAMES recevedFramesOperation = RECEIVED_FRAMES.CENTER;\n private COLOR_TYPE colorType = COLOR_TYPE.COMMON;\n private long lastSentMS = SystemClock.elapsedRealtime();\n private ShieldFrame frame;\n int[] detected;\n ColorPalette currentPallete = ColorPalette._24_BIT_RGB;\n private PATCH_SIZE patchSize = PATCH_SIZE.LARGE;\n public boolean isBackPreview = true;\n\n @Override\n\n public ControllerParent<ColorDetectionShield> init(String tag) {\n // TODO Auto-generated method stub\n initMessenger();\n return super.init(tag, true);\n }\n\n @Override\n public ControllerParent<ColorDetectionShield> invalidate(\n com.integreight.onesheeld.shields.ControllerParent.SelectionAction selectionAction,\n boolean isToastable) {\n this.selectionAction = selectionAction;\n addRequiredPremission(Manifest.permission.CAMERA);\n if (!CameraUtils.checkCameraHardware(getApplication().getApplicationContext())) {\n if (selectionAction != null)\n selectionAction.onFailure();\n if (isToastable)\n activity.showToast(R.string.color_detector_camera_is_unavailable_maybe_its_used_by_another_application_toast);\n } else {\n if (checkForPermissions()) {\n if(!activity.canDrawOverApps()){\n final AlertDialog.Builder builder = new AlertDialog.Builder(\n activity);\n builder.setMessage(\n R.string.color_detector_we_need_you_to_enable_the_draw_over_apps_permission_in_order_to_show_the_camera_preview_correctly)\n .setCancelable(false)\n .setPositiveButton(R.string.color_detector_validation_dialog_ok_button,\n new DialogInterface.OnClickListener() {\n public void onClick(final DialogInterface dialog,\n final int id) {\n activity.requestDrawOverApps();\n }\n })\n .setNegativeButton(R.string.color_detector_validation_dialog_later_button, new DialogInterface.OnClickListener() {\n public void onClick(final DialogInterface dialog,\n final int id) {\n dialog.cancel();\n activity.showToast(R.string.color_detector_please_enable_the_permission_to_be_able_to_select_this_shield_toast);\n }\n });\n final AlertDialog alert = builder.create();\n alert.show();\n if (this.selectionAction != null) {\n this.selectionAction.onFailure();\n }\n }\n else {\n if (selectionAction != null)\n selectionAction.onSuccess();\n bindService();\n }\n }else {\n if (selectionAction != null)\n selectionAction.onFailure();\n }\n }\n return super.invalidate(selectionAction, isToastable);\n }\n\n private void bindService(){\n getApplication().bindService(new Intent(getActivity(), CameraHeadService.class), mConnection, Context.BIND_AUTO_CREATE);\n }\n\n public ColorDetectionShield(Activity activity, String tag) {\n super(activity, tag, true);\n }\n\n public ColorDetectionShield() {\n super();\n }\n\n private void notifyPatchSize() {\n if (isCameraBound) {\n Message msg = Message.obtain(null, SET_COLOR_PATCH_SIZE);\n msg.replyTo = mMessenger;\n Bundle data = new Bundle();\n data.putInt(\"size\", patchSize.value);\n msg.setData(data);\n try {\n if (mService != null)\n mService.send(msg);\n } catch (RemoteException e) {\n }\n } else\n bindService();\n\n }\n\n private void notifyColorDetectionOperation() {\n if (isCameraBound) {\n Message msg = Message.obtain(null, SET_COLOR_DETECTION_OPERATION);\n msg.replyTo = mMessenger;\n Bundle data = new Bundle();\n data.putInt(\"type\", recevedFramesOperation.type);\n msg.setData(data);\n try {\n if (mService != null)\n mService.send(msg);\n } catch (RemoteException e) {\n }\n } else\n bindService();\n }\n\n private void notifyColorDetectionType() {\n if (isCameraBound) {\n Message msg = Message.obtain(null, SET_COLOR_DETECTION_TYPE);\n msg.replyTo = mMessenger;\n Bundle data = new Bundle();\n data.putInt(\"type\", colorType.type);\n msg.setData(data);\n try {\n if (mService != null)\n mService.send(msg);\n } catch (RemoteException e) {\n }\n } else\n bindService();\n\n }\n\n @Override\n public void onNewShieldFrameReceived(ShieldFrame frame) {\n if (frame.getShieldId() == SHIELD_ID) {\n switch (frame.getFunctionId()) {\n case ENABLE_FULL_COLORS:\n if (colorEventHandler != null) {\n colorEventHandler.enableFullColor();\n }\n recevedFramesOperation = RECEIVED_FRAMES.NINE_FRAMES;\n notifyColorDetectionOperation();\n break;\n case ENABLE_NORMAL_COLOR:\n if (colorEventHandler != null) {\n colorEventHandler.enableNormalColor();\n }\n recevedFramesOperation = RECEIVED_FRAMES.CENTER;\n notifyColorDetectionOperation();\n break;\n case SET_PALLETE:\n currentPallete = ColorPalette.get(frame.getArgument(0)[0]);\n if (colorEventHandler != null) {\n colorEventHandler.setPallete(currentPallete);\n }\n break;\n case SET_CALC_MODE:\n colorType = frame.getArgument(0)[0] == AVERAGE_COLOR ? COLOR_TYPE.AVERAGE : COLOR_TYPE.COMMON;\n if (colorEventHandler != null) {\n colorEventHandler.changeCalculationMode(colorType);\n }\n break;\n case SET_PATCH_SIZE:\n patchSize = frame.getArgument(0)[0] == SMALL_PATCH ? PATCH_SIZE.SMALL : frame.getArgument(0)[0] == MED_PATCH ? PATCH_SIZE.MEDIUM : PATCH_SIZE.LARGE;\n if (colorEventHandler != null) {\n colorEventHandler.changePatchSize(patchSize);\n }\n notifyPatchSize();\n break;\n }\n }\n }\n\n public void setColorEventHandler(ColorDetectionEventHandler colorEventHandler) {\n this.colorEventHandler = colorEventHandler;\n\n }\n\n public void showPreview(float x, float y, int width, int height) throws RemoteException {\n Message msg = Message.obtain(null, CameraHeadService.SHOW_PREVIEW);\n msg.replyTo = mMessenger;\n Bundle b = new Bundle();\n b.putFloat(\"x\", x);\n b.putFloat(\"y\", y);\n b.putInt(\"w\", width);\n b.putInt(\"h\", height);\n msg.setData(b);\n if (mService != null)\n mService.send(msg);\n else\n bindService();\n\n }\n\n public void invalidatePreview(float x, float y) throws RemoteException {\n Message msg = Message.obtain(null, CameraHeadService.INVALIDATE_PREVIEW);\n msg.replyTo = mMessenger;\n Bundle b = new Bundle();\n b.putFloat(\"x\", x);\n b.putFloat(\"y\", y);\n msg.setData(b);\n if (mService != null)\n mService.send(msg);\n else\n bindService();\n\n }\n\n public void hidePreview() throws RemoteException {\n Message msg = Message.obtain(null, CameraHeadService.HIDE_PREVIEW);\n msg.replyTo = mMessenger;\n if (mService != null)\n mService.send(msg);\n }\n\n public static interface ColorDetectionEventHandler {\n void onColorChanged(int... color);\n\n void enableFullColor();\n\n void enableNormalColor();\n\n void setPallete(ColorPalette pallete);\n\n void changeCalculationMode(COLOR_TYPE type);\n\n void changePatchSize(PATCH_SIZE patchSize);\n\n void onCameraPreviewTypeChanged(final boolean isBack);\n }\n\n public void setCurrentPallete(ColorPalette currentPallete) {\n this.currentPallete = currentPallete;\n }\n\n public ColorPalette getCurrentPallete() {\n return currentPallete;\n }\n\n public RECEIVED_FRAMES getRecevedFramesOperation() {\n return recevedFramesOperation;\n }\n\n @Override\n public void preConfigChange() {\n super.preConfigChange();\n }\n\n @Override\n public void postConfigChange() {\n super.postConfigChange();\n }\n\n @Override\n public void reset() {\n Message msg = Message.obtain(null, UNBIND_COLOR_DETECTOR);\n msg.replyTo = mMessenger;\n try {\n if (mService != null)\n mService.send(msg);\n } catch (RemoteException e) {\n }\n try {\n getApplication().unbindService(mConnection);\n }catch(IllegalArgumentException e){\n\n }\n }\n\n boolean fullFrame = true;\n private Messenger mMessenger;\n\n private void initMessenger() {\n new Thread(new Runnable() {\n @Override\n public void run() {\n Looper.prepare();\n mMessenger = new Messenger(new Handler() {\n\n public void handleMessage(Message msg) {\n if (msg.what == CameraHeadService.GET_RESULT && msg.getData() != null) {\n detected = msg.getData().getIntArray(\"detected\");\n frame = new ShieldFrame(SHIELD_ID, recevedFramesOperation == RECEIVED_FRAMES.NINE_FRAMES ? SEND_FULL_COLORS : SEND_NORMAL_COLOR);\n int i = 0;\n for (int det : detected) {\n int color = getColorInRange(det, currentPallete);\n detected[i] = color;\n frame.addArgument(3, color);\n fullFrame = true;\n i++;\n }\n if (fullFrame && colorEventHandler != null) {\n colorEventHandler.onColorChanged(detected);\n }\n if (fullFrame && SystemClock.elapsedRealtime() - lastSentMS >= 100) {\n sendShieldFrame(frame);\n lastSentMS = SystemClock.elapsedRealtime();\n }\n } else if (msg.what == CameraHeadService.CRASHED) {\n bindService();\n } else if (msg.what == CameraHeadService.SET_CAMERA_PREVIEW_TYPE) {\n isBackPreview = msg.getData().getBoolean(\"isBack\");\n if (colorEventHandler != null)\n colorEventHandler.onCameraPreviewTypeChanged(isBackPreview);\n isChangingPreview = false;\n }\n super.handleMessage(msg);\n }\n });\n Looper.loop();\n }\n }).start();\n }\n\n public boolean isBackPreview() {\n return isBackPreview;\n }\n\n private boolean isChangingPreview = false;\n\n public boolean setCameraToPreview(boolean isBack) {\n if (!isBack && !CameraUtils.checkFrontCamera(getActivity().getApplicationContext()))\n return false;\n if (isChangingPreview)\n return false;\n isChangingPreview = true;\n Message msg = Message.obtain(null, CameraHeadService.SET_CAMERA_PREVIEW_TYPE);\n msg.replyTo = mMessenger;\n Bundle b = new Bundle();\n b.putBoolean(\"isBack\", isBack);\n msg.setData(b);\n if (mService != null) {\n try {\n mService.send(msg);\n } catch (RemoteException e) {\n return false;\n }\n }\n isBackPreview = isBack;\n return true;\n }\n\n private ServiceConnection mConnection = new ServiceConnection() {\n\n public void onServiceConnected(ComponentName className,\n IBinder binder) {\n notifyHardwareOfShieldSelection();\n isCameraBound = true;\n mService = new Messenger(binder);\n Message msg = Message.obtain(null, CameraHeadService.GET_RESULT);\n msg.replyTo = mMessenger;\n try {\n mService.send(msg);\n notifyPatchSize();\n notifyColorDetectionType();\n notifyColorDetectionOperation();\n } catch (RemoteException e) {\n }\n }\n\n public void onServiceDisconnected(ComponentName className) {\n isCameraBound = false;\n }\n };\n\n public void setRecevedFramesOperation(RECEIVED_FRAMES recevedFramesOperation) {\n this.recevedFramesOperation = recevedFramesOperation;\n notifyColorDetectionOperation();\n }\n\n public COLOR_TYPE getColorType() {\n return colorType;\n }\n\n public void setColorType(COLOR_TYPE colorType) {\n this.colorType = colorType;\n notifyColorDetectionType();\n }\n\n int getColorInRange(int color, ColorPalette palette) {\n int i = 0;\n if (palette.isGrayscale) {\n i = palette.getNumberOfBits();\n int grayscale = (Color.red(color) + Color.green(color) + Color\n .blue(color)) / 3;\n color = Color.rgb(grayscale, grayscale, grayscale);\n } else\n i = palette.getNumberOfBits() / 3;\n\n int newR = (int) Math\n .round(((Color.red(color) >>> (8 - i)) * (255 / (Math.pow(2, i) - 1))));\n int newG = (int) Math\n .round(((Color.green(color) >>> (8 - i)) * (255 / (Math.pow(2, i) - 1))));\n int newB = (int) Math\n .round(((Color.blue(color) >>> (8 - i)) * (255 / (Math.pow(2, i) - 1))));\n return Color.rgb(newR, newG, newB);\n }\n\n public PATCH_SIZE getPatchSize() {\n return patchSize;\n }\n\n public void setPatchSize(PATCH_SIZE patchSize) {\n this.patchSize = patchSize;\n notifyPatchSize();\n }\n\n public enum ColorPalette {\n _1_BIT_GRAYSCALE(true, 1, 0), _2_BIT_GRAYSCALE(true, 2, 1), _4_BIT_GRAYSCALE(\n true, 4, 2), _8_BIT_GRAYSCALE(true, 8, 3), _3_BIT_RGB(3, 0), _6_BIT_RGB(\n 6, 1), _9_BIT_RGB(9, 2), _12_BIT_RGB(12, 3), _15_BIT_RGB(15, 4), _18_BIT_RGB(\n 18, 5), _24_BIT_RGB(24, 6);\n private boolean isGrayscale;\n private int numberOfBits;\n private int index;\n\n ColorPalette(int numberOfBits, int index) {\n this.isGrayscale = false;\n this.numberOfBits = numberOfBits;\n this.index = index;\n }\n\n ColorPalette(boolean isGrayscale, int numberOfBits, int index) {\n this.isGrayscale = isGrayscale;\n this.numberOfBits = numberOfBits;\n this.index = index;\n }\n\n public int getIndex() {\n return index;\n }\n\n public boolean isGrayscale() {\n return isGrayscale;\n }\n\n public int getNumberOfBits() {\n return numberOfBits;\n }\n\n @Override\n public String toString() {\n double colorRange = Math.pow(2, numberOfBits);\n DecimalFormat formatter = new DecimalFormat(\"#,###\");\n return formatter.format(colorRange)\n + (isGrayscale ? \" Grayscale\" : \"\") + \" Colors Palette\";\n }\n\n public static ColorPalette get(byte key) {\n switch (key) {\n case 1:\n return _1_BIT_GRAYSCALE;\n case 2:\n return _2_BIT_GRAYSCALE;\n case 3:\n return _4_BIT_GRAYSCALE;\n case 4:\n return _8_BIT_GRAYSCALE;\n case 5:\n return _3_BIT_RGB;\n case 6:\n return _6_BIT_RGB;\n case 7:\n return _9_BIT_RGB;\n case 8:\n return _12_BIT_RGB;\n case 9:\n return _15_BIT_RGB;\n case 10:\n return _18_BIT_RGB;\n case 11:\n default:\n return _24_BIT_RGB;\n }\n }\n }\n\n public static enum RECEIVED_FRAMES {\n CENTER(0), NINE_FRAMES(1);\n public int type;\n\n private RECEIVED_FRAMES(int type) {\n this.type = type;\n }\n\n public static RECEIVED_FRAMES getEnum(int type) {\n return type == 0 ? CENTER : NINE_FRAMES;\n }\n }\n\n public static enum COLOR_TYPE {\n COMMON(0), AVERAGE(1);\n public int type;\n\n private COLOR_TYPE(int type) {\n this.type = type;\n }\n\n public static COLOR_TYPE getEnum(int type) {\n return type == 0 ? COMMON : AVERAGE;\n }\n }\n\n public static enum PATCH_SIZE {\n SMALL(4), MEDIUM(2), LARGE(1);\n public int value;\n\n private PATCH_SIZE(int value) {\n this.value = value;\n }\n\n public static PATCH_SIZE getEnum(byte type) {\n return type == SMALL_PATCH ? SMALL : type == MED_PATCH ? MEDIUM : LARGE;\n }\n }\n}", "public class FaceDetectionShield extends ControllerParent<FaceDetectionShield> {\n private static final String TAG = FaceDetectionShield.class.getName();\n public static final int FACE_CRASHED = 18;\n public static final int BIND_FACE_DETECTION = 9;\n public static final int START_DETECTION = 14;\n public static final int SEND_FACES = 20;\n public static final int SEND_EMPTY = 21;\n public static final int IS_FACE_ACTIVE = 25;\n public static final int UNBIND_FACE_DETECTION = 6;\n private static final byte DETECTED_FACES = 0x01;\n private static final byte MISSING_FACES = 0x02;\n private Messenger faceBinder;\n private boolean isCameraBound = false;\n public boolean isBackPreview = true;\n public boolean isFaceSelected = false;\n private boolean isChangingPreview = false;\n private FaceDetectionHandler eventHandler;\n private byte[] faceId = new byte[2];\n private byte[] xPosition = new byte[2];\n private byte[] yPosition = new byte[2];\n private byte[] height = new byte[2];\n private byte[] width = new byte[2];\n private byte[] leftEye = new byte[2];\n private byte[] rightEye = new byte[2];\n private byte[] isSmile = new byte[2];\n private ShieldFrame frame;\n ArrayList<FaceDetectionObj> tmpArray = null;\n private int previewWidth, previewHeight;\n private int rotation;\n\n public FaceDetectionShield() {\n }\n\n public FaceDetectionShield(Activity activity, String tag) {\n super(activity, tag);\n }\n\n @Override\n public ControllerParent<FaceDetectionShield> init(String tag) {\n return super.init(tag);\n }\n\n @Override\n public ControllerParent<FaceDetectionShield> invalidate(SelectionAction selectionAction, boolean isToastable) {\n this.selectionAction = selectionAction;\n if (!checkCameraHardware(getApplication().getApplicationContext())) {\n if (selectionAction != null)\n selectionAction.onFailure();\n if (isToastable)\n activity.showToast(R.string.camera_camera_is_unavailable_maybe_its_used_by_another_application_toast);\n } else {\n addRequiredPremission(Manifest.permission.CAMERA);\n addRequiredPremission(Manifest.permission.WRITE_EXTERNAL_STORAGE);\n if (Build.VERSION.SDK_INT >= 16)\n addRequiredPremission(Manifest.permission.READ_EXTERNAL_STORAGE);\n if (checkForPermissions()) {\n if (!activity.canDrawOverApps()) {\n final AlertDialog.Builder builder = new AlertDialog.Builder(\n activity);\n builder.setMessage(\n R.string.camera_we_need_you_to_enable_the_draw_over_apps_permission_in_order_to_show_the_camera_preview_correctly)\n .setCancelable(false)\n .setPositiveButton(R.string.camera_validation_dialog_ok_button,\n new DialogInterface.OnClickListener() {\n public void onClick(final DialogInterface dialog,\n final int id) {\n activity.requestDrawOverApps();\n }\n })\n .setNegativeButton(R.string.camera_validation_dialog_later_button, new DialogInterface.OnClickListener() {\n public void onClick(final DialogInterface dialog,\n final int id) {\n dialog.cancel();\n activity.showToast(R.string.camera_please_enable_the_permission_to_be_able_to_select_this_shield_toast);\n }\n });\n final AlertDialog alert = builder.create();\n alert.show();\n if (this.selectionAction != null) {\n this.selectionAction.onFailure();\n }\n } else {\n if (selectionAction != null)\n selectionAction.onSuccess();\n bindService();\n }\n } else {\n if (this.selectionAction != null) {\n this.selectionAction.onFailure();\n }\n }\n }\n\n return super.invalidate(selectionAction, isToastable);\n }\n\n private Messenger mMessenger = new Messenger(new Handler() {\n public void handleMessage(Message msg) {\n if (msg.what == FACE_CRASHED) {\n faceBinder = null;\n isCameraBound = false;\n bindService();\n } else if (msg.what == CameraHeadService.SET_CAMERA_PREVIEW_TYPE) {\n isBackPreview = msg.getData().getBoolean(\"isBack\");\n if (eventHandler != null)\n eventHandler.setOnCameraPreviewTypeChanged(isBackPreview);\n isChangingPreview = false;\n\n } else if (msg.what == SEND_FACES) {\n Bundle bundle = msg.getData();\n if (tmpArray == null)\n tmpArray = new ArrayList<>();\n bundle.setClassLoader(FaceDetectionObj.class.getClassLoader());\n ArrayList<FaceDetectionObj> faceDetectionObjArrayList;\n faceDetectionObjArrayList = bundle.getParcelableArrayList(\"face_array\");\n previewHeight = bundle.getInt(\"height\");\n previewWidth = bundle.getInt(\"width\");\n rotation = bundle.getInt(\"rotation\");\n for (int i = 0; i < faceDetectionObjArrayList.size(); i++) {\n boolean isMatched = false;\n for (int j = 0; j < tmpArray.size(); j++)\n if (faceDetectionObjArrayList.get(i).getFaceId() == tmpArray.get(j).getFaceId()) {\n isMatched = true;\n if (tmpArray.get(j).getxPosition() != faceDetectionObjArrayList.get(i).getxPosition() ||\n tmpArray.get(j).getyPosition() != faceDetectionObjArrayList.get(i).getyPosition() ||\n tmpArray.get(j).getWidth() != faceDetectionObjArrayList.get(i).getWidth() ||\n tmpArray.get(j).getHeight() != faceDetectionObjArrayList.get(i).getHeight() ||\n tmpArray.get(j).getLeftEye() != faceDetectionObjArrayList.get(i).getLeftEye() ||\n tmpArray.get(j).getRightEye() != faceDetectionObjArrayList.get(i).getRightEye() ||\n tmpArray.get(j).getIsSmile() != faceDetectionObjArrayList.get(i).getIsSmile()) {\n sendDetectedFaces(tmpArray.get(j), previewWidth, previewHeight);\n tmpArray.remove(j);\n }\n break;\n }\n if (!isMatched)\n sendDetectedFaces(faceDetectionObjArrayList.get(i), previewWidth, previewHeight);\n }\n if (tmpArray.size() > 0)\n for (int k = 0; k < tmpArray.size(); k++)\n sendMissingFaces(tmpArray.get(k));\n tmpArray = faceDetectionObjArrayList;\n }\n if (msg.what == SEND_EMPTY) {\n if (tmpArray != null)\n for (int i = 0; i < tmpArray.size(); i++)\n sendMissingFaces(tmpArray.get(i));\n tmpArray = null;\n }\n super.handleMessage(msg);\n }\n });\n\n private ServiceConnection serviceConnection = new ServiceConnection() {\n @Override\n public void onServiceConnected(ComponentName name, IBinder service) {\n notifyHardwareOfShieldSelection();\n faceBinder = new Messenger(service);\n Message msg = Message.obtain(null, BIND_FACE_DETECTION);\n msg.replyTo = mMessenger;\n try {\n faceBinder.send(msg);\n } catch (RemoteException e) {\n }\n isCameraBound = true;\n try {\n setStartDetection();\n } catch (RemoteException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public void onServiceDisconnected(ComponentName name) {\n isCameraBound = false;\n }\n };\n\n private void bindService() {\n getApplication().bindService(new Intent(getActivity(), CameraHeadService.class), serviceConnection, Context.BIND_AUTO_CREATE);\n\n }\n\n /**\n * Check if this device has a camera\n */\n private synchronized boolean checkCameraHardware(Context context) {\n if (context.getPackageManager().hasSystemFeature(\n PackageManager.FEATURE_CAMERA)) {\n // this device has a camera\n return true;\n } else {\n // no camera on this device\n return false;\n }\n }\n\n public boolean isBackPreview() {\n return isBackPreview;\n }\n\n public boolean isFaceSelected() {\n return isFaceSelected;\n }\n\n public void setStartDetection() throws RemoteException {\n if (isCameraBound) {\n Message msg = Message.obtain(null, START_DETECTION);\n msg.replyTo = mMessenger;\n if (faceBinder != null) {\n faceBinder.send(msg);\n }\n } else {\n bindService();\n }\n }\n\n public void setIsFaceSelected(boolean isFaceSelected) {\n if (faceBinder != null) {\n Message msg = Message.obtain(null, IS_FACE_ACTIVE);\n msg.replyTo = mMessenger;\n Bundle b = new Bundle();\n b.putBoolean(\"setIsFaceSelected\", isFaceSelected);\n msg.setData(b);\n try {\n faceBinder.send(msg);\n } catch (RemoteException e) {\n e.printStackTrace();\n }\n } else {\n bindService();\n }\n this.isFaceSelected = isFaceSelected;\n }\n\n public boolean setCameraToPreview(boolean isBack) {\n if (faceBinder != null) {\n if (!isBack && !CameraUtils.checkFrontCamera(getActivity().getApplicationContext()))\n return false;\n if (isChangingPreview)\n return false;\n isChangingPreview = true;\n Log.d(\"Acc\", isBack + \" **\");\n Message msg = Message.obtain(null, CameraHeadService.SET_CAMERA_PREVIEW_TYPE);\n msg.replyTo = mMessenger;\n Bundle b = new Bundle();\n b.putBoolean(\"isBack\", isBack);\n msg.setData(b);\n try {\n faceBinder.send(msg);\n } catch (RemoteException e) {\n return false;\n }\n } else {\n bindService();\n }\n isBackPreview = isBack;\n return true;\n }\n\n public boolean showPreview() throws RemoteException {\n if (faceBinder != null) {\n Message msg = Message.obtain(null, CameraHeadService.SHOW_PREVIEW);\n msg.replyTo = mMessenger;\n faceBinder.send(msg);\n return true;\n } else {\n bindService();\n return false;\n }\n }\n\n public boolean hidePreview() throws RemoteException {\n if (faceBinder != null) {\n Message msg = Message.obtain(null, CameraHeadService.HIDE_PREVIEW);\n msg.replyTo = mMessenger;\n faceBinder.send(msg);\n return true;\n } else {\n return false;\n }\n }\n\n public void invalidatePreview() throws RemoteException {\n if (faceBinder != null) {\n Message msg = Message.obtain(null, CameraHeadService.INVALIDATE_PREVIEW);\n msg.replyTo = mMessenger;\n faceBinder.send(msg);\n } else\n bindService();\n }\n\n @Override\n public void onNewShieldFrameReceived(ShieldFrame frame) {\n }\n\n public interface FaceDetectionHandler {\n void setOnCameraPreviewTypeChanged(boolean isBack);\n }\n\n @Override\n public void reset() {\n android.util.Log.d(TAG, \"unbind: \");\n Message msg = Message.obtain(null, UNBIND_FACE_DETECTION);\n msg.replyTo = mMessenger;\n try {\n if (faceBinder != null)\n faceBinder.send(msg);\n } catch (RemoteException e) {\n }\n try {\n getApplication().unbindService(serviceConnection);\n } catch (IllegalArgumentException e) {\n }\n isCameraBound = false;\n }\n\n public void setCameraEventHandler(FaceDetectionHandler eventHandler) {\n this.eventHandler = eventHandler;\n }\n\n @Override\n public void preConfigChange() {\n super.preConfigChange();\n }\n\n @Override\n public void postConfigChange() {\n super.postConfigChange();\n }\n\n private static byte[] intTo2ByteArray(int value) {\n byte[] bytes = new byte[2];\n bytes[0] = (byte) (value & 0xff);\n bytes[1] = (byte) ((value >>> 8) & 0xff);\n return bytes;\n }\n\n private static byte[] float2ByteArray(float value) {\n int bits = Math.round(value);\n byte[] bytes = new byte[2];\n bytes[0] = (byte) (bits & 0xff);\n bytes[1] = (byte) ((bits >>> 8) & 0xff);\n return bytes;\n }\n\n private static byte[] twoByteArraysInto4ByteArray(byte[] value1, byte[] value2) {\n byte[] bytes = new byte[4];\n bytes[0] = value1[0];\n bytes[1] = value1[1];\n bytes[2] = value2[0];\n bytes[3] = value2[1];\n return bytes;\n }\n\n private static byte[] threeByteArraysTo4ByteArray(byte[] value, byte[] value1, byte[] value2) {\n byte[] bytes = new byte[4];\n bytes[0] = value[0];\n bytes[1] = value1[0];\n bytes[2] = value2[0];\n bytes[3] = 0;\n return bytes;\n }\n\n private static float transform(float value, float inMin, float inMax, float outMin, float outMax) {\n return (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;\n }\n\n public void sendDetectedFaces(FaceDetectionObj faceDetection, int previewWidth, int previewHeight) {\n float x = faceDetection.getxPosition();\n float y = faceDetection.getyPosition();\n float scaledX, scaledY, scaleSmile, scaleRightEye, scaleLeftEye;\n switch (rotation) {\n case 0: {\n if (!isBackPreview)\n x = previewHeight - x;\n break;\n }\n case 1: {\n if (!isBackPreview)\n x = previewWidth - x;\n break;\n }\n case 2: {\n if (!isBackPreview)\n x = previewHeight - x;\n break;\n }\n case 3: {\n if (!isBackPreview)\n x = previewWidth - x;\n break;\n }\n }\n frame = new ShieldFrame(UIShield.FACE_DETECTION.getId(), DETECTED_FACES);\n faceId = intTo2ByteArray(faceDetection.getFaceId());\n scaledX = transform(x, 0, previewWidth, -500, 500);\n scaledY = transform(y, 0, previewHeight, 500, -500);\n if (faceDetection.getIsSmile() == -1)\n isSmile = float2ByteArray(faceDetection.getIsSmile());\n else if (faceDetection.getRightEye() == -1)\n rightEye = float2ByteArray(faceDetection.getRightEye());\n else if (faceDetection.getLeftEye() == -1)\n leftEye = float2ByteArray(faceDetection.getLeftEye());\n else {\n scaleSmile = transform(faceDetection.getIsSmile(), 0, 1, 0, 100);\n scaleRightEye = transform(faceDetection.getRightEye(), 0, 1, 0, 100);\n scaleLeftEye = transform(faceDetection.getLeftEye(), 0, 1, 0, 100);\n leftEye = float2ByteArray(scaleLeftEye);\n rightEye = float2ByteArray(scaleRightEye);\n isSmile = float2ByteArray(scaleSmile);\n }\n xPosition = float2ByteArray(scaledX);\n yPosition = float2ByteArray(scaledY);\n height = float2ByteArray(faceDetection.getHeight());\n width = float2ByteArray(faceDetection.getWidth());\n frame.addArgument(faceId);\n frame.addArgument(twoByteArraysInto4ByteArray(xPosition, yPosition));\n if (rotation == 1 || rotation == 3)\n frame.addArgument(twoByteArraysInto4ByteArray(height, width));\n else\n frame.addArgument(twoByteArraysInto4ByteArray(width, height));\n frame.addArgument(threeByteArraysTo4ByteArray(leftEye, rightEye, isSmile));\n sendShieldFrame(frame);\n }\n\n public void sendMissingFaces(FaceDetectionObj faceDetectionObj) {\n frame = new ShieldFrame(UIShield.FACE_DETECTION.getId(), MISSING_FACES);\n faceId = intTo2ByteArray(faceDetectionObj.getFaceId());\n frame.addArgument(faceId);\n sendShieldFrame(frame);\n }\n\n\n}", "public class AppShields {\n private static AppShields thisInstance;\n private Hashtable<String, Shield> shieldsTable;\n private Hashtable<String, String> shieldsTags;\n private SparseArray<Shield> shieldsArray;\n private String rememberedShields;\n\n private AppShields() {\n // TODO Auto-generated constructor stub\n }\n\n public static AppShields getInstance() {\n if (thisInstance == null) {\n thisInstance = new AppShields();\n }\n return thisInstance;\n }\n\n public void init(String selectedCach) {\n this.rememberedShields = selectedCach;\n initShields();\n }\n\n public Hashtable<String, Shield> getShieldsTable() {\n if (shieldsTable == null || shieldsTable.size() == 0) {\n initShields();\n }\n return shieldsTable;\n }\n\n public SparseArray<Shield> getShieldsArray() {\n if (shieldsArray == null || shieldsArray.size() == 0)\n initShields();\n return shieldsArray;\n }\n\n public Shield getShield(String tag) {\n if (shieldsArray == null || shieldsArray.size() == 0)\n initShields();\n return shieldsTable.get(tag);\n }\n//\n// public Shield getShieldByName(String name) {\n// if (nameAndTagTable == null || nameAndTagTable.size() == 0 || shieldsArray == null || shieldsArray.size() == 0)\n// initShields();\n// return shieldsTable.get(nameAndTagTable.get(name));\n// }\n\n public void putShield(int position, Shield shield) {\n if (shieldsArray == null || shieldsArray.size() == 0)\n initShields();\n shieldsArray.put(position, shield);\n shieldsTable.put(shield.tag, shield);\n }\n\n public void putShield(String tag, Shield shield) {\n if (shieldsArray == null || shieldsArray.size() == 0)\n initShields();\n shieldsTable.put(tag, shield);\n shieldsArray.put(shield.position, shield);\n }\n\n public Shield getShield(int position) {\n if (shieldsArray == null || shieldsArray.size() == 0)\n initShields();\n return shieldsArray.get(position);\n }\n\n public ArrayList<Byte> getRememberedShields() {\n if (rememberedShields == null || rememberedShields.length() == 0)\n return new ArrayList<>();\n String[] arrString = rememberedShields.split(\",\");\n ArrayList<Byte> bytes = new ArrayList<>();\n for (int i = 0; i < arrString.length; i++) {\n bytes.add(Byte.parseByte(arrString[i]));\n }\n return bytes;\n }\n\n public String getSelectedShields() {\n String selected = \"\";\n for (int i = 0; i < shieldsArray.size(); i++) {\n Shield shield = shieldsArray.get(i);\n selected += (shield.mainActivitySelection ? shield.id + \",\" : \"\");\n }\n return selected.trim().length() == 0 ? selected : selected.substring(0, selected.length() - 1);\n }\n\n private void initShields() {\n int i = 0;\n shieldsArray = new SparseArray();\n shieldsTable = new Hashtable();\n shieldsTags = new Hashtable();\n ArrayList<Byte> remembered = getRememberedShields();\n for (UIShield shield : UIShield.valuesFiltered()) {\n shieldsTable.put(shield.name(), new Shield(shield.getId(), i,\n shield.name(), shield.getName(), shield.getItemBackgroundColor(),\n shield.getSymbolId(), remembered.contains(shield.getId()) ? true : shield.isMainActivitySelection(),\n shield.getShieldType(), shield.getShieldFragment(), shield.isReleasable(),\n shield.getIsInvalidatable()));\n shieldsArray.put(i,\n new Shield(shield.getId(), i, shield.name(), shield.getName(),\n shield.getItemBackgroundColor(), shield.getSymbolId(),\n remembered.contains(shield.getId()) ? true : shield.isMainActivitySelection(), shield.getShieldType(), shield.getShieldFragment(),\n shield.isReleasable(), shield.getIsInvalidatable()));\n shieldsTags.put(shield.getShieldType().getName(), shield.name());\n shieldsTags.put(shield.getShieldFragment().getName(), shield.name());\n i++;\n }\n }\n\n public synchronized String getShieldTag(String key) {\n if (shieldsTags == null || shieldsTags.size() == 0)\n initShields();\n return shieldsTags.get(key);\n }\n}" ]
import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.ListView; import android.widget.Toast; import com.google.android.gms.analytics.HitBuilders; import com.integreight.onesheeld.BuildConfig; import com.integreight.onesheeld.MainActivity; import com.integreight.onesheeld.OneSheeldApplication; import com.integreight.onesheeld.R; import com.integreight.onesheeld.Tutorial; import com.integreight.onesheeld.adapters.ShieldsListAdapter; import com.integreight.onesheeld.enums.UIShield; import com.integreight.onesheeld.model.Shield; import com.integreight.onesheeld.popup.ArduinoConnectivityPopup; import com.integreight.onesheeld.popup.FirmwareUpdatingPopup; import com.integreight.onesheeld.popup.ValidationPopup; import com.integreight.onesheeld.popup.ValidationPopup.ValidationAction; import com.integreight.onesheeld.sdk.OneSheeldConnectionCallback; import com.integreight.onesheeld.sdk.OneSheeldDevice; import com.integreight.onesheeld.sdk.OneSheeldError; import com.integreight.onesheeld.sdk.OneSheeldErrorCallback; import com.integreight.onesheeld.sdk.OneSheeldSdk; import com.integreight.onesheeld.services.OneSheeldService; import com.integreight.onesheeld.shields.controller.CameraShield; import com.integreight.onesheeld.shields.controller.ColorDetectionShield; import com.integreight.onesheeld.shields.controller.FaceDetectionShield; import com.integreight.onesheeld.shields.controller.TaskerShield; import com.integreight.onesheeld.utils.AppShields; import com.integreight.onesheeld.utils.CrashlyticsUtils; import com.integreight.onesheeld.utils.Log; import com.integreight.onesheeld.utils.customviews.OneSheeldEditText; import com.manuelpeinado.quickreturnheader.QuickReturnHeaderHelper; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import hotchemi.android.rate.AppRate;
if (activity.getSupportFragmentManager() .getBackStackEntryCount() > 1) { activity.getSupportFragmentManager() .popBackStack(); activity.getSupportFragmentManager() .executePendingTransactions(); } OneSheeldSdk.getManager().disconnectAll(); } else { Log.test("Test", "Cannot disconnect in demoMode"); getApplication().setIsDemoMode(false); } if (!ArduinoConnectivityPopup.isOpened) { ArduinoConnectivityPopup.isOpened = true; new ArduinoConnectivityPopup(activity) .show(); } } }); return; } else { activity.replaceCurrentFragment(R.id.appTransitionsContainer, ShieldsOperations.getInstance(), ShieldsOperations.class.getName(), true, true); activity.findViewById(R.id.getAvailableDevices) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); } } } OneSheeldErrorCallback errorCallback = new OneSheeldErrorCallback() { @Override public void onError(OneSheeldDevice device, OneSheeldError error) { super.onError(device, error); if (activity != null && activity.getThisApplication().taskerController != null) { activity.getThisApplication().taskerController.reset(); } activity.runOnUiThread(new Runnable() { @Override public void run() { getApplication() .endConnectionTimerAndReport(); UIShield.setConnected(false); adapter.notifyDataSetChanged(); if (activity.getSupportFragmentManager().getBackStackEntryCount() > 1) { activity.getSupportFragmentManager().popBackStack(); activity.getSupportFragmentManager() .executePendingTransactions(); } if (!ArduinoConnectivityPopup.isOpened && !getApplication().getIsDemoMode()) { new ArduinoConnectivityPopup(activity).show(); } } }); } }; OneSheeldConnectionCallback connectionCallback = new OneSheeldConnectionCallback() { @Override public void onConnect(OneSheeldDevice device) { super.onConnect(device); ((OneSheeldApplication) activity.getApplication()).setConnectedDevice(device); if (activity.getThisApplication().getConnectedDevice() != null) activity.getThisApplication().getConnectedDevice().addVersionQueryCallback(activity.versionQueryCallback); Intent intent = new Intent(activity, OneSheeldService.class); intent.putExtra(ArduinoConnectivityPopup.EXTRA_DEVICE_NAME, device.getName()); activity.startService(intent); getApplication().setConnectedDevice(device); activity.runOnUiThread(new Runnable() { @Override public void run() { activity.getThisApplication().taskerController = new TaskerShield( activity, UIShield.TASKER_SHIELD.name()); Log.e(TAG, "- ARDUINO CONNECTED -"); getApplication().getTracker() .send(new HitBuilders.ScreenViewBuilder().setNewSession() .build()); getApplication() .startConnectionTimer(); // if (isOneSheeldServiceRunning()) { if (adapter != null) adapter.applyToControllerTable(); // } AppRate.showRateDialogIfMeetsConditions(activity); activity.showMenuButtonTutorialOnce(); } }); } @Override public void onDisconnect(OneSheeldDevice device) { super.onDisconnect(device); getApplication().setConnectedDevice(null); activity.runOnUiThread(new Runnable() { @Override public void run() { if (activity != null) { if (activity.getThisApplication().getRunningShields().get(UIShield.CAMERA_SHIELD.name()) != null) try { ((CameraShield) activity.getThisApplication().getRunningShields().get(UIShield.CAMERA_SHIELD.name())).hidePreview(); } catch (RemoteException e) { e.printStackTrace(); } if (activity.getThisApplication().getRunningShields().get(UIShield.COLOR_DETECTION_SHIELD.name()) != null) try { ((ColorDetectionShield) activity.getThisApplication().getRunningShields().get(UIShield.COLOR_DETECTION_SHIELD.name())).hidePreview(); } catch (RemoteException e) { e.printStackTrace(); } if (activity.getThisApplication().getRunningShields().get(UIShield.FACE_DETECTION.name()) != null) try {
((FaceDetectionShield) activity.getThisApplication().getRunningShields().get(UIShield.FACE_DETECTION.name())).hidePreview();
7
btk5h/skript-mirror
src/main/java/com/btk5h/skriptmirror/skript/reflect/ExprProxy.java
[ "public class FunctionWrapper {\n private final String name;\n private final Object[] arguments;\n\n public FunctionWrapper(String name, Object[] arguments) {\n this.name = name;\n this.arguments = arguments;\n }\n\n public String getName() {\n return name;\n }\n\n public Object[] getArguments() {\n return arguments;\n }\n\n public Function getFunction() {\n Function<?> function = Functions.getFunction(name);\n if (function == null) {\n Skript.warning(String.format(\"The function '%s' could not be resolved.\", name));\n return NoOpFunction.INSTANCE;\n }\n return function;\n }\n\n private static class NoOpFunction extends Function<Object> {\n private static NoOpFunction INSTANCE = new NoOpFunction();\n\n private NoOpFunction() {\n super(\"$noop\", new Parameter[0], Classes.getExactClassInfo(Object.class), true);\n }\n\n @Override\n public Object[] execute(FunctionEvent e, Object[][] params) {\n return null;\n }\n\n @Override\n public boolean resetReturnValue() {\n return false;\n }\n }\n}", "public final class JavaType {\n private final Class<?> javaClass;\n\n public JavaType(Class<?> javaClass) {\n this.javaClass = javaClass;\n }\n\n public Class<?> getJavaClass() {\n return javaClass;\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 JavaType javaType1 = (JavaType) o;\n return Objects.equals(javaClass, javaType1.javaClass);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(javaClass);\n }\n}", "public class LibraryLoader {\n private static ClassLoader classLoader = LibraryLoader.class.getClassLoader();\n\n private static final PathMatcher MATCHER =\n FileSystems.getDefault().getPathMatcher(\"glob:**/*.jar\");\n\n private static class LibraryVisitor extends SimpleFileVisitor<Path> {\n private List<URL> urls = new ArrayList<>();\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n if (MATCHER.matches(file)) {\n Skript.info(\"Loaded external library \" + file.getFileName());\n urls.add(file.toUri().toURL());\n }\n return super.visitFile(file, attrs);\n }\n\n public URL[] getUrls() {\n return urls.toArray(new URL[urls.size()]);\n }\n }\n\n public static void loadLibraries(Path dataFolder) throws IOException {\n if (Files.isDirectory(dataFolder)) {\n LibraryVisitor visitor = new LibraryVisitor();\n Files.walkFileTree(dataFolder, visitor);\n classLoader = new URLClassLoader(visitor.getUrls(), LibraryLoader.class.getClassLoader());\n } else {\n Files.createDirectory(dataFolder);\n }\n }\n\n public static ClassLoader getClassLoader() {\n return classLoader;\n }\n}", "public class Consent extends SelfRegisteringSkriptEvent {\n static {\n CustomSyntaxSection.register(\"Consent\", Consent.class, \"skript-mirror, I know what I'm doing\");\n }\n\n public enum Feature {\n PROXIES(\"proxies\"),\n DEFERRED_PARSING(\"deferred-parsing\");\n\n private String codeName;\n\n Feature(String codeName) {\n this.codeName = codeName;\n }\n\n public boolean hasConsent(File script) {\n List<Feature> features = consentedFeatures.get(script);\n return features != null && features.contains(this);\n }\n\n public static Optional<Feature> byCodeName(String codeName) {\n return Arrays.stream(Feature.values())\n .filter(f -> codeName.equals(f.codeName))\n .findFirst();\n }\n }\n\n private static final Map<File, List<Feature>> consentedFeatures = new HashMap<>();\n\n private static final String[] CONSENT_LINES = new String[]{\n \"I understand that the following features are experimental and may change in the future.\",\n \"I have read about this at https://skript-mirror.gitbook.io/docs/advanced/experiments\"\n };\n\n @Override\n public void register(Trigger t) {\n }\n\n @Override\n public void unregister(Trigger t) {\n consentedFeatures.remove(t.getScript());\n }\n\n @Override\n public void unregisterAll() {\n consentedFeatures.clear();\n }\n\n @Override\n public boolean init(Literal<?>[] args, int matchedPattern, SkriptParser.ParseResult parseResult) {\n File currentScript = ScriptLoader.currentScript.getFile();\n SectionNode node = ((SectionNode) SkriptLogger.getNode());\n\n if (node.getKey().toLowerCase().startsWith(\"on \")) {\n return false;\n }\n\n int consentLine = 0;\n for (Node subNode : node) {\n String text = subNode.getKey();\n\n // For the first few lines, make sure the consent text is copied verbatim\n if (consentLine < CONSENT_LINES.length) {\n if (!text.equals(CONSENT_LINES[consentLine])) {\n return false;\n }\n\n consentLine++;\n continue;\n }\n\n Feature.byCodeName(text).ifPresent(feature -> {\n consentedFeatures\n .computeIfAbsent(currentScript, t -> new ArrayList<>())\n .add(feature);\n });\n }\n\n SkriptUtil.clearSectionNode(node);\n return true;\n }\n\n\n @Override\n public String toString(Event e, boolean debug) {\n return \"experimental consent notice\";\n }\n}", "public class SkriptReflection {\n public static String MISSING_AND_OR;\n\n private static Field PATTERNS;\n private static Field PARAMETERS;\n private static Field HANDLERS;\n private static Field CURRENT_OPTIONS;\n private static Field LOCAL_VARIABLES;\n private static Field VARIABLES_MAP_HASHMAP;\n private static Field VARIABLES_MAP_TREEMAP;\n private static Constructor VARIABLES_MAP;\n\n static {\n Field _FIELD;\n Constructor _CONSTRUCTOR;\n\n try {\n _FIELD = SkriptParser.class.getDeclaredField(\"MISSING_AND_OR\");\n _FIELD.setAccessible(true);\n MISSING_AND_OR = (String) _FIELD.get(null);\n } catch (NoSuchFieldException | IllegalAccessException ignored) {\n }\n\n try {\n _FIELD = SyntaxElementInfo.class.getDeclaredField(\"patterns\");\n _FIELD.setAccessible(true);\n PATTERNS = _FIELD;\n } catch (NoSuchFieldException e) {\n Skript.warning(\"Skript's pattern info field could not be resolved. \" +\n \"Custom syntax will not work.\");\n }\n\n try {\n _FIELD = Function.class.getDeclaredField(\"parameters\");\n _FIELD.setAccessible(true);\n PARAMETERS = _FIELD;\n } catch (NoSuchFieldException e) {\n Skript.warning(\"Skript's parameters field could not be resolved. \" +\n \"Class proxies will not work.\");\n }\n\n try {\n _FIELD = SkriptLogger.class.getDeclaredField(\"handlers\");\n _FIELD.setAccessible(true);\n JavaReflection.removeFinalModifier(_FIELD);\n HANDLERS = _FIELD;\n } catch (NoSuchFieldException e) {\n Skript.warning(\"Skript's handlers field could not be resolved. Some Skript warnings may not be available.\");\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n\n try {\n _FIELD = ScriptLoader.class.getDeclaredField(\"currentOptions\");\n _FIELD.setAccessible(true);\n CURRENT_OPTIONS = _FIELD;\n } catch (NoSuchFieldException e) {\n Skript.warning(\"Skript's options field could not be resolved.\");\n }\n\n try {\n _FIELD = Variables.class.getDeclaredField(\"localVariables\");\n _FIELD.setAccessible(true);\n LOCAL_VARIABLES = _FIELD;\n } catch (NoSuchFieldException e) {\n Skript.warning(\"Skript's local variables field could not be resolved.\");\n }\n\n try {\n Class<?> variablesMap = Class.forName(\"ch.njol.skript.variables.VariablesMap\");\n\n try {\n _FIELD = variablesMap.getDeclaredField(\"hashMap\");\n _FIELD.setAccessible(true);\n VARIABLES_MAP_HASHMAP = _FIELD;\n } catch (NoSuchFieldException e) {\n Skript.warning(\"Skript's hash map field could not be resolved.\");\n }\n\n try {\n _FIELD = variablesMap.getDeclaredField(\"treeMap\");\n _FIELD.setAccessible(true);\n VARIABLES_MAP_TREEMAP = _FIELD;\n } catch (NoSuchFieldException e) {\n Skript.warning(\"Skript's tree map field could not be resolved.\");\n }\n\n try {\n _CONSTRUCTOR = variablesMap.getDeclaredConstructor();\n _CONSTRUCTOR.setAccessible(true);\n VARIABLES_MAP = _CONSTRUCTOR;\n } catch (NoSuchMethodException e) {\n Skript.warning(\"Skript's variables map constructors could not be resolved.\");\n }\n } catch (ClassNotFoundException e) {\n Skript.warning(\"Skript's variables map class could not be resolved.\");\n }\n }\n\n public static void setPatterns(SyntaxElementInfo<?> info, String[] patterns) {\n try {\n PATTERNS.set(info, patterns);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n }\n\n public static Parameter<?>[] getParameters(Function function) {\n try {\n return ((Parameter<?>[]) PARAMETERS.get(function));\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n throw new IllegalStateException();\n }\n\n public static void printLog(RetainingLogHandler logger) {\n logger.stop();\n HandlerList handler;\n try {\n handler = (HandlerList) HANDLERS.get(logger);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n return;\n }\n\n Iterator<LogHandler> handlers = handler.iterator();\n LogHandler nextHandler;\n List<LogHandler> parseLogs = new ArrayList<>();\n\n while (handlers.hasNext()) {\n nextHandler = handlers.next();\n\n if (!(nextHandler instanceof ParseLogHandler)) {\n break;\n }\n parseLogs.add(nextHandler);\n }\n\n parseLogs.forEach(LogHandler::stop);\n SkriptLogger.logAll(logger.getLog());\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Map<String, String> getCurrentOptions() {\n try {\n return (Map<String, String>) CURRENT_OPTIONS.get(null);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n throw new IllegalStateException();\n }\n\n @SuppressWarnings(\"unchecked\")\n public static boolean hasLocalVariables(Event e) {\n try {\n return ((Map<Event, Object>) LOCAL_VARIABLES.get(null)).containsKey(e);\n } catch (IllegalAccessException ex) {\n return false;\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static void copyVariablesMap(Event from, Event to) {\n if (from == null) {\n return;\n }\n\n try {\n Map<Event, Object> localVariables = (Map<Event, Object>) LOCAL_VARIABLES.get(null);\n Object originalVariablesMap = localVariables.get(from);\n\n if (originalVariablesMap != null) {\n Object variablesMap = localVariables\n .computeIfAbsent(to, JavaUtil.propagateErrors(e -> VARIABLES_MAP.newInstance()));\n\n ((Map<String, Object>) VARIABLES_MAP_HASHMAP.get(variablesMap))\n .putAll((Map<String, Object>) VARIABLES_MAP_HASHMAP.get(originalVariablesMap));\n ((Map<String, Object>) VARIABLES_MAP_TREEMAP.get(variablesMap))\n .putAll((Map<String, Object>) VARIABLES_MAP_TREEMAP.get(originalVariablesMap));\n }\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n }\n}", "public class SkriptUtil {\n @SuppressWarnings(\"unchecked\")\n public static <T> Expression<T> defendExpression(Expression<?> expr) {\n if (expr instanceof UnparsedLiteral) {\n Literal<?> parsed = ((UnparsedLiteral) expr).getConvertedExpression(Object.class);\n return (Expression<T>) (parsed == null ? expr : parsed);\n } else if (expr instanceof ExpressionList) {\n Expression[] exprs = ((ExpressionList) expr).getExpressions();\n for (int i = 0; i < exprs.length; i++) {\n exprs[i] = defendExpression(exprs[i]);\n }\n }\n return (Expression<T>) expr;\n }\n\n public static boolean hasUnparsedLiteral(Expression<?> expr) {\n return expr instanceof UnparsedLiteral ||\n (expr instanceof ExpressionList &&\n Arrays.stream(((ExpressionList) expr).getExpressions())\n .anyMatch(UnparsedLiteral.class::isInstance));\n }\n\n public static boolean canInitSafely(Expression<?>... expressions) {\n return Arrays.stream(expressions)\n .filter(Objects::nonNull)\n .noneMatch(SkriptUtil::hasUnparsedLiteral);\n }\n\n public static List<TriggerItem> getItemsFromNode(SectionNode node) {\n RetainingLogHandler log = SkriptLogger.startRetainingLog();\n try {\n return ScriptLoader.loadItems(node);\n } finally {\n SkriptReflection.printLog(log);\n ScriptLoader.deleteCurrentEvent();\n }\n }\n\n public static void clearSectionNode(SectionNode node) {\n List<Node> subNodes = new ArrayList<>();\n node.forEach(subNodes::add);\n subNodes.forEach(Node::remove);\n }\n\n public static File getCurrentScript() {\n Config currentScript = ScriptLoader.currentScript;\n return currentScript == null ? null : currentScript.getFile();\n }\n\n public static ClassInfo<?> getUserClassInfo(String name) {\n NonNullPair<String, Boolean> wordData = Utils.getEnglishPlural(name);\n\n ClassInfo<?> ci = Classes.getClassInfoNoError(wordData.getFirst());\n\n if (ci == null) {\n ci = Classes.getClassInfoFromUserInput(wordData.getFirst());\n }\n\n if (ci == null) {\n Skript.warning(String.format(\"'%s' is not a valid Skript type. Using 'object' instead.\", name));\n return Classes.getExactClassInfo(Object.class);\n }\n\n return ci;\n }\n\n public static NonNullPair<ClassInfo<?>, Boolean> getUserClassInfoAndPlural(String name) {\n NonNullPair<String, Boolean> wordData = Utils.getEnglishPlural(name);\n ClassInfo<?> ci = getUserClassInfo(name);\n\n return new NonNullPair<>(ci, wordData.getSecond());\n }\n\n public static String replaceUserInputPatterns(String name) {\n NonNullPair<String, Boolean> wordData = Utils.getEnglishPlural(name);\n ClassInfo<?> ci = getUserClassInfo(name);\n\n return Utils.toEnglishPlural(ci.getCodeName(), wordData.getSecond());\n }\n\n public static Function<Expression, Object> unwrapWithEvent(Event e) {\n return expr -> expr.isSingle() ? expr.getSingle(e) : expr.getArray(e);\n }\n}" ]
import ch.njol.skript.Skript; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.ExpressionType; import ch.njol.skript.lang.SkriptParser; import ch.njol.skript.lang.Variable; import ch.njol.skript.lang.function.Function; import ch.njol.skript.lang.function.FunctionEvent; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; import com.btk5h.skriptmirror.FunctionWrapper; import com.btk5h.skriptmirror.JavaType; import com.btk5h.skriptmirror.LibraryLoader; import com.btk5h.skriptmirror.skript.Consent; import com.btk5h.skriptmirror.util.SkriptReflection; import com.btk5h.skriptmirror.util.SkriptUtil; import org.bukkit.event.Event; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.*;
package com.btk5h.skriptmirror.skript.reflect; public class ExprProxy extends SimpleExpression<Object> { static { Skript.registerExpression(ExprProxy.class, Object.class, ExpressionType.COMBINED, "[a] [new] proxy [instance] of %javatypes% (using|from) %objects%"); } private Expression<JavaType> interfaces; private Variable<?> handler; @Override protected Object[] get(Event e) { Map<String, FunctionWrapper> handlers = new HashMap<>(); handler.variablesIterator(e) .forEachRemaining(pair -> { Object value = pair.getValue(); if (value instanceof FunctionWrapper) { handlers.put(pair.getKey(), ((FunctionWrapper) value)); } }); return new Object[]{ Proxy.newProxyInstance( LibraryLoader.getClassLoader(), Arrays.stream(interfaces.getArray(e)) .map(JavaType::getJavaClass) .filter(Class::isInterface) .toArray(Class[]::new), new VariableInvocationHandler(handlers) ) }; } private static class VariableInvocationHandler implements InvocationHandler { private final Map<String, FunctionWrapper> handlers; public VariableInvocationHandler(Map<String, FunctionWrapper> handlers) { this.handlers = handlers; } @Override public Object invoke(Object proxy, Method method, Object[] methodArgs) throws Throwable { FunctionWrapper functionWrapper = handlers.get(method.getName().toLowerCase()); if (functionWrapper == null) { return null; } Function<?> function = functionWrapper.getFunction(); Object[] functionArgs = functionWrapper.getArguments(); if (function == null) { return null; } if (methodArgs == null) { methodArgs = new Object[0]; } List<Object[]> params = new ArrayList<>(functionArgs.length + methodArgs.length + 1); Arrays.stream(functionArgs) .map(arg -> new Object[]{arg}) .forEach(params::add); params.add(new Object[]{proxy}); Arrays.stream(methodArgs) .map(arg -> new Object[]{arg}) .forEach(params::add); FunctionEvent functionEvent = new FunctionEvent(null); return function.execute( functionEvent, params.stream() .limit(SkriptReflection.getParameters(function).length) .toArray(Object[][]::new) ); } } @Override public boolean isSingle() { return true; } @Override public Class<?> getReturnType() { return Object.class; } @Override public String toString(Event e, boolean debug) { return String.format("proxy of %s from %s", interfaces.toString(e, debug), handler.toString(e, debug)); } @Override public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parseResult) {
if (!Consent.Feature.PROXIES.hasConsent(SkriptUtil.getCurrentScript())) {
5
Dynious/Biota
src/main/java/com/dynious/biota/command/CommandBiota.java
[ "public class BioSystem\n{\n private static final Random RANDOM = new Random();\n\n public final WeakReference<Chunk> chunkReference;\n private int tick = RANDOM.nextInt(Settings.TICKS_PER_BIOSYSTEM_UPDATE);\n\n /**\n * Stores the amount of plants in the chunk. Plant blocks can have different amounts 'plant value'.\n */\n private float biomass;\n\n /**\n * Stores the amount of nitrogen fixated by the plants in this chunk.\n */\n private float nitrogenFixation;\n\n /**\n * Phosphorus is used by plants for growth. Plants and animal waste will be turned into phosphates by bacteria when decomposed.\n * Phosphorus is usually the limiting factor in plant growth. It can be released slowly by weathering of rock but\n * can also be incorporated into rock. Bone meal has lots of phosphorus!\n *\n * 10 - 20 ppm normal\n * Normal Carbon:Phosphorus rate = 200:1 - 300:1\n */\n private float phosphorus;\n\n /**\n * Potassium is essential for plants and will affect plants greatly when there's not enough available in the soil.\n * Plants will take up more than needed for healthy growth if there's enough available. Works a lot like phosphorus.\n * Bone meal has no potassium. Potassium can be gained by mining rock.\n *\n * 150 - 250 ppm K normal.\n */\n private float potassium;\n\n /**\n * Nitrate is used by plants for growth. Plants and animal waste will be turned into ammonia by bacteria when decomposed.\n * This ammonia will be turned into nitrate by nitrifying bacteria. Nitrate can be removed from the ground and into\n * the atmosphere by denitrifying bacteria. Ammonia can be inserted in the ground from the atmosphere by nitrogen-fixing\n * soil bacteria.\n *\n * 5 - 10 ppm normal. 25+ ppm optimal\n */\n private float nitrogen;\n\n /**\n * Bacteria that decompose dead stuff. When there are not enough of these bacteria, the nutrients in dead plants\n * and animals will not fully be reinserted into the biosystem. The amount needed depends on the amount of plants\n * and animals in the chunk.\n */\n private float decomposingBacteria;\n\n /**\n * Nitrifying bacteria are needed to convert the ammonia created by the Decomposing Bacteria to Nitrate used by\n * plants to grow. When there are not enough of these bacteria the amount of nitrogen will Nitrate in the soil\n * will slowly decline, causing growth issues.\n */\n private float nitrifyingBacteria;\n\n /*\n Soil density: 1360 kg/m^3\n Around 768 dirt blocks per chunk (calculate this? biome dependant?) (16*16*3)\n 1044480 kg of dirt per chunk\n We assume all parts in soil weigh the same so: 1.04448 kg per millionth part (for ppm)\n 1 ppm ~= 1 kg\n */\n\n\n public BioSystem(Chunk chunk)\n {\n this(chunk, BiomeConfig.getRandomizedNutrientValuesForChunk(chunk));\n }\n\n private BioSystem(Chunk chunk ,float[] nutrients)\n {\n this(chunk, nutrients[0], nutrients[1], nutrients[2]);\n }\n\n public BioSystem(Chunk chunk, float phosphorus, float potassium, float nitrogen)\n {\n this(chunk, 0F, 0F, phosphorus, potassium, nitrogen, 0F, 0F);\n }\n\n private BioSystem(Chunk chunk, float biomass, float nitrogenFixation, float phosphorus, float potassium, float nitrogen, float decomposingBacteria, float nitrifyingBacteria)\n {\n this.chunkReference = new WeakReference<Chunk>(chunk);\n this.biomass = biomass;\n this.nitrogenFixation = nitrogenFixation;\n this.phosphorus = phosphorus;\n this.potassium = potassium;\n this.nitrogen = nitrogen;\n this.decomposingBacteria = decomposingBacteria;\n this.nitrifyingBacteria = nitrifyingBacteria;\n }\n\n public void addBiomass(float amount)\n {\n setChunkModified();\n this.biomass += amount;\n }\n\n public void onGrowth(float bioMassIncrease, boolean addBiomass)\n {\n if (addBiomass)\n addBiomass(bioMassIncrease);\n phosphorus -= bioMassIncrease*Settings.BIOMASS_PHOSPHORUS_RATE;\n potassium -= bioMassIncrease*Settings.BIOMASS_POTASSIUM_RATE;\n nitrogen -= bioMassIncrease*Settings.BIOMASS_NITROGEN_RATE;\n setChunkModified();\n }\n\n public void setBiomass(float amount)\n {\n setChunkModified();\n biomass = amount;\n setStableBacteriaValues();\n }\n\n public float getBiomass()\n {\n return biomass;\n }\n\n public float getNitrogenFixation()\n {\n return nitrogenFixation;\n }\n\n public void addNitrogenFixation(float amount)\n {\n setChunkModified();\n this.nitrogenFixation += amount;\n }\n\n public float getPhosphorus()\n {\n return phosphorus;\n }\n\n public float getPotassium()\n {\n return potassium;\n }\n\n public float getNitrogen()\n {\n return nitrogen;\n }\n\n public float getDecomposingBacteria()\n {\n return decomposingBacteria;\n }\n\n public float getNitrifyingBacteria()\n {\n return nitrifyingBacteria;\n }\n\n public void setNitrogenFixation(float nitrogenFixation)\n {\n this.nitrogenFixation = nitrogenFixation;\n }\n\n public void setPhosphorus(float phosphorus)\n {\n this.phosphorus = phosphorus;\n }\n\n public void setPotassium(float potassium)\n {\n this.potassium = potassium;\n }\n\n public void setNitrogen(float nitrogen)\n {\n this.nitrogen = nitrogen;\n }\n\n public void setStableBacteriaValues()\n {\n decomposingBacteria = biomass + RANDOM.nextFloat()*(Settings.BACTERIA_GROWTH_MAX*biomass - biomass);\n nitrifyingBacteria = biomass + RANDOM.nextFloat()*(Settings.BACTERIA_GROWTH_MAX*biomass - biomass);\n }\n\n public void setStableBacteriaValuesNearChunk()\n {\n setStableBacteriaValues();\n Chunk chunk = chunkReference.get();\n if (chunk != null)\n {\n getAndStabilizeChunk(chunk.worldObj, chunk.xPosition + 1, chunk.zPosition + 1);\n getAndStabilizeChunk(chunk.worldObj, chunk.xPosition, chunk.zPosition + 1);\n getAndStabilizeChunk(chunk.worldObj, chunk.xPosition + 1, chunk.zPosition);\n getAndStabilizeChunk(chunk.worldObj, chunk.xPosition - 1, chunk.zPosition);\n getAndStabilizeChunk(chunk.worldObj, chunk.xPosition, chunk.zPosition - 1);\n getAndStabilizeChunk(chunk.worldObj, chunk.xPosition - 1, chunk.zPosition - 1);\n getAndStabilizeChunk(chunk.worldObj, chunk.xPosition - 1, chunk.zPosition + 1);\n getAndStabilizeChunk(chunk.worldObj, chunk.xPosition + 1, chunk.zPosition - 1);\n }\n }\n\n public void getAndStabilizeChunk(World world, int x, int z)\n {\n if (world.chunkExists(x, z))\n {\n BioSystem bioSystem = BioSystemHandler.getBioSystem(world, world.getChunkFromChunkCoords(x, z));\n if (bioSystem != null)\n bioSystem.setStableBacteriaValues();\n }\n\n }\n\n public void update()\n {\n tick++;\n\n if (tick % Settings.TICKS_PER_BIOSYSTEM_UPDATE == 0)\n {\n setChunkModified();\n Chunk chunk = chunkReference.get();\n\n if (chunk != null)\n {\n if (chunk.xPosition == 0 && chunk.zPosition == 0)\n {\n System.out.println(String.format(\"PRE: Biomass: %f, Nitrogen Fixation: %f, Phosphorus: %f, Potassium: %f, Nitrogen %f, Decomposing Bacteria: %f, Nirtifying Bacteria %f\", this.getBiomass(), this.getNitrogenFixation(), this.getPhosphorus(), this.getPotassium(), this.getNitrogen(), this.getDecomposingBacteria(), this.getNitrifyingBacteria()));\n }\n //TODO: BALANCE! BIOMASS INCREASE HAS A VERY DRAMATIC EFFECT, NUTRIENT USAGE TOO HIGH.\n //Bacteria calculations\n float biomassBacteriaRate = biomass / decomposingBacteria;\n if (biomassBacteriaRate > Settings.BACTERIA_GROWTH_MAX)\n {\n decomposingBacteria += decomposingBacteria * Settings.BACTERIA_CHANGE_RATE;\n }\n else if (biomassBacteriaRate < Settings.BACTERIA_DEATH)\n {\n decomposingBacteria -= (1-biomassBacteriaRate)*decomposingBacteria * Settings.BACTERIA_CHANGE_RATE;\n }\n\n float nirtifyingBacteriaRate = (Math.min(biomass, decomposingBacteria) + nitrogenFixation) / nitrifyingBacteria;\n if (nirtifyingBacteriaRate > Settings.BACTERIA_GROWTH_MAX)\n {\n nitrifyingBacteria += nitrifyingBacteria * Settings.BACTERIA_CHANGE_RATE;\n }\n else if (nirtifyingBacteriaRate < Settings.BACTERIA_DEATH)\n {\n nitrifyingBacteria -= (1-nirtifyingBacteriaRate)*nitrifyingBacteria * Settings.BACTERIA_CHANGE_RATE;\n }\n\n //Nutrient calculations\n //TODO: figure out good change rates\n phosphorus += Math.min(biomass, decomposingBacteria) * Settings.PHOSPHORUS_CHANGE_RATE;\n phosphorus -= biomass * Settings.PHOSPHORUS_CHANGE_RATE;\n phosphorus = Math.max(0, phosphorus);\n\n potassium += Math.min(biomass, decomposingBacteria) * Settings.POTASSIUM_CHANGE_RATE;\n potassium -= biomass * Settings.POTASSIUM_CHANGE_RATE;\n potassium = Math.max(0, potassium);\n\n //TODO: nitrogen fixation should be calculated diffently (should not be dependant on nitrogen change rate in plants)\n nitrogen += Math.min(Math.min(biomass, decomposingBacteria) + nitrogenFixation, nitrifyingBacteria) * Settings.NITROGEN_CHANGE_RATE;\n nitrogen -= biomass * Settings.NITROGEN_CHANGE_RATE;\n nitrogen = Math.max(0, nitrogen);\n\n //Spread BioSystem stuff to nearby chunks\n spreadToChunk(chunk, chunk.xPosition - 1, chunk.zPosition);\n spreadToChunk(chunk, chunk.xPosition + 1, chunk.zPosition);\n spreadToChunk(chunk, chunk.xPosition, chunk.zPosition - 1);\n spreadToChunk(chunk, chunk.xPosition, chunk.zPosition + 1);\n\n if (chunk.xPosition == 0 && chunk.zPosition == 0)\n {\n System.out.println(String.format(\"SPREAD: Biomass: %f, Nitrogen Fixation: %f, Phosphorus: %f, Potassium: %f, Nitrogen %f, Decomposing Bacteria: %f, Nirtifying Bacteria %f\", this.getBiomass(), this.getNitrogenFixation(), this.getPhosphorus(), this.getPotassium(), this.getNitrogen(), this.getDecomposingBacteria(), this.getNitrifyingBacteria()));\n }\n\n //Send the chunk biomass changes to all clients watching this chunk\n NetworkHandler.INSTANCE.sendToPlayersWatchingChunk(new MessageBioSystemUpdate(this), (WorldServer) chunk.worldObj, chunk.xPosition, chunk.zPosition);\n }\n }\n }\n\n private void spreadToChunk(Chunk chunk, int xPos, int zPos)\n {\n if (chunk.worldObj.chunkExists(xPos, zPos))\n {\n Chunk chunk1 = chunk.worldObj.getChunkFromChunkCoords(xPos, zPos);\n BioSystem bioSystem = BioSystemHandler.getBioSystem(chunk.worldObj, chunk1);\n if (bioSystem != null)\n spread(bioSystem);\n else\n Biota.logger.warn(String.format(\"Couldn't find BioSystem at: %d %d\", xPos, zPos));\n }\n }\n\n private void spread(BioSystem bioSystem)\n {\n float dP = this.phosphorus - bioSystem.phosphorus;\n float dK = this.potassium - bioSystem.potassium;\n float dN = this.nitrogen - bioSystem.nitrogen;\n float dDB = this.decomposingBacteria - bioSystem.decomposingBacteria;\n float dNB = this.nitrifyingBacteria - bioSystem.nitrifyingBacteria;\n\n float spreadP = Settings.BIOSYSTEM_SPREAD_RATE *dP;\n float spreadK = Settings.BIOSYSTEM_SPREAD_RATE *dK;\n float spreadN = Settings.BIOSYSTEM_SPREAD_RATE *dN;\n float spreadDB = Settings.BIOSYSTEM_SPREAD_RATE *dDB;\n float spreadNB = Settings.BIOSYSTEM_SPREAD_RATE *dNB;\n\n this.phosphorus -= spreadP;\n bioSystem.phosphorus += spreadP;\n this.potassium -= spreadK;\n bioSystem.potassium += spreadK;\n this.nitrogen -= spreadN;\n bioSystem.nitrogen += spreadN;\n this.decomposingBacteria -= spreadDB;\n bioSystem.decomposingBacteria += spreadDB;\n this.nitrifyingBacteria -= spreadNB;\n bioSystem.nitrifyingBacteria += spreadNB;\n }\n\n public void setChunkModified()\n {\n Chunk chunk1 = chunkReference.get();\n if (chunk1 != null)\n {\n chunk1.isModified = true;\n }\n }\n\n public static BioSystem loadFromNBT(Chunk chunk, NBTTagCompound compound)\n {\n float biomass = compound.getFloat(\"biomass\");\n float nitrogenFixation = compound.getFloat(\"nitrogenFixation\");\n float phosphorus = compound.getFloat(\"phosphorus\");\n float potassium = compound.getFloat(\"potassium\");\n float nitrogen = compound.getFloat(\"nitrogen\");\n float decomposingBacteria = compound.getFloat(\"decomposingBacteria\");\n float nitrifyingBacteria = compound.getFloat(\"nitrifyingBacteria\");\n\n return new BioSystem(chunk, biomass, nitrogenFixation, phosphorus, potassium, nitrogen, decomposingBacteria, nitrifyingBacteria);\n }\n\n public void saveToNBT(NBTTagCompound compound)\n {\n compound.setFloat(\"biomass\", biomass);\n compound.setFloat(\"nitrogenFixation\", nitrogenFixation);\n compound.setFloat(\"phosphorus\", phosphorus);\n compound.setFloat(\"potassium\", potassium);\n compound.setFloat(\"nitrogen\", nitrogen);\n compound.setFloat(\"decomposingBacteria\", decomposingBacteria);\n compound.setFloat(\"nitrifyingBacteria\", nitrifyingBacteria);\n }\n\n @Override\n public String toString()\n {\n StringBuilder result = new StringBuilder();\n String NEW_LINE = System.getProperty(\"line.separator\");\n\n result.append(this.getClass().getName());\n result.append(\" Object {\");\n result.append(NEW_LINE);\n result.append(\" biomass: \");\n result.append(biomass);\n result.append(NEW_LINE);\n result.append(\" nitrogen fixation: \");\n result.append(nitrogenFixation);\n result.append(NEW_LINE);\n result.append(\" phosphorus: \");\n result.append(phosphorus);\n result.append(NEW_LINE);\n result.append(\" potassium: \");\n result.append(potassium);\n result.append(NEW_LINE);\n result.append(\" nitrogen: \");\n result.append(nitrogen);\n result.append(NEW_LINE);\n result.append(\" decomposingBacteria: \");\n result.append(decomposingBacteria);\n result.append(NEW_LINE);\n result.append(\" nitrifyingBacteria: \");\n result.append(nitrifyingBacteria);\n result.append(NEW_LINE);\n result.append(\"}\");\n\n return result.toString();\n }\n}", "public class BioSystemHandler\n{\n private static WeakHashMap<World, BioSystemHandler> handlers = new WeakHashMap<World, BioSystemHandler>();\n\n private Map<Chunk, BioSystem> bioSystemMap = new WeakHashMap<Chunk, BioSystem>();\n public TObjectFloatMap<ChunkCoords> biomassChangeMap = new TObjectFloatHashMap<ChunkCoords>();\n public TObjectFloatMap<ChunkCoords> nitrogenFixationChangeMap = new TObjectFloatHashMap<ChunkCoords>();\n public List<BioSystem> stabilizeList = new ArrayList<BioSystem>();\n\n public static void onChunkLoaded(World world, Chunk chunk, NBTTagCompound compound)\n {\n assert chunk != null;\n\n BioSystemHandler handler;\n if (!handlers.containsKey(world))\n {\n handler = new BioSystemHandler();\n handlers.put(world, handler);\n }\n else\n handler = handlers.get(world);\n\n BioSystem bioSystem;\n\n if (compound == null || compound.hasNoTags())\n {\n if (handler.bioSystemMap.containsKey(chunk))\n {\n //We already have this chunk loaded, but apparently it changed, we'll need to recheck it, but keep the nutrients for minimal loss\n BioSystem bioSystem1 = handler.bioSystemMap.remove(chunk);\n bioSystem = new BioSystem(chunk, bioSystem1.getPhosphorus(), bioSystem1.getPotassium(), bioSystem1.getNitrogen());\n BioSystemInitThread.addBioSystem(bioSystem);\n }\n else\n {\n //Existing chunk, but new BioSystem!\n bioSystem = new BioSystem(chunk);\n BioSystemInitThread.addBioSystem(bioSystem);\n }\n }\n else\n {\n bioSystem = BioSystem.loadFromNBT(chunk, compound);\n }\n\n handler.bioSystemMap.put(chunk, bioSystem);\n }\n\n public static void onChunkLoaded(World world, Chunk chunk)\n {\n BioSystemHandler handler;\n if (!handlers.containsKey(world))\n {\n handler = new BioSystemHandler();\n handlers.put(world, handler);\n }\n else\n handler = handlers.get(world);\n\n if (!handler.bioSystemMap.containsKey(chunk))\n handler.bioSystemMap.put(chunk, new BioSystem(chunk));\n }\n\n public static void onChunkUnload(World world, Chunk chunk)\n {\n BioSystemHandler handler = handlers.get(world);\n if (handler != null)\n handler.bioSystemMap.remove(chunk);\n }\n\n public static BioSystemHandler get(World world)\n {\n return handlers.get(world);\n }\n\n public static BioSystem getBioSystem(World world, Chunk chunk)\n {\n BioSystemHandler handler = handlers.get(world);\n if (handler != null)\n return handler.getBioSystem(chunk);\n return null;\n }\n\n public BioSystem getBioSystem(Chunk chunk)\n {\n return bioSystemMap.get(chunk);\n }\n\n public Iterator<BioSystem> iterator()\n {\n return bioSystemMap.values().iterator();\n }\n\n public void update()\n {\n biomassChangeMap.forEachEntry(BiomassProcedure.INSTANCE);\n biomassChangeMap.clear();\n\n nitrogenFixationChangeMap.forEachEntry(NitrogenFixationProcedure.INSTANCE);\n nitrogenFixationChangeMap.clear();\n\n if (!stabilizeList.isEmpty())\n {\n List<BioSystem> copiedList = new ArrayList<BioSystem>(stabilizeList);\n stabilizeList.clear();\n for (BioSystem bioSystem : copiedList)\n bioSystem.setStableBacteriaValuesNearChunk();\n }\n\n Iterator<BioSystem> iterator = iterator();\n while (iterator.hasNext())\n {\n iterator.next().update();\n }\n }\n\n public static class ChunkCoords\n {\n public World world;\n public int x, z;\n\n public ChunkCoords(World world, int x, int z)\n {\n this.world = world;\n this.x = x;\n this.z = z;\n }\n\n @Override\n public boolean equals(Object o)\n {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n ChunkCoords that = (ChunkCoords) o;\n\n if (x != that.x) return false;\n if (z != that.z) return false;\n if (!world.equals(that.world)) return false;\n\n return true;\n }\n\n @Override\n public int hashCode()\n {\n int result = world.hashCode();\n result = 31 * result + x;\n result = 31 * result + z;\n return result;\n }\n }\n\n private static class BiomassProcedure implements TObjectFloatProcedure<ChunkCoords>\n {\n public static final BiomassProcedure INSTANCE = new BiomassProcedure();\n\n private BiomassProcedure()\n {\n }\n\n @Override\n public boolean execute(ChunkCoords coords, float amount)\n {\n Chunk chunk = coords.world.getChunkFromChunkCoords(coords.x, coords.z);\n BioSystem bioSystem = getBioSystem(coords.world, chunk);\n if (bioSystem != null)\n {\n bioSystem.addBiomass(amount);\n }\n else\n {\n Biota.logger.warn(String.format(\"Couldn't find BioSystem at: %d %d\", coords.x, coords.z));\n }\n return true;\n }\n }\n\n private static class NitrogenFixationProcedure implements TObjectFloatProcedure<ChunkCoords>\n {\n public static final NitrogenFixationProcedure INSTANCE = new NitrogenFixationProcedure();\n\n private NitrogenFixationProcedure()\n {\n }\n\n @Override\n public boolean execute(ChunkCoords coords, float amount)\n {\n Chunk chunk = coords.world.getChunkFromChunkCoords(coords.x, coords.z);\n BioSystem bioSystem = getBioSystem(coords.world, chunk);\n if (bioSystem != null)\n {\n bioSystem.addNitrogenFixation(amount);\n }\n else\n {\n Biota.logger.warn(String.format(\"Couldn't find BioSystem at: %d %d\", coords.x, coords.z));\n }\n return true;\n }\n }\n}", "public class BioSystemInitThread implements Callable\n{\n private static ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());\n\n private final BioSystem bioSystem;\n\n public BioSystemInitThread(BioSystem bioSystem)\n {\n this.bioSystem = bioSystem;\n }\n\n @Override\n public Object call()\n {\n float biomass = 0F;\n Chunk chunk = bioSystem.chunkReference.get();\n\n if (chunk != null)\n {\n for (int x = 0; x < 16; x++)\n {\n for (int y = 0; y < 256; y++)\n {\n for (int z = 0; z < 16; z++)\n {\n Block block = chunk.getBlock(x, y, z);\n if (block instanceof IPlant)\n {\n int meta = chunk.getBlockMetadata(x, y, z);\n biomass += PlantConfig.getPlantBlockBiomassValue(block, meta);\n }\n }\n }\n }\n bioSystem.setBiomass(biomass);\n }\n\n return null;\n }\n\n public static void addBioSystem(BioSystem bioSystem)\n {\n listeningExecutorService.submit(new BioSystemInitThread(bioSystem));\n }\n}", "public class Commands\n{\n public static final String BIOTA = \"biota\";\n public static final String HELP = \"help\";\n public static final String GET_NUTRIENTS = \"getNutrients\";\n public static final String SET_NUTRIENTS = \"setNutrients\";\n public static final String GET_BIOSYSTEM = \"getBioSystem\";\n public static final String RECALCULATE_BIOMASS = \"recalculateBiomass\";\n}", "public class NetworkHandler\n{\n public static final SimpleNetworkWrapperExtension INSTANCE = new SimpleNetworkWrapperExtension(Reference.MOD_ID.toLowerCase());\n\n public static void init()\n {\n INSTANCE.registerMessage(MessageBioSystemUpdate.class, MessageBioSystemUpdate.class, 0, Side.CLIENT);\n }\n}", "public class MessageBioSystemUpdate implements IMessage, IMessageHandler<MessageBioSystemUpdate, IMessage>\n{\n int dimensionId, x, z;\n float phosphorus, potassium, nitrogen;\n\n public MessageBioSystemUpdate()\n {\n }\n\n public MessageBioSystemUpdate(BioSystem bioSystem)\n {\n Chunk chunk = bioSystem.chunkReference.get();\n if (chunk != null)\n {\n dimensionId = chunk.worldObj.provider.dimensionId;\n x = chunk.xPosition;\n z = chunk.zPosition;\n phosphorus = bioSystem.getPhosphorus();\n potassium = bioSystem.getPotassium();\n nitrogen = bioSystem.getNitrogen();\n }\n }\n\n @Override\n public void fromBytes(ByteBuf buf)\n {\n dimensionId = buf.readInt();\n x = buf.readInt();\n z = buf.readInt();\n phosphorus = buf.readFloat();\n potassium = buf.readFloat();\n nitrogen = buf.readFloat();\n }\n\n @Override\n public void toBytes(ByteBuf buf)\n {\n buf.writeInt(dimensionId);\n buf.writeInt(x);\n buf.writeInt(z);\n buf.writeFloat(phosphorus);\n buf.writeFloat(potassium);\n buf.writeFloat(nitrogen);\n }\n\n @Override\n public IMessage onMessage(MessageBioSystemUpdate message, MessageContext ctx)\n {\n //World world = DimensionManager.getWorld(message.dimensionId);\n Chunk chunk = Minecraft.getMinecraft().theWorld.getChunkFromChunkCoords(message.x, message.z);\n ClientBioSystem bioSystem = new ClientBioSystem(message.phosphorus, message.potassium, message.nitrogen);\n ClientBioSystemHandler.bioSystemMap.put(chunk, bioSystem);\n\n //Re-render whole chunk to update colors\n Minecraft.getMinecraft().theWorld.markBlockRangeForRenderUpdate((message.x << 4) + 1, 0, (message.z << 4) + 1, (message.x << 4) + 14, 256, (message.z << 4) + 14);\n\n return null;\n }\n}" ]
import com.dynious.biota.biosystem.BioSystem; import com.dynious.biota.biosystem.BioSystemHandler; import com.dynious.biota.biosystem.BioSystemInitThread; import com.dynious.biota.lib.Commands; import com.dynious.biota.network.NetworkHandler; import com.dynious.biota.network.message.MessageBioSystemUpdate; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import java.util.List;
package com.dynious.biota.command; public class CommandBiota extends CommandBase { @Override public String getCommandName() { return Commands.BIOTA; } @Override public int getRequiredPermissionLevel() { return 2; } @Override public String getCommandUsage(ICommandSender icommandsender) { return "/" + getCommandName() + " " + Commands.HELP; } @Override public void processCommand(ICommandSender icommandsender, String[] args) { if (args.length > 0) { String commandName = args[0]; if (commandName.equalsIgnoreCase(Commands.HELP)) { //Halp } else if (commandName.equalsIgnoreCase(Commands.GET_NUTRIENTS)) { World world = icommandsender.getEntityWorld(); Chunk chunk = world.getChunkFromBlockCoords(icommandsender.getPlayerCoordinates().posX, icommandsender.getPlayerCoordinates().posZ); BioSystem bioSystem = BioSystemHandler.getBioSystem(world, chunk); if (bioSystem != null) { icommandsender.addChatMessage(new ChatComponentText(String.format("Phosphorus: %f, Potassium: %f, Nitrogen %f", bioSystem.getPhosphorus(), bioSystem.getPotassium(), bioSystem.getNitrogen()))); } } else if (commandName.equalsIgnoreCase(Commands.SET_NUTRIENTS)) { if (args.length > 3) { World world = icommandsender.getEntityWorld(); Chunk chunk = world.getChunkFromBlockCoords(icommandsender.getPlayerCoordinates().posX, icommandsender.getPlayerCoordinates().posZ); BioSystem bioSystem = BioSystemHandler.getBioSystem(world, chunk); if (bioSystem != null) { bioSystem.setPhosphorus((float) parseDouble(icommandsender, args[1])); bioSystem.setPotassium((float) parseDouble(icommandsender, args[2])); bioSystem.setNitrogen((float) parseDouble(icommandsender, args[3]));
NetworkHandler.INSTANCE.sendToPlayersWatchingChunk(new MessageBioSystemUpdate(bioSystem), (WorldServer) world, chunk.xPosition, chunk.zPosition);
4
mjuhasz/BDSup2Sub
src/main/java/bdsup2sub/supstream/dvd/IfoParser.java
[ "public class Palette {\n /** Number of palette entries */\n private final int size;\n /** Byte buffer for RED info */\n private final byte[] r;\n /** Byte buffer for GREEN info */\n private final byte[] g;\n /** Byte buffer for BLUE info */\n private final byte[] b;\n /** Byte buffer for alpha info */\n private final byte[] a;\n /** Byte buffer for Y (luminance) info */\n private final byte[] y;\n /** Byte buffer for Cb (chrominance blue) info */\n private final byte[] cb;\n /** Byte buffer for Cr (chrominance red) info */\n private final byte[] cr;\n /** Use BT.601 color model instead of BT.709 */\n private final boolean useBT601;\n\n /**\n * Initializes palette with transparent black (RGBA: 0x00000000)\n * @param size Number of palette entries\n */\n public Palette(int size, boolean useBT601) {\n this.size = size;\n this.useBT601 = useBT601;\n r = new byte[size];\n g = new byte[size];\n b = new byte[size];\n a = new byte[size];\n y = new byte[size];\n cb = new byte[size];\n cr = new byte[size];\n\n // set at least all alpha values to invisible\n int[] yCbCr = RGB2YCbCr(0, 0, 0, useBT601);\n for (int i=0; i < size; i++) {\n a[i] = 0;\n r[i] = 0;\n g[i] = 0;\n b[i] = 0;\n y[i] = (byte)yCbCr[0];\n cb[i] = (byte)yCbCr[1];\n cr[i] = (byte)yCbCr[2];\n }\n }\n\n /**\n * Initializes a palette with transparent black (RGBA: 0x00000000)\n */\n public Palette(int size) {\n this(size, false);\n }\n\n public Palette(byte[] red, byte[] green, byte[] blue, byte[] alpha, boolean useBT601) {\n size = red.length;\n this.useBT601 = useBT601;\n r = new byte[size];\n g = new byte[size];\n b = new byte[size];\n a = new byte[size];\n y = new byte[size];\n cb = new byte[size];\n cr = new byte[size];\n\n int yCbCr[];\n for (int i=0; i<size; i++) {\n a[i] = alpha[i];\n r[i] = red[i];\n g[i] = green[i];\n b[i] = blue[i];\n yCbCr = RGB2YCbCr(r[i]&0xff, g[i]&0xff, b[i]&0xff, useBT601);\n y[i] = (byte)yCbCr[0];\n cb[i] = (byte)yCbCr[1];\n cr[i] = (byte)yCbCr[2];\n }\n }\n\n /**\n * Constructs a palette from red, green blue and alpha buffers using BT.709\n */\n public Palette(byte[] red, byte[] green, byte[] blue, byte[] alpha) {\n this(red, green, blue, alpha, false);\n }\n\n public Palette(Palette palette) {\n size = palette.getSize();\n useBT601 = palette.usesBT601();\n r = new byte[size];\n g = new byte[size];\n b = new byte[size];\n a = new byte[size];\n y = new byte[size];\n cb = new byte[size];\n cr = new byte[size];\n\n for (int i = 0; i < size; i++) {\n a[i] = palette.a[i];\n r[i] = palette.r[i];\n g[i] = palette.g[i];\n b[i] = palette.b[i];\n y[i] = palette.y[i];\n cb[i] = palette.cb[i];\n cr[i] = palette.cr[i];\n }\n }\n\n public ColorModel getColorModel() {\n return new IndexColorModel(8, size, r, g, b, a);\n }\n\n public void setColor(int index, Color c) {\n setRGB(index, c.getRed(), c.getGreen(), c.getBlue());\n setAlpha(index, c.getAlpha());\n }\n\n public void setARGB(int index, int c) {\n setColor(index, new Color(c, true));\n }\n\n public Color getColor(int index) {\n return new Color(r[index] & 0xff, g[index] & 0xff, b[index] & 0xff, a[index] & 0xff);\n }\n\n public int getARGB(int index) {\n return ((a[index] & 0xff) << 24) | ((r[index] & 0xff) << 16) | (( g[index] & 0xff) << 8) | (b[index] & 0xff) ;\n }\n\n public void setRGB(int index, int red, int green, int blue) {\n r[index] = (byte)red;\n g[index] = (byte)green;\n b[index] = (byte)blue;\n\n int yCbCr[] = RGB2YCbCr(red, green, blue, useBT601);\n y[index] = (byte)yCbCr[0];\n cb[index] = (byte)yCbCr[1];\n cr[index] = (byte)yCbCr[2];\n }\n\n public void setYCbCr(int index, int yn, int cbn, int crn) {\n y[index] = (byte)yn;\n cb[index] = (byte)cbn;\n cr[index] = (byte)crn;\n\n int rgb[] = ColorSpaceUtils.YCbCr2RGB(yn, cbn, crn, useBT601);\n r[index] = (byte)rgb[0];\n g[index] = (byte)rgb[1];\n b[index] = (byte)rgb[2];\n }\n\n public void setAlpha(int index, int alpha) {\n a[index] = (byte)alpha;\n }\n\n public int getAlpha(int index) {\n return a[index] & 0xff;\n }\n\n public byte[] getAlpha() {\n return Arrays.copyOf(a, a.length);\n }\n\n public int[] getRGB(int index) {\n int rgb[] = new int[3];\n rgb[0] = r[index] & 0xff;\n rgb[1] = g[index] & 0xff;\n rgb[2] = b[index] & 0xff;\n return rgb;\n }\n\n public int[] getYCbCr(final int index) {\n int yCbCr[] = new int[3];\n yCbCr[0] = y[index] & 0xff;\n yCbCr[1] = cb[index] & 0xff;\n yCbCr[2] = cr[index] & 0xff;\n return yCbCr;\n }\n\n public byte[] getR() {\n return Arrays.copyOf(r, r.length);\n }\n\n public byte[] getG() {\n return Arrays.copyOf(g, g.length);\n }\n\n public byte[] getB() {\n return Arrays.copyOf(b, b.length);\n }\n\n public byte[] getY() {\n return Arrays.copyOf(y, y.length);\n }\n\n public byte[] getCb() {\n return Arrays.copyOf(cb, cb.length);\n }\n\n public byte[] getCr() {\n return Arrays.copyOf(cr, cr.length);\n }\n\n public int getSize() {\n return size;\n }\n\n public int getIndexOfMostTransparentPaletteEntry() {\n int transpIdx = 0;\n int minAlpha = 0x100;\n for (int i = 0; i < size; i++ ) {\n if ((a[i] & 0xff) < minAlpha) {\n minAlpha = a[i] & 0xff;\n transpIdx = i;\n if (minAlpha == 0) {\n break;\n }\n }\n }\n return transpIdx;\n }\n\n public boolean usesBT601() {\n return useBT601;\n }\n}", "public class CoreException extends Exception {\n\n public CoreException() {\n }\n\n public CoreException(String s) {\n super(s);\n }\n}", "public final class Logger {\n\n private static final Configuration configuration = Configuration.getInstance();\n private static final Logger INSTANCE = new Logger();\n\n private int errorCount;\n private int warningCount;\n\n private MainFrameView mainFrame;\n\n private Logger() {\n }\n\n public static Logger getInstance() {\n return INSTANCE;\n }\n\n public void warn(String message) {\n warningCount++;\n final String msg = \"WARNING: \" + message;\n if (mainFrame != null) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n mainFrame.printToConsole(msg);\n }\n });\n } else {\n System.out.print(msg);\n }\n }\n\n public void error(String message) {\n errorCount++;\n final String msg = \"ERROR: \" + message;\n if (mainFrame != null) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n mainFrame.printToConsole(msg);\n }\n });\n } else {\n System.out.print(msg);\n }\n }\n\n public void trace(String message) {\n final String msg = message;\n if (configuration.isVerbose()) {\n if (mainFrame != null) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n mainFrame.printToConsole(msg);\n }\n });\n } else {\n System.out.print(msg);\n }\n }\n }\n\n public void info(String message) {\n final String msg = message;\n if (mainFrame != null) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n mainFrame.printToConsole(msg);\n }\n });\n } else {\n System.out.print(msg);\n }\n }\n\n public int getErrorCount() {\n return errorCount;\n }\n\n public void resetErrorCounter() {\n errorCount = 0;\n }\n\n public int getWarningCount() {\n return warningCount;\n }\n\n public void resetWarningCounter() {\n warningCount = 0;\n }\n\n public void printWarningsAndErrorsAndResetCounters() {\n if (warningCount + errorCount > 0) {\n String message = \"\";\n if (warningCount > 0) {\n if (warningCount == 1) {\n message += warningCount + \" warning\";\n } else {\n message += warningCount + \" warnings\";\n }\n }\n if (warningCount > 0 && errorCount > 0) {\n message += \" and \";\n }\n if (errorCount > 0) {\n if (errorCount == 1) {\n message = errorCount + \" error\";\n } else {\n message = errorCount + \" errors\";\n }\n }\n if (warningCount + errorCount < 3) {\n message = \"There was \" + message;\n } else {\n message = \"There were \" + message;\n }\n System.out.println(message);\n }\n resetWarningCounter();\n resetErrorCounter();\n }\n\n public void setMainFrame(MainFrameView mainFrame) {\n this.mainFrame = mainFrame;\n }\n}", "public class FileBuffer {\n\n /** Size of the buffer in memory */\n private static final int BUFFERSIZE = 1024*1024; /* 1MB */\n /** Buffer in memory */\n private byte[] buf;\n /** File name of the input file */\n private String filename;\n /** File input stream of the input file */\n private FileInputStream fi;\n /** File channel of the input file */\n private FileChannel fc;\n /** Current offset in file = start of memory buffer */\n private long offset;\n /** Last valid offset that is stored in internal buffer */\n private long offsetEnd;\n /** Length of file */\n private long length;\n\n public FileBuffer(final String filename) throws FileBufferException {\n this.filename = filename;\n length = new File(filename).length();\n if (length < BUFFERSIZE) {\n buf = new byte[(int)length];\n } else {\n buf = new byte[BUFFERSIZE];\n }\n try {\n fi = new FileInputStream(filename);\n fc = fi.getChannel();\n offset = 0;\n readBuffer(offset);\n } catch (FileNotFoundException ex) {\n throw new FileBufferException(\"File '\" + filename + \"' not found\");\n }\n }\n\n /**\n * Move offset, read file to memory buffer.\n * @param offset New file offset\n * @throws FileBufferException\n */\n private void readBuffer(long offset) throws FileBufferException {\n try {\n this.offset = offset;\n fc.position(offset);\n long l = length - offset;\n int numRead;\n if (l < 0) {\n throw new FileBufferException(\"Offset \" + offset + \" out of bounds for file \" + filename);\n }\n if (l < buf.length) {\n numRead = fi.read(buf, 0, (int)l);\n } else {\n numRead = fi.read(buf, 0, buf.length);\n }\n offsetEnd = offset + numRead - 1; // points to last valid position\n } catch (IOException ex) {\n throw new FileBufferException(\"IO error at offset +\" + offset + \" of file '\" + filename + \"'\");\n } catch (IllegalArgumentException ex) {\n throw new FileBufferException(\"IO error at offset +\" + offset + \" of file '\" + filename + \"'\");\n }\n }\n\n /**\n * Read one byte from the buffer.\n * @param offset File offset\n * @return Byte read from the buffer\n * @throws FileBufferException\n */\n public int getByte(long offset) throws FileBufferException {\n if ((offset < this.offset) || (offset > offsetEnd)) {\n readBuffer(offset);\n }\n return buf[(int)(offset - this.offset)] & 0xff;\n }\n\n /**\n * Read one (big endian) 16bit word from the buffer.\n * @param offset File offset\n * @return Word read from the buffer\n * @throws FileBufferException\n */\n public int getWord(long offset) throws FileBufferException {\n if ((offset < this.offset) || ((offset+1) > offsetEnd)) {\n readBuffer(offset);\n }\n int idx = (int)(offset - this.offset);\n return (buf[idx+1] & 0xff) | ((buf[idx] & 0xff) << 8);\n }\n\n /**\n * Read one (little endian) 16bit word from the buffer.\n * @param offset File offset\n * @return Word read from the buffer\n * @throws FileBufferException\n */\n public int getWordLE(long offset) throws FileBufferException {\n if ((offset < this.offset) || ((offset + 1) > offsetEnd)) {\n readBuffer(offset);\n }\n int idx = (int)(offset - this.offset);\n return (buf[idx] & 0xff) | ((buf[idx+1] & 0xff) << 8);\n }\n\n /**\n * Read one (big endian) 32bit dword from the buffer.\n * @param offset File offset\n * @return Dword read from the buffer\n * @throws FileBufferException\n */\n public int getDWord(long offset) throws FileBufferException {\n if ((offset < this.offset) || ((offset+3) > offsetEnd)) {\n readBuffer(offset);\n }\n int idx = (int)(offset - this.offset);\n return (buf[idx+3] & 0xff) | ((buf[idx + 2] & 0xff) << 8)\n | ((buf[idx+1] & 0xff) << 16) | ((buf[idx] & 0xff) << 24);\n }\n\n /**\n * Read one (little endian) 32bit dword from the buffer.\n * @param offset File offset\n * @return Dword read from the buffer\n * @throws FileBufferException\n */\n public int getDWordLE(long offset) throws FileBufferException {\n if ((offset < this.offset) || ((offset + 3) > offsetEnd)) {\n readBuffer(offset);\n }\n int idx = (int)(offset - this.offset);\n return (buf[idx] & 0xff) | ((buf[idx + 1] & 0xff) << 8)\n | ((buf[idx + 2] & 0xff) << 16) | ((buf[idx + 3] & 0xff) << 24);\n }\n\n /**\n * Read multiple bytes from the buffer.\n * @param ofs\tFile offset\n * @param b\t\tBuffer to store bytes (has to be allocated and large enough)\n * @param len\tNumber of bytes to read\n * @throws FileBufferException\n */\n public void getBytes(long ofs, byte b[], int len) throws FileBufferException {\n if ((ofs < offset) || ( (ofs + len - 1) > offsetEnd)) {\n readBuffer(ofs);\n }\n for (int i = 0; i < len; i++) {\n b[i] = buf[(int)(ofs - offset + i)];\n }\n }\n\n /**\n * Get size of input file.\n * @return Size of input file in bytes\n */\n public long getSize() {\n return length;\n }\n\n /**\n * Close file buffer (closes input file).\n */\n public void close() {\n try {\n if (fc != null) {\n fc.close();\n }\n if (fi != null) {\n fi.close();\n }\n } catch (IOException ex) {\n }\n }\n\n @Override\n public void finalize() throws Throwable {\n if (fc != null) {\n fc.close();\n }\n if (fi != null) {\n fi.close();\n }\n super.finalize();\n }\n}", "public class FileBufferException extends Exception {\n\n public FileBufferException(String s) {\n super(s);\n }\n}", "public final class ToolBox {\n\n private static final DecimalFormat FPS_FORMATTER = new DecimalFormat(\"##.###\", DecimalFormatSymbols.getInstance(Locale.US));\n\n public static String leftZeroPad(int value, int width) {\n return String.format(\"%0\" + width + \"d\", value);\n }\n\n public static String toHexLeftZeroPadded(long value, int width) {\n return String.format(\"0x%0\" + width + \"x\", value);\n }\n\n public static String formatDouble(double value) {\n return FPS_FORMATTER.format(value);\n }\n\n /**\n * Write ASCII string to buffer[index] (no special handling for multi-byte characters)\n * @param buffer Byte array\n * @param index Index to write to\n * @param s String containing ASCII characters\n * @throws ArrayIndexOutOfBoundsException\n */\n public static void setString(byte buffer[], int index, String s) {\n for (int i =0; i<s.length(); i++) {\n buffer[index+i] = (byte)s.charAt(i);\n }\n }\n\n /**\n * Show a dialog with details about an exception\n * @param ex Throwable/Exception to display\n */\n public static void showException(Throwable ex) {\n String m;\n m = \"<html>\";\n m += ex.getClass().getName() + \"<p>\";\n if (ex.getMessage() != null) {\n m += ex.getMessage() + \"<p>\";\n }\n StackTraceElement ste[] = ex.getStackTrace();\n for (StackTraceElement e : ste) {\n m += e.toString() + \"<p>\";\n }\n m += \"</html>\";\n ex.printStackTrace();\n JOptionPane.showMessageDialog(null, m, \"Error\", JOptionPane.ERROR_MESSAGE);\n }\n\n /**\n * Get file name via \"file chooser\" dialog\n * @param path Default path (without file name).\n * @param filename Default file name (without path).\n * @param extensions Array of allowed extensions (without \".\")\n * @param loadDialog If true, this is a load dialog, else it's a save dialog\n * @param parent Parent component (Frame, Window)\n * @return Selected filename or null if canceled\n */\n public static String getFilename(String path, String filename, List<String> extensions, boolean loadDialog, Component parent) {\n if (path == null || path.isEmpty()) {\n path = \".\";\n }\n JFileChooser fileChooser = new JFileChooser(path);\n if (extensions != null) {\n JFileFilter fileFilter = new JFileFilter();\n for (String extension : extensions) {\n fileFilter.addExtension(extension);\n }\n fileChooser.setFileFilter(fileFilter);\n }\n fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);\n File file;\n if (filename != null && !filename.isEmpty()) {\n file = new File(FilenameUtils.addSeparator(path) + filename);\n if (file.canRead()) {\n fileChooser.setSelectedFile(file);\n }\n }\n if (!loadDialog) {\n fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);\n }\n int returnVal = fileChooser.showDialog(parent, null);\n if (returnVal == JFileChooser.APPROVE_OPTION) {\n file = fileChooser.getSelectedFile();\n if (file != null) {\n return file.getAbsolutePath();\n }\n }\n return null;\n }\n\n /**\n * Returns the first few bytes of a file to check it's type\n * @param fname Filename of the file\n * @param num Number of bytes to return\n * @return Array of bytes (size num) from the beginning of the file\n */\n public static byte[] getFileID(String fname, int num) {\n byte buf[] = new byte[num];\n File f = new File(fname);\n if (f.length() < num) {\n return null;\n }\n try {\n FileInputStream fi = new FileInputStream(fname);\n fi.read(buf);\n fi.close();\n } catch (Exception ex) {\n return null;\n }\n return buf;\n }\n\n /**\n * Convert String to integer\n * @param s String containing integer (assumed: positive)\n * @return Integer value or -1.0 if no valid numerical value\n */\n public static int getInt(String s) {\n try {\n return Integer.parseInt(s.trim());\n } catch (NumberFormatException ex) {\n return -1;\n }\n }\n\n /**\n * Convert String to double\n * @param s String containing double\n * @return Double value or -1.0 if no valid numerical value\n */\n public static double getDouble(String s) {\n try {\n return Double.parseDouble(s.trim());\n } catch (NumberFormatException ex) {\n return -1.0;\n }\n }\n}", "public static final Palette DEFAULT_DVD_PALETTE = new Palette(\n DEFAULT_PALETTE_RED,\n DEFAULT_PALETTE_GREEN,\n DEFAULT_PALETTE_BLUE,\n DEFAULT_PALETTE_ALPHA,\n true\n);", "public static final String[][] LANGUAGES = {\n {\"English\", \"en\", \"eng\"},\n {\"Abkhazian\", \"ab\", \"abk\"},\n {\"Afar\", \"aa\", \"aar\"},\n {\"Afrikaans\", \"af\", \"afr\"},\n {\"Albanian\", \"sq\", \"sqi\"},\n {\"Amharic\", \"am\", \"amh\"},\n {\"Arabic\", \"ar\", \"ara\"},\n {\"Aragonese\", \"an\", \"arg\"},\n {\"Armenian\", \"hy\", \"hye\"},\n {\"Assamese\", \"as\", \"asm\"},\n {\"Avaric\", \"av\", \"ava\"},\n {\"Avestan\", \"ae\", \"ave\"},\n {\"Aymara\", \"ay\", \"aym\"},\n {\"Azerbaijani\", \"az\", \"aze\"},\n {\"Bambara\", \"bm\", \"bam\"},\n {\"Bashkir\", \"ba\", \"bak\"},\n {\"Basque\", \"eu\", \"eus\"},\n {\"Belarusian\", \"be\", \"bel\"},\n {\"Bengali\", \"bn\", \"ben\"},\n {\"Bihari\", \"bh\", \"bih\"},\n {\"Bislama\", \"bi\", \"bis\"},\n {\"Bosnian\", \"bs\", \"bos\"},\n {\"Breton\", \"br\", \"bre\"},\n {\"Bulgarian\", \"bg\", \"bul\"},\n {\"Burmese\", \"my\", \"mya\"},\n {\"Cambodian\", \"km\", \"khm\"},\n {\"Catalan\", \"ca\", \"cat\"},\n {\"Chamorro\", \"ch\", \"cha\"},\n {\"Chechen\", \"ce\", \"che\"},\n {\"Chichewa\", \"ny\", \"nya\"},\n {\"Chinese\", \"zh\", \"zho\"},\n {\"Chuvash\", \"cv\", \"chv\"},\n {\"Cornish\", \"kw\", \"cor\"},\n {\"Corsican\", \"co\", \"cos\"},\n {\"Cree\", \"cr\", \"cre\"},\n {\"Croatian\", \"hr\", \"hrv\"},\n {\"Czech\", \"cs\", \"ces\"},\n {\"Danish\", \"da\", \"dan\"},\n {\"Divehi\", \"dv\", \"div\"},\n {\"Dzongkha\", \"dz\", \"dzo\"},\n {\"Dutch\", \"nl\", \"nld\"},\n {\"Esperanto\", \"eo\", \"epo\"},\n {\"Estonian\", \"et\" ,\"est\"},\n {\"Ewe\", \"ee\", \"ewe\"},\n {\"Faroese\", \"fo\", \"fao\"},\n {\"Fiji\", \"fj\", \"fij\"},\n {\"Finnish\", \"fi\", \"fin\"},\n {\"French\", \"fr\", \"fra\"},\n {\"Frisian\", \"fy\", \"fry\"},\n {\"Fulah\", \"ff\", \"ful\"},\n {\"Gaelic\", \"gd\", \"gla\"},\n {\"Galician\", \"gl\", \"glg\"},\n {\"Ganda\", \"lg\", \"lug\"},\n {\"Georgian\", \"ka\", \"kat\"},\n {\"German\", \"de\", \"deu\"},\n {\"Greek\", \"el\", \"ell\"},\n {\"Greenlandic\", \"kl\", \"kal\"},\n {\"Guarani\", \"gn\", \"grn\"},\n {\"Gujarati\", \"gu\", \"guj\"},\n {\"Haitian\", \"ht\", \"hat\"},\n {\"Hausa\", \"ha\", \"hau\"},\n {\"Hebrew\", \"he\", \"heb\"},\n {\"Herero\", \"hz\", \"her\"},\n {\"Hindi\", \"hi\", \"hin\"},\n {\"Hiri Motu\", \"ho\", \"hmo\"},\n {\"Hungarian\", \"hu\", \"hun\"},\n {\"Icelandic\", \"is\", \"isl\"},\n {\"Ido\", \"io\", \"ido\"},\n {\"Igbo\", \"ig\", \"ibo\"},\n {\"Indonesian\", \"id\", \"ind\"},\n {\"Interlingua\", \"ia\", \"ina\"},\n {\"Interlingue\", \"ie\", \"ile\"},\n {\"Inupiaq\", \"ik\", \"ipk\"},\n {\"Inuktitut\", \"iu\", \"iku\"},\n {\"Irish\", \"ga\", \"gle\"},\n {\"Italian\", \"it\", \"ita\"},\n {\"Japanese\", \"ja\", \"jpn\"},\n {\"Javanese\", \"jv\", \"jav\"},\n {\"Kannada\", \"kn\", \"kan\"},\n {\"Kanuri\", \"kr\", \"kau\"},\n {\"Kashmiri\", \"ks\", \"kas\"},\n {\"Kazakh\", \"kk\", \"kaz\"},\n {\"Kikuyu\", \"ki\", \"kik\"},\n {\"Kinyarwanda\", \"rw\", \"kin\"},\n {\"Kirghiz\", \"ky\", \"kir\"},\n {\"Komi\", \"kv\", \"kom\"},\n {\"Kongo\", \"kg\", \"kon\"},\n {\"Korean\", \"ko\", \"kor\"},\n {\"Kuanyama\", \"kj\", \"kua\"},\n {\"Kurdish\", \"ku\", \"kur\"},\n {\"Lao\", \"lo\", \"lao\"},\n {\"Latin\", \"la\", \"lat\"},\n {\"Latvian\", \"lv\", \"lav\"},\n {\"Limburgan\", \"li\", \"lim\"},\n {\"Lingala\", \"ln\", \"lin\"},\n {\"Lithuanian\", \"lt\", \"lit\"},\n {\"Luba\", \"lu\", \"lub\"},\n {\"Luxembourgish\",\"lb\",\"ltz\"},\n {\"Macedonian\", \"mk\", \"mkd\"},\n {\"Malagasy\", \"mg\", \"mlg\"},\n {\"Malay\", \"ms\", \"msa\"},\n {\"Malayalam\", \"ml\", \"mal\"},\n {\"Maltese\", \"mt\", \"mlt\"},\n {\"Marshallese\", \"mh\", \"mah\"},\n {\"Manx\", \"gv\", \"glv\"},\n {\"Maori\", \"mi\", \"mri\"},\n {\"Marathi\", \"mr\", \"mar\"},\n {\"Mongolian\", \"mn\", \"mon\"},\n {\"Nauru\", \"na\", \"nau\"},\n {\"Navajo\", \"nv\", \"nav\"},\n {\"Ndebele\", \"nd\", \"nde\"},\n {\"Ndonga\", \"ng\", \"ndo\"},\n {\"Nepali\", \"ne\", \"nep\"},\n {\"Norwegian\", \"no\", \"nor\"},\n {\"Occitan\", \"oc\", \"oci\"},\n {\"Ojibwa\", \"oj\", \"oji\"},\n {\"Oriya\", \"or\", \"ori\"},\n {\"Oromo\", \"om\", \"orm\"},\n {\"Ossetian\", \"os\", \"oss\"},\n {\"Pali\", \"pi\", \"pli\"},\n {\"Panjabi\", \"pa\", \"pan\"},\n {\"Pashto\", \"ps\", \"pus\"},\n {\"Persian\", \"fa\", \"fas\"},\n {\"Polish\", \"pl\", \"pol\"},\n {\"Portuguese\", \"pt\", \"por\"},\n {\"Quechua\", \"qu\", \"que\"},\n {\"Romansh\", \"rm\", \"roh\"},\n {\"Romanian\", \"ro\", \"ron\"},\n {\"Rundi\", \"rn\", \"run\"},\n {\"Russian\", \"ru\", \"rus\"},\n {\"Sami\", \"se\", \"sme\"},\n {\"Samoan\", \"sm\", \"smo\"},\n {\"Sango\", \"sg\", \"sag\"},\n {\"Sanskrit\", \"sa\", \"san\"},\n {\"Sardinian\", \"sc\", \"srd\"},\n {\"Serbian\", \"sr\", \"srp\"},\n {\"Shona\", \"sn\", \"sna\"},\n {\"Sichuan Yi\", \"ii\", \"iii\"},\n {\"Sindhi\", \"sd\", \"snd\"},\n {\"Sinhalese\", \"si\", \"sin\"},\n {\"Slavonic\", \"cu\", \"chu\"},\n {\"Slovak\", \"sk\", \"slk\"},\n {\"Slovenian\", \"sl\", \"slv\"},\n {\"Somali\", \"so\", \"som\"},\n {\"Sotho\", \"st\", \"sot\"},\n {\"Spanish\", \"es\", \"spa\"},\n {\"Sundanese\", \"su\", \"sun\"},\n {\"Swahili\", \"sw\", \"swa\"},\n {\"Swati\", \"ss\", \"ssw\"},\n {\"Swedish\", \"sv\", \"swe\"},\n {\"Tagalog\", \"tl\", \"tgl\"},\n {\"Tahitian\", \"ty\", \"tah\"},\n {\"Tajik\", \"tg\", \"tgk\"},\n {\"Tamil\", \"ta\", \"tam\"},\n {\"Tatar\", \"tt\", \"tar\"},\n {\"Telugu\", \"te\", \"tel\"},\n {\"Thai\", \"th\", \"tha\"},\n {\"Tibetan\", \"bo\", \"bod\"},\n {\"Tigrinya\", \"ti\", \"tir\"},\n {\"Tonga\", \"to\", \"ton\"},\n {\"Tsonga\", \"ts\", \"tso\"},\n {\"Tswana\", \"tn\", \"tsn\"},\n {\"Turkish\", \"tr\", \"tur\"},\n {\"Turkmen\", \"tk\", \"tuk\"},\n {\"Twi\", \"tw\", \"twi\"},\n {\"Uighur\", \"ug\", \"uig\"},\n {\"Ukrainian\", \"uk\", \"ukr\"},\n {\"Urdu\", \"ur\", \"urd\"},\n {\"Uzbek\", \"uz\", \"uzb\"},\n {\"Venda\", \"ve\", \"ven\"},\n {\"Vietnamese\", \"vi\", \"vie\"},\n {\"Volapük\", \"vo\", \"vol\"},\n {\"Welsh\", \"cy\", \"cym\"},\n {\"Walloon\", \"wa\", \"wln\"},\n {\"Wolof\", \"wo\", \"wol\"},\n {\"Xhosa\", \"xh\", \"xho\"},\n {\"Yiddish\", \"yi\", \"yid\"},\n {\"Yoruba\", \"yo\", \"yor\"},\n {\"Zhuang\", \"za\", \"zha\"},\n {\"Zulu\", \"zu\", \"zul\"},\n};" ]
import bdsup2sub.bitmap.Palette; import bdsup2sub.core.CoreException; import bdsup2sub.core.Logger; import bdsup2sub.tools.FileBuffer; import bdsup2sub.tools.FileBufferException; import bdsup2sub.utils.ToolBox; import java.util.Arrays; import static bdsup2sub.core.Constants.DEFAULT_DVD_PALETTE; import static bdsup2sub.core.Constants.LANGUAGES;
/* * Copyright 2014 Volker Oth (0xdeadbeef) / Miklos Juhasz (mjuhasz) * * 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 bdsup2sub.supstream.dvd; public class IfoParser { private static final Logger logger = Logger.getInstance(); private static final byte[] IFO_HEADER = "DVDVIDEO-VTS".getBytes(); private final FileBuffer fileBuffer; private int screenWidth; private int screenHeight; private int languageIdx; private Palette srcPalette = new Palette(DEFAULT_DVD_PALETTE); public IfoParser(String filename) throws CoreException { try { this.fileBuffer = new FileBuffer(filename); processIFO(); } catch (FileBufferException e) { throw new CoreException(e.getMessage()); } } private void processIFO() throws CoreException { try { validateIfoHeader(); readVideoAttributes(); readFirstLanguageIndex(); readFirstPalette(); } catch (FileBufferException e) { throw new CoreException(e.getMessage()); } } private void validateIfoHeader() throws FileBufferException, CoreException { byte header[] = new byte[IFO_HEADER.length]; fileBuffer.getBytes(0, header, IFO_HEADER.length); if (!Arrays.equals(header, IFO_HEADER)) { throw new CoreException("Not a valid IFO file."); } } private void readVideoAttributes() throws FileBufferException { int vidAttr = fileBuffer.getWord(0x200); if ((vidAttr & 0x3000) != 0) { // PAL switch ((vidAttr>>3) & 3) { case 0: screenWidth = 720; screenHeight = 576; break; case 1: screenWidth = 704; screenHeight = 576; break; case 2: screenWidth = 352; screenHeight = 576; break; case 3: screenWidth = 352; screenHeight = 288; break; } } else { // NTSC switch ((vidAttr>>3) & 3) { case 0: screenWidth = 720; screenHeight = 480; break; case 1: screenWidth = 704; screenHeight = 480; break; case 2: screenWidth = 352; screenHeight = 480; break; case 3: screenWidth = 352; screenHeight = 240; break; } } logger.trace("Resolution: " + screenWidth + "x" + screenHeight + "\n"); } private void readFirstLanguageIndex() throws FileBufferException { if (fileBuffer.getWord(0x254) > 0 && fileBuffer.getByte(0x256) == 1) { StringBuilder langSB = new StringBuilder(2); boolean found = false; langSB.append((char) fileBuffer.getByte(0x258)); langSB.append((char) fileBuffer.getByte(0x259)); String lang = langSB.toString(); for (int i=0; i < LANGUAGES.length; i++) { if (lang.equalsIgnoreCase(LANGUAGES[i][1])) { languageIdx = i; found = true; break; } } if (!found) { logger.warn("Illegal language id: " + lang + "\n"); } else { logger.trace("Set language to: " + lang + "\n"); } } else { logger.warn("Missing language id.\n"); } } private void readFirstPalette() throws FileBufferException { // get start offset of Titles&Chapters table long VTS_PGCITI_ofs = fileBuffer.getDWord(0xCC) * 2048; // PTT_SRPTI VTS_PGCITI_ofs += fileBuffer.getDWord(VTS_PGCITI_ofs+0x0C);
logger.trace("Reading palette from offset: " + ToolBox.toHexLeftZeroPadded(VTS_PGCITI_ofs, 8) + "\n");
5
deephacks/westty
westty-protobuf/src/main/java/org/deephacks/westty/internal/protobuf/ProtobufPipelineFactory.java
[ "@ConfigScope\n@Config(name = \"protobuf\",\n desc = \"Protobuf configuration. Changes requires server restart.\")\npublic class ProtobufConfig {\n\n @Id(desc=\"Name of this server\")\n private String serverName = ServerConfig.DEFAULT_SERVER_NAME;\n\n public ProtobufConfig(){\n }\n\n public ProtobufConfig(String serverName){\n this.serverName = serverName;\n }\n\n @Config(desc = \"Protobuf listening port.\")\n @NotNull\n @Min(0)\n @Max(65535)\n private Integer port = 7777;\n\n @Config(desc = \"Specify the worker count to use. \"\n + \"See netty javadoc NioServerSocketChannelFactory.\")\n @Min(1)\n @NotNull\n private Integer ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2;\n\n public Integer getIoWorkerCount() {\n return ioWorkerCount;\n }\n\n public int getPort() {\n return port;\n }\n\n public void setPort(Integer port) {\n this.port = port;\n }\n\n public void setIoWorkerCount(Integer ioWorkerCount) {\n this.ioWorkerCount = ioWorkerCount;\n }\n}", "public class ServerSpecificConfigProxy<T> {\n private T config;\n\n private ServerSpecificConfigProxy(T config){\n this.config = config;\n }\n\n /**\n * @return The configurable server specific instance or an empty default\n * instance if it does not exist in the configuration bean manager.\n */\n public T get(){\n return config;\n }\n\n static class ServerSpecificConfigProxyProducer<T> {\n private static final Logger log = LoggerFactory.getLogger(ServerSpecificConfigProxyProducer.class);\n @Inject\n private ServerName serverName;\n\n @Inject\n private ConfigContext config;\n\n @Produces\n public ServerSpecificConfigProxy<T> produceServerConfigProxy(InjectionPoint ip){\n Class<?> declaringClass = ip.getMember().getDeclaringClass();\n Class<?> configCls = getParameterizedType(declaringClass, ip.getAnnotated().getBaseType());\n try {\n Optional<?> optionalServer = config.get(serverName.getName(), configCls);\n if (optionalServer.isPresent()) {\n return new ServerSpecificConfigProxy(optionalServer.get());\n } else {\n log.debug(\"Config instance {} of type {} not found\", serverName.getName(), configCls);\n Object config = newInstance(configCls, serverName.getName());\n return new ServerSpecificConfigProxy(config);\n }\n } catch (AbortRuntimeException e) {\n if (e.getEvent().getCode() != Events.CFG304){\n throw e;\n }\n log.debug(\"Config instance {} of type {} not found\", serverName.getName(), configCls);\n Object config = newInstance(configCls, serverName.getName());\n return new ServerSpecificConfigProxy(config);\n }\n }\n\n Class<?> getParameterizedType(Class<?> cls, final Type type) {\n if (!ParameterizedType.class.isAssignableFrom(type.getClass())) {\n throw new IllegalArgumentException(\"ServerSpecificConfigProxy does not have generic type \" + type);\n }\n\n ParameterizedType ptype = (ParameterizedType) type;\n Type[] targs = ptype.getActualTypeArguments();\n\n for (Type aType : targs) {\n return extractClass(cls, aType);\n }\n throw new IllegalArgumentException(\"Could not get generic type from ServerSpecificConfigProxy \" + type);\n }\n private static Class<?> extractClass(Class<?> ownerClass, Type arg) {\n if (arg instanceof ParameterizedType) {\n return extractClass(ownerClass, ((ParameterizedType) arg).getRawType());\n } else if (arg instanceof GenericArrayType) {\n throw new UnsupportedOperationException(\"GenericArray types are not supported.\");\n } else if (arg instanceof TypeVariable) {\n throw new UnsupportedOperationException(\"GenericArray types are not supported.\");\n }\n return (arg instanceof Class ? (Class<?>) arg : Object.class);\n }\n\n Object newInstance(Class<?> type, String name) {\n try {\n Class<?> enclosing = type.getEnclosingClass();\n if (enclosing == null) {\n Constructor<?> c = type.getDeclaredConstructor(String.class);\n c.setAccessible(true);\n return type.cast(c.newInstance(name));\n }\n Object o = enclosing.newInstance();\n Constructor<?> cc = type.getDeclaredConstructor(enclosing, String.class);\n cc.setAccessible(true);\n return type.cast(cc.newInstance(o, name));\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n static Class<?> forName(String className) {\n try {\n return Thread.currentThread().getContextClassLoader().loadClass(className);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }\n\n\n }\n}", "public static final class Failure extends\n com.google.protobuf.GeneratedMessage\n implements FailureOrBuilder {\n // Use Failure.newBuilder() to construct.\n private Failure(Builder builder) {\n super(builder);\n }\n private Failure(boolean noInit) {}\n \n private static final Failure defaultInstance;\n public static Failure getDefaultInstance() {\n return defaultInstance;\n }\n \n public Failure getDefaultInstanceForType() {\n return defaultInstance;\n }\n \n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.deephacks.westty.protobuf.FailureMessages.internal_static_example_Failure_descriptor;\n }\n \n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.deephacks.westty.protobuf.FailureMessages.internal_static_example_Failure_fieldAccessorTable;\n }\n \n private int bitField0_;\n // optional uint32 protoType = 1000;\n public static final int PROTOTYPE_FIELD_NUMBER = 1000;\n private int protoType_;\n public boolean hasProtoType() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n public int getProtoType() {\n return protoType_;\n }\n \n // required string msg = 1;\n public static final int MSG_FIELD_NUMBER = 1;\n private java.lang.Object msg_;\n public boolean hasMsg() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n public String getMsg() {\n java.lang.Object ref = msg_;\n if (ref instanceof String) {\n return (String) ref;\n } else {\n com.google.protobuf.ByteString bs = \n (com.google.protobuf.ByteString) ref;\n String s = bs.toStringUtf8();\n if (com.google.protobuf.Internal.isValidUtf8(bs)) {\n msg_ = s;\n }\n return s;\n }\n }\n private com.google.protobuf.ByteString getMsgBytes() {\n java.lang.Object ref = msg_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b = \n com.google.protobuf.ByteString.copyFromUtf8((String) ref);\n msg_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n \n // required uint32 code = 2;\n public static final int CODE_FIELD_NUMBER = 2;\n private int code_;\n public boolean hasCode() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n public int getCode() {\n return code_;\n }\n \n private void initFields() {\n protoType_ = 0;\n msg_ = \"\";\n code_ = 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 (!hasMsg()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (!hasCode()) {\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_ & 0x00000002) == 0x00000002)) {\n output.writeBytes(1, getMsgBytes());\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n output.writeUInt32(2, code_);\n }\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeUInt32(1000, protoType_);\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_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(1, getMsgBytes());\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n size += com.google.protobuf.CodedOutputStream\n .computeUInt32Size(2, code_);\n }\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeUInt32Size(1000, protoType_);\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.deephacks.westty.protobuf.FailureMessages.Failure parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return newBuilder().mergeFrom(data).buildParsed();\n }\n public static org.deephacks.westty.protobuf.FailureMessages.Failure parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return newBuilder().mergeFrom(data, extensionRegistry)\n .buildParsed();\n }\n public static org.deephacks.westty.protobuf.FailureMessages.Failure parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return newBuilder().mergeFrom(data).buildParsed();\n }\n public static org.deephacks.westty.protobuf.FailureMessages.Failure parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return newBuilder().mergeFrom(data, extensionRegistry)\n .buildParsed();\n }\n public static org.deephacks.westty.protobuf.FailureMessages.Failure parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return newBuilder().mergeFrom(input).buildParsed();\n }\n public static org.deephacks.westty.protobuf.FailureMessages.Failure parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return newBuilder().mergeFrom(input, extensionRegistry)\n .buildParsed();\n }\n public static org.deephacks.westty.protobuf.FailureMessages.Failure parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n Builder builder = newBuilder();\n if (builder.mergeDelimitedFrom(input)) {\n return builder.buildParsed();\n } else {\n return null;\n }\n }\n public static org.deephacks.westty.protobuf.FailureMessages.Failure parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n Builder builder = newBuilder();\n if (builder.mergeDelimitedFrom(input, extensionRegistry)) {\n return builder.buildParsed();\n } else {\n return null;\n }\n }\n public static org.deephacks.westty.protobuf.FailureMessages.Failure parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return newBuilder().mergeFrom(input).buildParsed();\n }\n public static org.deephacks.westty.protobuf.FailureMessages.Failure parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return newBuilder().mergeFrom(input, extensionRegistry)\n .buildParsed();\n }\n \n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.deephacks.westty.protobuf.FailureMessages.Failure 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 public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.deephacks.westty.protobuf.FailureMessages.FailureOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.deephacks.westty.protobuf.FailureMessages.internal_static_example_Failure_descriptor;\n }\n \n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.deephacks.westty.protobuf.FailureMessages.internal_static_example_Failure_fieldAccessorTable;\n }\n \n // Construct using org.deephacks.westty.protobuf.FailureMessages.Failure.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n \n private Builder(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 protoType_ = 0;\n bitField0_ = (bitField0_ & ~0x00000001);\n msg_ = \"\";\n bitField0_ = (bitField0_ & ~0x00000002);\n code_ = 0;\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.deephacks.westty.protobuf.FailureMessages.Failure.getDescriptor();\n }\n \n public org.deephacks.westty.protobuf.FailureMessages.Failure getDefaultInstanceForType() {\n return org.deephacks.westty.protobuf.FailureMessages.Failure.getDefaultInstance();\n }\n \n public org.deephacks.westty.protobuf.FailureMessages.Failure build() {\n org.deephacks.westty.protobuf.FailureMessages.Failure result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n \n private org.deephacks.westty.protobuf.FailureMessages.Failure buildParsed()\n throws com.google.protobuf.InvalidProtocolBufferException {\n org.deephacks.westty.protobuf.FailureMessages.Failure result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(\n result).asInvalidProtocolBufferException();\n }\n return result;\n }\n \n public org.deephacks.westty.protobuf.FailureMessages.Failure buildPartial() {\n org.deephacks.westty.protobuf.FailureMessages.Failure result = new org.deephacks.westty.protobuf.FailureMessages.Failure(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.protoType_ = protoType_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.msg_ = msg_;\n if (((from_bitField0_ & 0x00000004) == 0x00000004)) {\n to_bitField0_ |= 0x00000004;\n }\n result.code_ = code_;\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.deephacks.westty.protobuf.FailureMessages.Failure) {\n return mergeFrom((org.deephacks.westty.protobuf.FailureMessages.Failure)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n \n public Builder mergeFrom(org.deephacks.westty.protobuf.FailureMessages.Failure other) {\n if (other == org.deephacks.westty.protobuf.FailureMessages.Failure.getDefaultInstance()) return this;\n if (other.hasProtoType()) {\n setProtoType(other.getProtoType());\n }\n if (other.hasMsg()) {\n setMsg(other.getMsg());\n }\n if (other.hasCode()) {\n setCode(other.getCode());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n \n public final boolean isInitialized() {\n if (!hasMsg()) {\n \n return false;\n }\n if (!hasCode()) {\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 com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder(\n this.getUnknownFields());\n while (true) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n this.setUnknownFields(unknownFields.build());\n onChanged();\n return this;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n this.setUnknownFields(unknownFields.build());\n onChanged();\n return this;\n }\n break;\n }\n case 10: {\n bitField0_ |= 0x00000002;\n msg_ = input.readBytes();\n break;\n }\n case 16: {\n bitField0_ |= 0x00000004;\n code_ = input.readUInt32();\n break;\n }\n case 8000: {\n bitField0_ |= 0x00000001;\n protoType_ = input.readUInt32();\n break;\n }\n }\n }\n }\n \n private int bitField0_;\n \n // optional uint32 protoType = 1000;\n private int protoType_ ;\n public boolean hasProtoType() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n public int getProtoType() {\n return protoType_;\n }\n public Builder setProtoType(int value) {\n bitField0_ |= 0x00000001;\n protoType_ = value;\n onChanged();\n return this;\n }\n public Builder clearProtoType() {\n bitField0_ = (bitField0_ & ~0x00000001);\n protoType_ = 0;\n onChanged();\n return this;\n }\n \n // required string msg = 1;\n private java.lang.Object msg_ = \"\";\n public boolean hasMsg() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n public String getMsg() {\n java.lang.Object ref = msg_;\n if (!(ref instanceof String)) {\n String s = ((com.google.protobuf.ByteString) ref).toStringUtf8();\n msg_ = s;\n return s;\n } else {\n return (String) ref;\n }\n }\n public Builder setMsg(String value) {\n if (value == null) {\n throw new NullPointerException();\n}\nbitField0_ |= 0x00000002;\n msg_ = value;\n onChanged();\n return this;\n }\n public Builder clearMsg() {\n bitField0_ = (bitField0_ & ~0x00000002);\n msg_ = getDefaultInstance().getMsg();\n onChanged();\n return this;\n }\n void setMsg(com.google.protobuf.ByteString value) {\n bitField0_ |= 0x00000002;\n msg_ = value;\n onChanged();\n }\n \n // required uint32 code = 2;\n private int code_ ;\n public boolean hasCode() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n public int getCode() {\n return code_;\n }\n public Builder setCode(int value) {\n bitField0_ |= 0x00000004;\n code_ = value;\n onChanged();\n return this;\n }\n public Builder clearCode() {\n bitField0_ = (bitField0_ & ~0x00000004);\n code_ = 0;\n onChanged();\n return this;\n }\n \n // @@protoc_insertion_point(builder_scope:example.Failure)\n }\n \n static {\n defaultInstance = new Failure(true);\n defaultInstance.initFields();\n }\n \n // @@protoc_insertion_point(class_scope:example.Failure)\n}", "@Singleton\npublic class ProtobufClient {\n private static final Logger log = LoggerFactory.getLogger(ProtobufClient.class);\n\n public static final int MESSAGE_LENGTH = 4;\n public static final int MESSAGE_MAX_SIZE_10MB = 10485760;\n private final ProtobufSerializer serializer;\n private final Lock lock = new ReentrantLock();\n private final ConcurrentHashMap<Integer, ConcurrentLinkedQueue<Callback>> callbacks = new ConcurrentHashMap<>();\n private final ChannelFactory factory;\n private final ChannelGroup channelGroup = new DefaultChannelGroup(\"channels\");\n private final ClientProtobufDecoder decoder;\n private final ClientProtobufEncoder encoder;\n private final LengthFieldPrepender lengthPrepender = new LengthFieldPrepender(MESSAGE_LENGTH);\n private final ClientHandler clientHandler = new ClientHandler();\n private final ProtobufConfig config;\n @Inject\n public ProtobufClient(IoExecutors excutors,\n ProtobufSerializer serializer, ProtobufConfig config) {\n this.factory = new NioClientSocketChannelFactory(excutors.getBoss(), excutors.getWorker());\n this.serializer = serializer;\n this.decoder = new ClientProtobufDecoder(serializer);\n this.encoder = new ClientProtobufEncoder();\n this.config = config;\n }\n\n public int connect() throws IOException {\n return connect(new InetSocketAddress(config.getPort()));\n }\n\n public int connect(InetSocketAddress address) throws IOException {\n ClientBootstrap bootstrap = new ClientBootstrap(factory);\n bootstrap.setPipelineFactory(new ChannelPipelineFactory() {\n\n @Override\n public ChannelPipeline getPipeline() throws Exception {\n ChannelPipeline pipeline = Channels.pipeline();\n pipeline.addLast(\"lengthFrameDecoder\", new LengthFieldBasedFrameDecoder(\n MESSAGE_MAX_SIZE_10MB, 0, MESSAGE_LENGTH, 0, MESSAGE_LENGTH));\n pipeline.addLast(\"decoder\", decoder);\n pipeline.addLast(\"lengthPrepender\", lengthPrepender);\n pipeline.addLast(\"encoder\", encoder);\n pipeline.addLast(\"handler\", clientHandler);\n return pipeline;\n }\n });\n\n ChannelFuture future = bootstrap.connect(address);\n\n if (!future.awaitUninterruptibly().isSuccess()) {\n bootstrap.releaseExternalResources();\n throw new IllegalArgumentException(\"Could not connect to \" + address);\n }\n\n Channel channel = future.getChannel();\n\n if (!channel.isConnected()) {\n bootstrap.releaseExternalResources();\n throw new IllegalStateException(\"Channel could not connect to \" + address);\n }\n channelGroup.add(channel);\n return channel.getId();\n }\n\n public void registerResource(String protodesc) {\n serializer.registerResource(protodesc);\n }\n\n public ChannelFuture callAsync(Integer channelId, Object protoMsg) throws IOException {\n Channel channel = channelGroup.find(channelId);\n byte[] bytes = serializer.write(protoMsg);\n if (channel == null || !channel.isOpen()) {\n throw new IOException(\"Channel is not open\");\n }\n return channel.write(ChannelBuffers.wrappedBuffer(bytes));\n }\n\n public Object callSync(int id, Object protoMsg) throws IOException, FailureMessageException {\n Preconditions.checkNotNull(protoMsg);\n Channel channel = channelGroup.find(id);\n if(channel == null){\n throw new IllegalArgumentException(\"Channel not found [\"+id+\"]\");\n }\n byte[] bytes = serializer.write(protoMsg);\n Callback callback = new Callback();\n lock.lock();\n try {\n if (!channel.isOpen()) {\n throw new IOException(\"Channel is not open\");\n }\n ConcurrentLinkedQueue<Callback> callbackQueue = callbacks.get(id);\n if(callbackQueue == null){\n callbackQueue = new ConcurrentLinkedQueue<>();\n callbacks.put(id, callbackQueue);\n }\n callbackQueue.add(callback);\n channel.write(ChannelBuffers.wrappedBuffer(bytes));\n } finally {\n lock.unlock();\n }\n Object res = callback.get();\n if (res instanceof Failure) {\n Failure failure = (Failure) res;\n throw new FailureMessageException(failure);\n }\n if(res instanceof VoidMessage.Void){\n return null;\n }\n return res;\n }\n\n public void disconnect(Integer id) {\n Channel channel = channelGroup.find(id);\n if (channel != null && channel.isConnected()) {\n channel.close().awaitUninterruptibly();\n }\n\n }\n\n public void shutdown() {\n channelGroup.close().awaitUninterruptibly();\n final class ShutdownNetty extends Thread {\n public void run() {\n factory.releaseExternalResources();\n }\n }\n new ShutdownNetty().start();\n }\n\n class ClientHandler extends SimpleChannelHandler {\n\n @Override\n public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent e)\n throws Exception {\n if (e instanceof ChannelStateEvent) {\n log.debug(e.toString());\n }\n super.handleUpstream(ctx, e);\n }\n\n @Override\n public void channelClosed(ChannelHandlerContext ctx, final ChannelStateEvent e)\n throws Exception {\n disconnect(e.getChannel().getId());\n }\n\n @Override\n public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {\n ConcurrentLinkedQueue<Callback> callbackQueue = callbacks.get(e.getChannel().getId());\n if(callbackQueue == null){\n return;\n }\n Callback callback = callbackQueue.poll();\n if (callback != null) {\n callback.handle(e.getMessage());\n }\n }\n\n @Override\n public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {\n final Throwable cause = e.getCause();\n final Channel ch = ctx.getChannel();\n if (cause instanceof ClosedChannelException) {\n log.warn(\"Attempt to write to closed channel.\" + ch);\n\n disconnect(e.getChannel().getId());\n } else if (cause instanceof IOException\n && \"Connection reset by peer\".equals(cause.getMessage())) {\n disconnect(e.getChannel().getId());\n } else if (cause instanceof ConnectException\n && \"Connection refused\".equals(cause.getMessage())) {\n // server not up, nothing to do\n } else {\n log.error(\"Unexpected exception.\", e.getCause());\n disconnect(e.getChannel().getId());\n }\n }\n }\n\n @Sharable\n static class ClientProtobufDecoder extends OneToOneDecoder {\n private final ProtobufSerializer serializer;\n\n public ClientProtobufDecoder(ProtobufSerializer serializer) {\n this.serializer = serializer;\n }\n\n @Override\n protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg)\n throws Exception {\n if (!(msg instanceof ChannelBuffer)) {\n return msg;\n }\n ChannelBuffer buf = (ChannelBuffer) msg;\n return serializer.read(buf.array());\n }\n }\n\n @Sharable\n static class ClientProtobufEncoder extends OneToOneEncoder {\n @Override\n protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg)\n throws Exception {\n if (msg instanceof MessageLite) {\n return wrappedBuffer(((MessageLite) msg).toByteArray());\n }\n if (msg instanceof MessageLite.Builder) {\n return wrappedBuffer(((MessageLite.Builder) msg).build().toByteArray());\n }\n return msg;\n }\n }\n\n static class Callback {\n private final CountDownLatch latch = new CountDownLatch(1);\n private Object response;\n\n Object get() {\n try {\n latch.await();\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n return response;\n }\n\n void handle(Object response) {\n this.response = response;\n latch.countDown();\n }\n }\n}", "@Alternative\npublic class ProtobufSerializer {\n private static final Logger log = LoggerFactory.getLogger(ProtobufSerializer.class);\n private HashMap<Integer, Method> numToMethod = new HashMap<>();\n private HashMap<String, Integer> protoToNum = new HashMap<>();\n private static final String UNRECOGNIZED_PROTOCOL_MSG = \"Unrecognized protocol.\";\n\n public ProtobufSerializer() {\n registerResource(\"META-INF/failure.desc\");\n registerResource(\"META-INF/void.desc\");\n }\n\n public void register(URL protodesc) {\n try {\n registerDesc(protodesc.getFile(), protodesc.openStream());\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void register(File protodesc) {\n try {\n registerDesc(protodesc.getName(), new FileInputStream(protodesc));\n } catch (FileNotFoundException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void registerResource(String protodesc) {\n URL url = Thread.currentThread().getContextClassLoader().getResource(protodesc);\n register(url);\n }\n\n private void registerDesc(String name, InputStream in) {\n try {\n FileDescriptorSet descriptorSet = FileDescriptorSet.parseFrom(in);\n for (FileDescriptorProto fdp : descriptorSet.getFileList()) {\n FileDescriptor fd = FileDescriptor.buildFrom(fdp, new FileDescriptor[] {});\n\n for (Descriptor desc : fd.getMessageTypes()) {\n FieldDescriptor fdesc = desc.findFieldByName(\"protoType\");\n if (fdesc == null) {\n throw new IllegalArgumentException(name\n + \".proto file must define protoType field \"\n + \"with unqiue number that identify proto type\");\n }\n String packageName = fdp.getOptions().getJavaPackage();\n\n if (Strings.isNullOrEmpty(packageName)) {\n throw new IllegalArgumentException(name\n + \".proto file must define java_package\");\n }\n String simpleClassName = fdp.getOptions().getJavaOuterClassname();\n if (Strings.isNullOrEmpty(simpleClassName)) {\n throw new IllegalArgumentException(name\n + \" .proto file must define java_outer_classname\");\n }\n\n String className = packageName + \".\" + simpleClassName + \"$\" + desc.getName();\n Class<?> cls = Thread.currentThread().getContextClassLoader()\n .loadClass(className);\n protoToNum.put(desc.getFullName(), fdesc.getNumber());\n numToMethod.put(fdesc.getNumber(), cls.getMethod(\"parseFrom\", byte[].class));\n log.debug(\"Registered protobuf resource {}.\", name);\n }\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public Object read(byte[] bytes) throws Exception {\n try {\n ByteBuffer buf = ByteBuffer.wrap(bytes);\n Varint32 vint = new Varint32(buf);\n int protoTypeNum = vint.read();\n buf = vint.getByteBuffer();\n byte[] message = new byte[buf.remaining()];\n buf.get(message);\n Method m = numToMethod.get(protoTypeNum);\n if (m == null) {\n return Failure.newBuilder().setCode(BAD_REQUEST.getCode())\n .setMsg(\"proto_type=\" + protoTypeNum).build();\n }\n return m.invoke(null, message);\n } catch (Exception e) {\n return Failure.newBuilder().setCode(BAD_REQUEST.getCode())\n .setMsg(UNRECOGNIZED_PROTOCOL_MSG).build();\n }\n }\n\n public byte[] write(Object proto) throws IOException {\n Message msg = (Message) proto;\n String protoName = msg.getDescriptorForType().getFullName();\n Integer num = protoToNum.get(protoName);\n if(num == null){\n throw new IllegalArgumentException(\"Could not find protoType mapping for \" + protoName);\n }\n byte[] msgBytes = msg.toByteArray();\n Varint32 vint = new Varint32(num);\n int vsize = vint.getSize();\n byte[] bytes = new byte[vsize + msgBytes.length];\n System.arraycopy(vint.write(), 0, bytes, 0, vsize);\n System.arraycopy(msgBytes, 0, bytes, vsize, msgBytes.length);\n return bytes;\n }\n}", "public class ProviderShutdownEvent {\n\n}", "public class ProviderStartupEvent {\n\n}" ]
import com.google.protobuf.MessageLite; import org.deephacks.westty.config.ProtobufConfig; import org.deephacks.westty.config.ServerSpecificConfigProxy; import org.deephacks.westty.protobuf.FailureMessages.Failure; import org.deephacks.westty.protobuf.ProtobufClient; import org.deephacks.westty.protobuf.ProtobufSerializer; import org.deephacks.westty.spi.ProviderShutdownEvent; import org.deephacks.westty.spi.ProviderStartupEvent; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.LengthFieldPrepender; import org.jboss.netty.handler.codec.oneone.OneToOneDecoder; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; import org.jboss.netty.handler.execution.ExecutionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.event.Observes; import javax.inject.Inject; import javax.inject.Singleton; import java.net.InetSocketAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import static org.jboss.netty.buffer.ChannelBuffers.wrappedBuffer;
/** * 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.deephacks.westty.internal.protobuf; @Singleton class ProtobufPipelineFactory implements ChannelPipelineFactory { private static final Logger log = LoggerFactory.getLogger(ProtobufChannelHandler.class); @Inject private ProtobufChannelHandler channelHandler; private ProtobufSerializer serializer; private ThreadPoolExecutor executor; private ExecutionHandler executionHandler; private Channel channel; private ServerBootstrap bootstrap; private ProtobufConfig config; @Inject public ProtobufPipelineFactory(ServerSpecificConfigProxy<ProtobufConfig> config, ThreadPoolExecutor executor, ProtobufSerializer serializer) { this.config = config.get(); this.executor = executor; this.serializer = serializer; ExecutorService workers = Executors.newCachedThreadPool(); ExecutorService boss = Executors.newCachedThreadPool(); bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(boss, workers, this.config.getIoWorkerCount())); bootstrap.setPipelineFactory(this); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); }
public void startup(@Observes ProviderStartupEvent event) {
6
lingochamp/FileDownloader
library/src/main/java/com/liulishuo/filedownloader/FileDownloader.java
[ "public class CustomComponentHolder {\n private DownloadMgrInitialParams initialParams;\n\n private FileDownloadHelper.ConnectionCountAdapter connectionCountAdapter;\n private FileDownloadHelper.ConnectionCreator connectionCreator;\n private FileDownloadHelper.OutputStreamCreator outputStreamCreator;\n private FileDownloadDatabase database;\n private FileDownloadHelper.IdGenerator idGenerator;\n private ForegroundServiceConfig foregroundServiceConfig;\n\n private static final class LazyLoader {\n private static final CustomComponentHolder INSTANCE = new CustomComponentHolder();\n }\n\n public static CustomComponentHolder getImpl() {\n return LazyLoader.INSTANCE;\n }\n\n public void setInitCustomMaker(DownloadMgrInitialParams.InitCustomMaker initCustomMaker) {\n synchronized (this) {\n initialParams = new DownloadMgrInitialParams(initCustomMaker);\n connectionCreator = null;\n outputStreamCreator = null;\n database = null;\n idGenerator = null;\n }\n }\n\n public FileDownloadConnection createConnection(String url) throws IOException {\n return getConnectionCreator().create(url);\n }\n\n public FileDownloadOutputStream createOutputStream(File file) throws IOException {\n return getOutputStreamCreator().create(file);\n }\n\n public FileDownloadHelper.IdGenerator getIdGeneratorInstance() {\n if (idGenerator != null) return idGenerator;\n\n synchronized (this) {\n if (idGenerator == null) {\n idGenerator = getDownloadMgrInitialParams().createIdGenerator();\n }\n }\n\n return idGenerator;\n }\n\n public FileDownloadDatabase getDatabaseInstance() {\n if (database != null) return database;\n\n synchronized (this) {\n if (database == null) {\n database = getDownloadMgrInitialParams().createDatabase();\n maintainDatabase(database.maintainer());\n }\n }\n\n return database;\n }\n\n public ForegroundServiceConfig getForegroundConfigInstance() {\n if (foregroundServiceConfig != null) return foregroundServiceConfig;\n\n synchronized (this) {\n if (foregroundServiceConfig == null) {\n foregroundServiceConfig = getDownloadMgrInitialParams()\n .createForegroundServiceConfig();\n }\n }\n\n return foregroundServiceConfig;\n }\n\n public int getMaxNetworkThreadCount() {\n return getDownloadMgrInitialParams().getMaxNetworkThreadCount();\n }\n\n public boolean isSupportSeek() {\n return getOutputStreamCreator().supportSeek();\n }\n\n public int determineConnectionCount(int downloadId, String url, String path, long totalLength) {\n return getConnectionCountAdapter()\n .determineConnectionCount(downloadId, url, path, totalLength);\n }\n\n private FileDownloadHelper.ConnectionCountAdapter getConnectionCountAdapter() {\n if (connectionCountAdapter != null) return connectionCountAdapter;\n\n synchronized (this) {\n if (connectionCountAdapter == null) {\n connectionCountAdapter = getDownloadMgrInitialParams()\n .createConnectionCountAdapter();\n }\n }\n\n return connectionCountAdapter;\n }\n\n private FileDownloadHelper.ConnectionCreator getConnectionCreator() {\n if (connectionCreator != null) return connectionCreator;\n\n synchronized (this) {\n if (connectionCreator == null) {\n connectionCreator = getDownloadMgrInitialParams().createConnectionCreator();\n }\n }\n\n return connectionCreator;\n }\n\n private FileDownloadHelper.OutputStreamCreator getOutputStreamCreator() {\n if (outputStreamCreator != null) return outputStreamCreator;\n\n synchronized (this) {\n if (outputStreamCreator == null) {\n outputStreamCreator = getDownloadMgrInitialParams().createOutputStreamCreator();\n }\n }\n\n return outputStreamCreator;\n }\n\n private DownloadMgrInitialParams getDownloadMgrInitialParams() {\n if (initialParams != null) return initialParams;\n\n synchronized (this) {\n if (initialParams == null) initialParams = new DownloadMgrInitialParams();\n }\n\n return initialParams;\n }\n\n private static void maintainDatabase(FileDownloadDatabase.Maintainer maintainer) {\n final Iterator<FileDownloadModel> iterator = maintainer.iterator();\n long refreshDataCount = 0;\n long removedDataCount = 0;\n long resetIdCount = 0;\n final FileDownloadHelper.IdGenerator idGenerator = getImpl().getIdGeneratorInstance();\n\n final long startTimestamp = System.currentTimeMillis();\n try {\n while (iterator.hasNext()) {\n boolean isInvalid = false;\n final FileDownloadModel model = iterator.next();\n do {\n if (model.getStatus() == FileDownloadStatus.progress\n || model.getStatus() == FileDownloadStatus.connected\n || model.getStatus() == FileDownloadStatus.error\n || (model.getStatus() == FileDownloadStatus.pending && model\n .getSoFar() > 0)\n ) {\n // Ensure can be covered by RESUME FROM BREAKPOINT.\n model.setStatus(FileDownloadStatus.paused);\n }\n final String targetFilePath = model.getTargetFilePath();\n if (targetFilePath == null) {\n // no target file path, can't used to resume from breakpoint.\n isInvalid = true;\n break;\n }\n\n final File targetFile = new File(targetFilePath);\n // consider check in new thread, but SQLite lock | file lock aways effect, so\n // sync\n if (model.getStatus() == FileDownloadStatus.paused\n && FileDownloadUtils.isBreakpointAvailable(model.getId(), model,\n model.getPath(), null)) {\n // can be reused in the old mechanism(no-temp-file).\n\n final File tempFile = new File(model.getTempFilePath());\n\n if (!tempFile.exists() && targetFile.exists()) {\n final boolean successRename = targetFile.renameTo(tempFile);\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadDatabase.class,\n \"resume from the old no-temp-file architecture \"\n + \"[%B], [%s]->[%s]\",\n successRename, targetFile.getPath(), tempFile.getPath());\n\n }\n }\n }\n\n /**\n * Remove {@code model} from DB if it can't used for judging whether the\n * old-downloaded file is valid for reused & it can't used for resuming from\n * BREAKPOINT, In other words, {@code model} is no use anymore for\n * FileDownloader.\n */\n if (model.getStatus() == FileDownloadStatus.pending && model.getSoFar() <= 0) {\n // This model is redundant.\n isInvalid = true;\n break;\n }\n\n if (!FileDownloadUtils.isBreakpointAvailable(model.getId(), model)) {\n // It can't used to resuming from breakpoint.\n isInvalid = true;\n break;\n }\n\n if (targetFile.exists()) {\n // It has already completed downloading.\n isInvalid = true;\n break;\n }\n\n } while (false);\n\n\n if (isInvalid) {\n iterator.remove();\n maintainer.onRemovedInvalidData(model);\n removedDataCount++;\n } else {\n final int oldId = model.getId();\n final int newId = idGenerator.transOldId(oldId, model.getUrl(), model.getPath(),\n model.isPathAsDirectory());\n if (newId != oldId) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadDatabase.class,\n \"the id is changed on restoring from db:\"\n + \" old[%d] -> new[%d]\",\n oldId, newId);\n }\n model.setId(newId);\n maintainer.changeFileDownloadModelId(oldId, model);\n resetIdCount++;\n }\n\n maintainer.onRefreshedValidData(model);\n refreshDataCount++;\n }\n }\n\n } finally {\n FileDownloadUtils.markConverted(FileDownloadHelper.getAppContext());\n maintainer.onFinishMaintain();\n // 566 data consumes about 140ms\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadDatabase.class,\n \"refreshed data count: %d , delete data count: %d, reset id count:\"\n + \" %d. consume %d\",\n refreshDataCount, removedDataCount, resetIdCount,\n System.currentTimeMillis() - startTimestamp);\n }\n }\n }\n}", "public class DownloadServiceConnectChangedEvent extends IDownloadEvent {\n public static final String ID = \"event.service.connect.changed\";\n\n public DownloadServiceConnectChangedEvent(final ConnectStatus status,\n final Class<?> serviceClass) {\n super(ID);\n\n this.status = status;\n this.serviceClass = serviceClass;\n }\n\n private final ConnectStatus status;\n\n public enum ConnectStatus {\n connected, disconnected,\n // the process hosting the service has crashed or been killed. (do not be unbound manually)\n lost\n }\n\n public ConnectStatus getStatus() {\n return status;\n }\n\n private final Class<?> serviceClass;\n\n public boolean isSuchService(final Class<?> serviceClass) {\n return this.serviceClass != null\n && this.serviceClass.getName().equals(serviceClass.getName());\n\n }\n}", "@SuppressWarnings({\"checkstyle:linelength\", \"checkstyle:constantname\"})\n/**\n * The downloading status.\n *\n * @see com.liulishuo.filedownloader.IFileDownloadMessenger\n * @see <a href=\"https://raw.githubusercontent.com/lingochamp/FileDownloader/master/art/filedownloadlistener_callback_flow.png\">Callback-Flow</a>\n */\npublic class FileDownloadStatus {\n // [-2^7, 2^7 -1]\n // by very beginning\n /**\n * When the task on {@code toLaunchPool} status, it means that the task is just into the\n * LaunchPool and is scheduled for launch.\n * <p>\n * The task is scheduled for launch and it isn't on the FileDownloadService yet.\n */\n public static final byte toLaunchPool = 10;\n /**\n * When the task on {@code toFileDownloadService} status, it means that the task is just post to\n * the FileDownloadService.\n * <p>\n * The task is posting to the FileDownloadService and after this status, this task can start.\n */\n public static final byte toFileDownloadService = 11;\n\n // by FileDownloadService\n /**\n * When the task on {@code pending} status, it means that the task is in the list on the\n * FileDownloadService and just waiting for start.\n * <p>\n * The task is waiting on the FileDownloadService.\n * <p>\n * The count of downloading simultaneously, you can configure in filedownloader.properties.\n */\n public static final byte pending = 1;\n /**\n * When the task on {@code started} status, it means that the network access thread of\n * downloading this task is started.\n * <p>\n * The task is downloading on the FileDownloadService.\n */\n public static final byte started = 6;\n /**\n * When the task on {@code connected} status, it means that the task is successfully connected\n * to the back-end.\n * <p>\n * The task is downloading on the FileDownloadService.\n */\n public static final byte connected = 2;\n /**\n * When the task on {@code progress} status, it means that the task is fetching data from the\n * back-end.\n * <p>\n * The task is downloading on the FileDownloadService.\n */\n public static final byte progress = 3;\n /**\n * When the task on {@code blockComplete} status, it means that the task has been completed\n * downloading successfully.\n * <p>\n * The task is completed downloading successfully and the action-flow is blocked for doing\n * something before callback completed method.\n */\n public static final byte blockComplete = 4;\n /**\n * When the task on {@code retry} status, it means that the task must occur some error, but\n * there is a valid chance to retry, so the task is retry to download again.\n * <p>\n * The task is restarting on the FileDownloadService.\n */\n public static final byte retry = 5;\n\n /**\n * When the task on {@code error} status, it means that the task must occur some error and there\n * isn't any valid chance to retry, so the task is finished with error.\n * <p>\n * The task is finished with an error.\n */\n public static final byte error = -1;\n /**\n * When the task on {@code paused} status, it means that the task is paused manually.\n * <p>\n * The task is finished with the pause action.\n */\n public static final byte paused = -2;\n /**\n * When the task on {@code completed} status, it means that the task is completed downloading\n * successfully.\n * <p>\n * The task is finished with completed downloading successfully.\n */\n public static final byte completed = -3;\n /**\n * When the task on {@code warn} status, it means that there is another same task(same url,\n * same path to store content) is running.\n * <p>\n * The task is finished with the warn status.\n */\n public static final byte warn = -4;\n\n /**\n * When the task on {@code INVALID_STATUS} status, it means that the task is IDLE.\n * <p>\n * The task is clear and it isn't launched.\n */\n public static final byte INVALID_STATUS = 0;\n\n public static boolean isOver(final int status) {\n return status < 0;\n }\n\n public static boolean isIng(final int status) {\n return status > 0;\n }\n\n public static boolean isKeepAhead(final int status, final int nextStatus) {\n if (status != progress && status != retry && status == nextStatus) {\n return false;\n }\n\n if (isOver(status)) {\n return false;\n }\n\n if (status >= pending && status <= started /** in FileDownloadService **/\n && nextStatus >= toLaunchPool && nextStatus <= toFileDownloadService) {\n return false;\n }\n\n switch (status) {\n case pending:\n switch (nextStatus) {\n case INVALID_STATUS:\n return false;\n default:\n return true;\n }\n case started:\n switch (nextStatus) {\n case INVALID_STATUS:\n case pending:\n return false;\n default:\n return true;\n }\n\n case connected:\n switch (nextStatus) {\n case INVALID_STATUS:\n case pending:\n case started:\n return false;\n default:\n return true;\n }\n case progress:\n switch (nextStatus) {\n case INVALID_STATUS:\n case pending:\n case started:\n case connected:\n return false;\n default:\n return true;\n }\n\n case retry:\n switch (nextStatus) {\n case pending:\n case started:\n return false;\n default:\n return true;\n }\n\n default:\n return true;\n }\n\n }\n\n @SuppressWarnings(\"checkstyle:avoidnestedblocks\")\n public static boolean isKeepFlow(final int status, final int nextStatus) {\n if (status != progress && status != retry && status == nextStatus) {\n return false;\n }\n\n if (isOver(status)) {\n return false;\n }\n\n if (nextStatus == paused) {\n return true;\n }\n\n if (nextStatus == error) {\n return true;\n }\n\n switch (status) {\n case INVALID_STATUS: {\n switch (nextStatus) {\n case toLaunchPool:\n return true;\n default:\n return false;\n }\n }\n case toLaunchPool:\n switch (nextStatus) {\n case toFileDownloadService:\n return true;\n default:\n return false;\n }\n case toFileDownloadService:\n switch (nextStatus) {\n case pending:\n case warn:\n case completed:\n return true;\n default:\n return false;\n }\n case pending:\n switch (nextStatus) {\n case started:\n return true;\n default:\n return false;\n }\n case retry:\n case started:\n switch (nextStatus) {\n case retry:\n case connected:\n return true;\n default:\n return false;\n }\n case connected:\n case progress:\n switch (nextStatus) {\n case progress:\n case completed:\n case retry:\n return true;\n default:\n return false;\n }\n default:\n return false;\n }\n\n }\n\n public static boolean isMoreLikelyCompleted(BaseDownloadTask task) {\n return task.getStatus() == INVALID_STATUS || task.getStatus() == progress;\n }\n}", "@SuppressWarnings({\"WeakerAccess\", \"deprecation\", \"DeprecatedIsStillUsed\"})\npublic class FileDownloadTaskAtom implements Parcelable {\n private String url;\n private String path;\n private long totalBytes;\n\n public FileDownloadTaskAtom(String url, String path, long totalBytes) {\n setUrl(url);\n setPath(path);\n setTotalBytes(totalBytes);\n }\n\n private int id;\n\n public int getId() {\n if (id != 0) {\n return id;\n }\n\n return id = FileDownloadUtils.generateId(getUrl(), getPath());\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public long getTotalBytes() {\n return totalBytes;\n }\n\n public void setTotalBytes(long totalBytes) {\n this.totalBytes = totalBytes;\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(this.url);\n dest.writeString(this.path);\n dest.writeLong(this.totalBytes);\n }\n\n protected FileDownloadTaskAtom(Parcel in) {\n this.url = in.readString();\n this.path = in.readString();\n this.totalBytes = in.readLong();\n }\n\n public static final Parcelable.Creator<FileDownloadTaskAtom> CREATOR =\n new Parcelable.Creator<FileDownloadTaskAtom>() {\n @Override\n public FileDownloadTaskAtom createFromParcel(Parcel source) {\n return new FileDownloadTaskAtom(source);\n }\n\n @Override\n public FileDownloadTaskAtom[] newArray(int size) {\n return new FileDownloadTaskAtom[size];\n }\n };\n}", "public class DownloadMgrInitialParams {\n\n private final InitCustomMaker mMaker;\n\n public DownloadMgrInitialParams() {\n mMaker = null;\n }\n\n public DownloadMgrInitialParams(InitCustomMaker maker) {\n this.mMaker = maker;\n }\n\n public int getMaxNetworkThreadCount() {\n if (mMaker == null) {\n return getDefaultMaxNetworkThreadCount();\n }\n\n final Integer customizeMaxNetworkThreadCount = mMaker.mMaxNetworkThreadCount;\n\n if (customizeMaxNetworkThreadCount != null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(this, \"initial FileDownloader manager with the customize \"\n + \"maxNetworkThreadCount: %d\", customizeMaxNetworkThreadCount);\n }\n\n return FileDownloadProperties\n .getValidNetworkThreadCount(customizeMaxNetworkThreadCount);\n } else {\n return getDefaultMaxNetworkThreadCount();\n }\n\n }\n\n public FileDownloadDatabase createDatabase() {\n if (mMaker == null || mMaker.mDatabaseCustomMaker == null) {\n return createDefaultDatabase();\n }\n final FileDownloadDatabase customDatabase = mMaker.mDatabaseCustomMaker.customMake();\n\n if (customDatabase != null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(this, \"initial FileDownloader manager with the customize \"\n + \"database: %s\", customDatabase);\n }\n return customDatabase;\n } else {\n return createDefaultDatabase();\n }\n }\n\n\n public FileDownloadHelper.OutputStreamCreator createOutputStreamCreator() {\n if (mMaker == null) {\n return createDefaultOutputStreamCreator();\n }\n\n final FileDownloadHelper.OutputStreamCreator outputStreamCreator =\n mMaker.mOutputStreamCreator;\n if (outputStreamCreator != null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(this, \"initial FileDownloader manager with the customize \"\n + \"output stream: %s\", outputStreamCreator);\n }\n return outputStreamCreator;\n } else {\n return createDefaultOutputStreamCreator();\n }\n }\n\n public FileDownloadHelper.ConnectionCreator createConnectionCreator() {\n if (mMaker == null) {\n return createDefaultConnectionCreator();\n }\n\n final FileDownloadHelper.ConnectionCreator connectionCreator = mMaker.mConnectionCreator;\n\n if (connectionCreator != null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(this, \"initial FileDownloader manager with the customize \"\n + \"connection creator: %s\", connectionCreator);\n }\n return connectionCreator;\n } else {\n return createDefaultConnectionCreator();\n }\n }\n\n public FileDownloadHelper.ConnectionCountAdapter createConnectionCountAdapter() {\n if (mMaker == null) {\n return createDefaultConnectionCountAdapter();\n }\n\n final FileDownloadHelper.ConnectionCountAdapter adapter = mMaker.mConnectionCountAdapter;\n if (adapter != null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(this, \"initial FileDownloader manager with the customize \"\n + \"connection count adapter: %s\", adapter);\n }\n return adapter;\n } else {\n return createDefaultConnectionCountAdapter();\n }\n }\n\n public FileDownloadHelper.IdGenerator createIdGenerator() {\n if (mMaker == null) {\n return createDefaultIdGenerator();\n }\n\n final FileDownloadHelper.IdGenerator idGenerator = mMaker.mIdGenerator;\n if (idGenerator != null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(this, \"initial FileDownloader manager with the customize \"\n + \"id generator: %s\", idGenerator);\n }\n\n return idGenerator;\n } else {\n return createDefaultIdGenerator();\n }\n }\n\n public ForegroundServiceConfig createForegroundServiceConfig() {\n if (mMaker == null) {\n return createDefaultForegroundServiceConfig();\n }\n\n final ForegroundServiceConfig foregroundServiceConfig = mMaker.mForegroundServiceConfig;\n if (foregroundServiceConfig != null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(this, \"initial FileDownloader manager with the customize \"\n + \"foreground service config: %s\", foregroundServiceConfig);\n }\n return foregroundServiceConfig;\n } else {\n return createDefaultForegroundServiceConfig();\n }\n }\n\n private ForegroundServiceConfig createDefaultForegroundServiceConfig() {\n return new ForegroundServiceConfig.Builder().needRecreateChannelId(true).build();\n }\n\n private FileDownloadHelper.IdGenerator createDefaultIdGenerator() {\n return new DefaultIdGenerator();\n }\n\n private int getDefaultMaxNetworkThreadCount() {\n return FileDownloadProperties.getImpl().downloadMaxNetworkThreadCount;\n }\n\n private FileDownloadDatabase createDefaultDatabase() {\n return new RemitDatabase();\n }\n\n private FileDownloadHelper.OutputStreamCreator createDefaultOutputStreamCreator() {\n return new FileDownloadRandomAccessFile.Creator();\n }\n\n private FileDownloadHelper.ConnectionCreator createDefaultConnectionCreator() {\n return new FileDownloadUrlConnection.Creator();\n }\n\n private FileDownloadHelper.ConnectionCountAdapter createDefaultConnectionCountAdapter() {\n return new DefaultConnectionCountAdapter();\n }\n\n public static class InitCustomMaker {\n FileDownloadHelper.DatabaseCustomMaker mDatabaseCustomMaker;\n Integer mMaxNetworkThreadCount;\n FileDownloadHelper.OutputStreamCreator mOutputStreamCreator;\n FileDownloadHelper.ConnectionCreator mConnectionCreator;\n FileDownloadHelper.ConnectionCountAdapter mConnectionCountAdapter;\n FileDownloadHelper.IdGenerator mIdGenerator;\n ForegroundServiceConfig mForegroundServiceConfig;\n\n /**\n * customize the id generator.\n *\n * @param idGenerator the id generator used for generating download identify manually.\n */\n public InitCustomMaker idGenerator(FileDownloadHelper.IdGenerator idGenerator) {\n this.mIdGenerator = idGenerator;\n return this;\n }\n\n /**\n * customize the connection count adapter.\n *\n * @param adapter the adapter used for determine how many connection will be used to\n * downloading the target task.\n * @return the connection count adapter.\n */\n public InitCustomMaker connectionCountAdapter(\n FileDownloadHelper.ConnectionCountAdapter adapter) {\n this.mConnectionCountAdapter = adapter;\n return this;\n }\n\n /**\n * customize the database component.\n * <p>\n * If you don't customize the data component, we use the result of\n * {@link #createDefaultDatabase()} as the default one.\n *\n * @param maker The database is used for storing the {@link FileDownloadModel}.\n * <p>\n * The data stored in the database is only used for task resumes from the\n * breakpoint.\n * <p>\n * The task of the data stored in the database must be a task that has not\n * finished downloading yet, and if the task has finished downloading, its data\n * will be {@link FileDownloadDatabase#remove(int)} from the database, since\n * that data is no longer available for resumption of its task pass.\n */\n public InitCustomMaker database(FileDownloadHelper.DatabaseCustomMaker maker) {\n this.mDatabaseCustomMaker = maker;\n return this;\n }\n\n /**\n * Customize the max network thread count.\n * <p>\n * If you don't customize the network thread count, we use the result of\n * {@link #getDefaultMaxNetworkThreadCount()} as the default one.\n *\n * @param maxNetworkThreadCount The maximum count of the network thread, what is the number\n * of simultaneous downloads in FileDownloader.\n * <p>\n * If this value is less than or equal to 0, the value will be\n * ignored and use\n * {@link FileDownloadProperties#downloadMaxNetworkThreadCount}\n * which is defined in filedownloader.properties instead.\n */\n public InitCustomMaker maxNetworkThreadCount(int maxNetworkThreadCount) {\n if (maxNetworkThreadCount > 0) {\n this.mMaxNetworkThreadCount = maxNetworkThreadCount;\n }\n return this;\n }\n\n /**\n * Customize the output stream component.\n * <p>\n * If you don't customize the output stream component, we use the result of\n * {@link #createDefaultOutputStreamCreator()} as the default one.\n *\n * @param creator The output stream creator is used for creating\n * {@link FileDownloadOutputStream} which is used to write the input stream\n * to the file for downloading.\n */\n public InitCustomMaker outputStreamCreator(FileDownloadHelper.OutputStreamCreator creator) {\n this.mOutputStreamCreator = creator;\n if (mOutputStreamCreator != null && !mOutputStreamCreator.supportSeek()) {\n if (!FileDownloadProperties.getImpl().fileNonPreAllocation) {\n throw new IllegalArgumentException(\n \"Since the provided FileDownloadOutputStream \"\n + \"does not support the seek function, if FileDownloader\"\n + \" pre-allocates file size at the beginning of the download,\"\n + \" it will can not be resumed from the breakpoint. If you need\"\n + \" to ensure that the resumption is available, please add and\"\n + \" set the value of 'file.non-pre-allocation' field to 'true'\"\n + \" in the 'filedownloader.properties' file which is in your\"\n + \" application assets folder manually for resolving this \"\n + \"problem.\");\n }\n }\n return this;\n }\n\n /**\n * Customize the connection component.\n * <p>\n * If you don't customize the connection component, we use the result of\n * {@link #createDefaultConnectionCreator()} as the default one.\n *\n * @param creator the connection creator will used for create the connection when start\n * downloading any task in the FileDownloader.\n */\n public InitCustomMaker connectionCreator(FileDownloadHelper.ConnectionCreator creator) {\n this.mConnectionCreator = creator;\n return this;\n }\n\n /**\n * customize configurations of foreground service\n * @param config determines how to show an notification for the foreground service\n */\n public InitCustomMaker foregroundServiceConfig(ForegroundServiceConfig config) {\n this.mForegroundServiceConfig = config;\n return this;\n }\n\n @SuppressWarnings(\"EmptyMethod\")\n public void commit() {\n // do nothing now.\n }\n\n @Override\n public String toString() {\n return FileDownloadUtils.formatString(\"component: database[%s], maxNetworkCount[%s],\"\n + \" outputStream[%s], connection[%s], connectionCountAdapter[%s]\",\n mDatabaseCustomMaker, mMaxNetworkThreadCount, mOutputStreamCreator,\n mConnectionCreator, mConnectionCountAdapter);\n }\n }\n}", "public class FileDownloadHelper {\n\n @SuppressLint(\"StaticFieldLeak\")\n private static Context APP_CONTEXT;\n\n public static void holdContext(final Context context) {\n APP_CONTEXT = context;\n }\n\n public static Context getAppContext() {\n return APP_CONTEXT;\n }\n\n @SuppressWarnings(\"UnusedParameters\")\n public interface IdGenerator {\n /**\n * Invoke this method when the data is restoring from the database.\n *\n * @param oldId the old download id which is generated through the different.\n * @param url the url path.\n * @param path the download path.\n * @param pathAsDirectory {@code true}: if the {@code path} is absolute directory to store\n * the downloading file, and the {@code filename} will be found in\n * contentDisposition from the response as default, if can't find\n * contentDisposition,the {@code filename} will be generated by\n * {@link FileDownloadUtils#generateFileName(String)} with\n * {@code url}.\n * </p>\n * {@code false}: if the {@code path} = (absolute directory/filename)\n * @return the new download id.\n */\n int transOldId(final int oldId, final String url, final String path,\n final boolean pathAsDirectory);\n\n /**\n * Invoke this method when there is a new task from very beginning.\n * <p>\n * Important Ting: this method would be used on the FileDownloadService and the upper-layer,\n * so as default FileDownloadService is running on the `:filedownloader` process, and\n * upper-layer\n * is on the user process, in this case, if you want to cache something on this instance, it\n * would be two different caches on two processes.\n * <p>\n * Tips: if you want the FileDownloadService runs on the upper-layer process too, just\n * config {@code process.non-separate=true} on the filedownloader.properties, more detail\n * please move to {@link FileDownloadProperties}\n *\n * @param url the download url.\n * @param path the download path.\n * @param pathAsDirectory {@code true}: if the {@code path} is absolute directory to store\n * the downloading file, and the {@code filename} will be found in\n * contentDisposition from the response as default, if can't find\n * contentDisposition,the {@code filename} will be generated by\n * {@link FileDownloadUtils#generateFileName(String)} with\n * {@code url}.\n * </p>\n * {@code false}: if the {@code path} = (absolute directory/filename)\n * @return the download task identify.\n */\n int generateId(final String url, final String path, final boolean pathAsDirectory);\n }\n\n @SuppressWarnings(\"UnusedParameters\")\n public interface ConnectionCountAdapter {\n /**\n * Before invoke this method to determine how many connection will be used to downloading\n * this task,\n * there are several conditions must be confirmed:\n * <p>\n * 1. the connection is support multiple connection(SUPPORT\"Partial Content(206)\" AND NOT\n * Chunked)\n * 2. the current {@link FileDownloadOutputStream} support seek(The default\n * one({@link FileDownloadRandomAccessFile} is support)\n * 3. this is a new task NOT resume from breakpoint( If the task resume from breakpoint\n * the connection count would be using\n * the one you determined when the task\n * first created ).\n * <p/>\n * The best strategy is refer to how much speed of each connection for the ip:port not file\n * size.\n *\n * @param downloadId the download id.\n * @param url the task url.\n * @param path the task path.\n * @param totalLength the total length of the file.\n * @return the count of connection you want for the task. the value must be large than 0.\n */\n int determineConnectionCount(int downloadId, String url, String path, long totalLength);\n }\n\n public interface DatabaseCustomMaker {\n /**\n * The database is used for storing the {@link FileDownloadModel}.\n * <p/>\n * The data stored in the database is only used for task resumes from the breakpoint.\n * <p>\n * The task of the data stored in the database must be a task that has not finished\n * downloading yet, and if the task has finished downloading, its data will be\n * {@link FileDownloadDatabase#remove(int)} from the database, since that data is no longer\n * available for resumption of its task pass.\n *\n * @return Nullable, Customize {@link FileDownloadDatabase} which will be used for storing\n * downloading model.\n * @see SqliteDatabaseImpl\n */\n FileDownloadDatabase customMake();\n }\n\n public interface OutputStreamCreator {\n /**\n * The output stream creator is used for creating {@link FileDownloadOutputStream} which is\n * used to write the input stream to the file for downloading.\n * <p>\n * <strong>Note:</strong> please create a output stream which append the content to the\n * exist file, which means that bytes would be written to the end of the file rather than\n * the beginning.\n *\n * @param file the file will used for storing the downloading content.\n * @return The output stream used to write downloading byte array to the {@code file}.\n * @throws FileNotFoundException if the file exists but is a directory\n * rather than a regular file, does not exist but cannot\n * be created, or cannot be opened for any other reason\n * @see FileDownloadRandomAccessFile.Creator\n */\n FileDownloadOutputStream create(File file) throws IOException;\n\n /**\n * @return {@code true} if the {@link FileDownloadOutputStream} is created through\n * {@link #create(File)} support {@link FileDownloadOutputStream#seek(long)} function.\n * If the {@link FileDownloadOutputStream} is created through {@link #create(File)} doesn't\n * support {@link FileDownloadOutputStream#seek(long)}, please return {@code false}, in\n * order to let the internal mechanism can predict this situation, and handle it smoothly.\n */\n boolean supportSeek();\n }\n\n public interface ConnectionCreator {\n /**\n * The connection creator is used for creating {@link FileDownloadConnection} component\n * which is used to use some protocol to connect to the remote server.\n *\n * @param url the uniform resource locator, which direct the aim resource we need to connect\n * @return The connection creator.\n * @throws IOException if an I/O exception occurs.\n */\n FileDownloadConnection create(String url) throws IOException;\n }\n\n /**\n * @param id the {@code id} used for filter out which task would be notified the\n * 'completed' message if need.\n * @param path if the file with {@code path} is exist it means the relate task would\n * be completed.\n * @param forceReDownload whether the task is force to re-download ignore whether the file has\n * been exist or not.\n * @param flowDirectly {@code true} if flow the message if need directly without throw to the\n * message-queue.\n * @return whether the task with {@code id} has been downloaded.\n */\n public static boolean inspectAndInflowDownloaded(int id, String path, boolean forceReDownload,\n boolean flowDirectly) {\n if (forceReDownload) {\n return false;\n }\n\n if (path != null) {\n final File file = new File(path);\n if (file.exists()) {\n MessageSnapshotFlow.getImpl().inflow(MessageSnapshotTaker.\n catchCanReusedOldFile(id, file, flowDirectly));\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * @param id the {@code id} used for filter out which task would be notified the\n * 'warn' message if need.\n * @param model the target model will be checked for judging whether it is downloading.\n * @param monitor the monitor for download-thread.\n * @param flowDirectly {@code true} if flow the message if need directly without throw to the\n * message-queue.\n * @return whether the {@code model} is downloading.\n */\n public static boolean inspectAndInflowDownloading(int id, FileDownloadModel model,\n IThreadPoolMonitor monitor,\n boolean flowDirectly) {\n if (monitor.isDownloading(model)) {\n MessageSnapshotFlow.getImpl().\n inflow(MessageSnapshotTaker.catchWarn(id, model.getSoFar(), model.getTotal(),\n flowDirectly));\n return true;\n }\n\n return false;\n }\n\n /**\n * @param id the {@code id} used for filter out which task would be notified the\n * 'error' message if need.\n * @param sofar the so far bytes of the current checking-task.\n * @param tempFilePath the temp file path(file path used for downloading) for the current\n * checking-task.\n * @param targetFilePath the target file path for the current checking-task.\n * @param monitor the monitor for download-thread.\n * @return whether the task with {@code id} is refused to start, because of there is an another\n * running task with the same {@code tempFilePath}.\n */\n public static boolean inspectAndInflowConflictPath(int id, long sofar,\n String tempFilePath, String targetFilePath,\n IThreadPoolMonitor monitor) {\n if (targetFilePath != null && tempFilePath != null) {\n final int anotherSameTempPathTaskId =\n monitor.findRunningTaskIdBySameTempPath(tempFilePath, id);\n if (anotherSameTempPathTaskId != 0) {\n MessageSnapshotFlow.getImpl().\n inflow(MessageSnapshotTaker.catchException(id, sofar,\n new PathConflictException(anotherSameTempPathTaskId, tempFilePath,\n targetFilePath)));\n return true;\n }\n }\n\n return false;\n }\n}", "public class FileDownloadLog {\n\n public static boolean NEED_LOG = false;\n\n private static final String TAG = \"FileDownloader.\";\n\n public static void e(Object o, Throwable e, String msg, Object... args) {\n log(Log.ERROR, o, e, msg, args);\n }\n\n public static void e(Object o, String msg, Object... args) {\n log(Log.ERROR, o, msg, args);\n }\n\n public static void i(Object o, String msg, Object... args) {\n log(Log.INFO, o, msg, args);\n }\n\n public static void d(Object o, String msg, Object... args) {\n log(Log.DEBUG, o, msg, args);\n }\n\n public static void w(Object o, String msg, Object... args) {\n log(Log.WARN, o, msg, args);\n }\n\n public static void v(Object o, String msg, Object... args) {\n log(Log.VERBOSE, o, msg, args);\n }\n\n private static void log(int priority, Object o, String message, Object... args) {\n log(priority, o, null, message, args);\n }\n\n private static void log(int priority, Object o, Throwable throwable, String message,\n Object... args) {\n final boolean force = priority >= Log.WARN;\n if (!force && !NEED_LOG) {\n return;\n }\n\n Log.println(priority, getTag(o), FileDownloadUtils.formatString(message, args));\n if (throwable != null) {\n throwable.printStackTrace();\n }\n }\n\n private static String getTag(final Object o) {\n return TAG + ((o instanceof Class)\n ? ((Class) o).getSimpleName() : o.getClass().getSimpleName());\n }\n}", "public class FileDownloadProperties {\n\n private static final String KEY_HTTP_LENIENT = \"http.lenient\";\n private static final String KEY_PROCESS_NON_SEPARATE = \"process.non-separate\";\n private static final String KEY_DOWNLOAD_MIN_PROGRESS_STEP = \"download.min-progress-step\";\n private static final String KEY_DOWNLOAD_MIN_PROGRESS_TIME = \"download.min-progress-time\";\n private static final String KEY_DOWNLOAD_MAX_NETWORK_THREAD_COUNT =\n \"download.max-network-thread-count\";\n private static final String KEY_FILE_NON_PRE_ALLOCATION = \"file.non-pre-allocation\";\n private static final String KEY_BROADCAST_COMPLETED = \"broadcast.completed\";\n private static final String KEY_TRIAL_CONNECTION_HEAD_METHOD\n = \"download.trial-connection-head-method\";\n\n public final int downloadMinProgressStep;\n public final long downloadMinProgressTime;\n public final boolean httpLenient;\n public final boolean processNonSeparate;\n public final int downloadMaxNetworkThreadCount;\n public final boolean fileNonPreAllocation;\n public final boolean broadcastCompleted;\n public final boolean trialConnectionHeadMethod;\n\n public static class HolderClass {\n private static final FileDownloadProperties INSTANCE = new FileDownloadProperties();\n }\n\n public static FileDownloadProperties getImpl() {\n return HolderClass.INSTANCE;\n }\n\n private static final String TRUE_STRING = \"true\";\n private static final String FALSE_STRING = \"false\";\n\n // init properties, normally consume <= 2ms\n private FileDownloadProperties() {\n if (FileDownloadHelper.getAppContext() == null) {\n throw new IllegalStateException(\"Please invoke the 'FileDownloader#setup' before using \"\n + \"FileDownloader. If you want to register some components on FileDownloader \"\n + \"please invoke the 'FileDownloader#setupOnApplicationOnCreate' on the \"\n + \"'Application#onCreate' first.\");\n }\n\n final long start = System.currentTimeMillis();\n String httpLenient = null;\n String processNonSeparate = null;\n String downloadMinProgressStep = null;\n String downloadMinProgressTime = null;\n String downloadMaxNetworkThreadCount = null;\n String fileNonPreAllocation = null;\n String broadcastCompleted = null;\n String downloadTrialConnectionHeadMethod = null;\n\n Properties p = new Properties();\n InputStream inputStream = null;\n\n try {\n inputStream = FileDownloadHelper.getAppContext().getAssets().\n open(\"filedownloader.properties\");\n if (inputStream != null) {\n p.load(inputStream);\n httpLenient = p.getProperty(KEY_HTTP_LENIENT);\n processNonSeparate = p.getProperty(KEY_PROCESS_NON_SEPARATE);\n downloadMinProgressStep = p.getProperty(KEY_DOWNLOAD_MIN_PROGRESS_STEP);\n downloadMinProgressTime = p.getProperty(KEY_DOWNLOAD_MIN_PROGRESS_TIME);\n downloadMaxNetworkThreadCount = p\n .getProperty(KEY_DOWNLOAD_MAX_NETWORK_THREAD_COUNT);\n fileNonPreAllocation = p.getProperty(KEY_FILE_NON_PRE_ALLOCATION);\n broadcastCompleted = p.getProperty(KEY_BROADCAST_COMPLETED);\n downloadTrialConnectionHeadMethod = p.getProperty(KEY_TRIAL_CONNECTION_HEAD_METHOD);\n }\n } catch (IOException e) {\n if (e instanceof FileNotFoundException) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadProperties.class,\n \"not found filedownloader.properties\");\n }\n } else {\n e.printStackTrace();\n }\n } finally {\n if (inputStream != null) {\n try {\n inputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n\n //http.lenient\n if (httpLenient != null) {\n if (!httpLenient.equals(TRUE_STRING) && !httpLenient.equals(FALSE_STRING)) {\n throw new IllegalStateException(\n FileDownloadUtils.formatString(\"the value of '%s' must be '%s' or '%s'\",\n KEY_HTTP_LENIENT, TRUE_STRING, FALSE_STRING));\n }\n this.httpLenient = httpLenient.equals(TRUE_STRING);\n } else {\n this.httpLenient = false;\n }\n\n //process.non-separate\n if (processNonSeparate != null) {\n if (!processNonSeparate.equals(TRUE_STRING)\n && !processNonSeparate.equals(FALSE_STRING)) {\n throw new IllegalStateException(\n FileDownloadUtils.formatString(\"the value of '%s' must be '%s' or '%s'\",\n KEY_PROCESS_NON_SEPARATE, TRUE_STRING, FALSE_STRING));\n }\n this.processNonSeparate = processNonSeparate.equals(TRUE_STRING);\n } else {\n this.processNonSeparate = false;\n }\n\n //download.min-progress-step\n if (downloadMinProgressStep != null) {\n int processDownloadMinProgressStep = Integer.valueOf(downloadMinProgressStep);\n processDownloadMinProgressStep = Math.max(0, processDownloadMinProgressStep);\n this.downloadMinProgressStep = processDownloadMinProgressStep;\n } else {\n this.downloadMinProgressStep = 65536;\n }\n\n //download.min-progress-time\n if (downloadMinProgressTime != null) {\n long processDownloadMinProgressTime = Long.valueOf(downloadMinProgressTime);\n processDownloadMinProgressTime = Math.max(0, processDownloadMinProgressTime);\n this.downloadMinProgressTime = processDownloadMinProgressTime;\n } else {\n this.downloadMinProgressTime = 2000L;\n }\n\n //download.max-network-thread-count\n if (downloadMaxNetworkThreadCount != null) {\n this.downloadMaxNetworkThreadCount = getValidNetworkThreadCount(\n Integer.valueOf(downloadMaxNetworkThreadCount));\n } else {\n this.downloadMaxNetworkThreadCount = 3;\n }\n\n // file.non-pre-allocation\n if (fileNonPreAllocation != null) {\n if (!fileNonPreAllocation.equals(TRUE_STRING)\n && !fileNonPreAllocation.equals(FALSE_STRING)) {\n throw new IllegalStateException(\n FileDownloadUtils.formatString(\"the value of '%s' must be '%s' or '%s'\",\n KEY_FILE_NON_PRE_ALLOCATION, TRUE_STRING, FALSE_STRING));\n }\n this.fileNonPreAllocation = fileNonPreAllocation.equals(TRUE_STRING);\n } else {\n this.fileNonPreAllocation = false;\n }\n\n // broadcast.completed\n if (broadcastCompleted != null) {\n if (!broadcastCompleted.equals(TRUE_STRING)\n && !broadcastCompleted.equals(FALSE_STRING)) {\n throw new IllegalStateException(\n FileDownloadUtils.formatString(\"the value of '%s' must be '%s' or '%s'\",\n KEY_BROADCAST_COMPLETED, TRUE_STRING, FALSE_STRING));\n }\n this.broadcastCompleted = broadcastCompleted.equals(TRUE_STRING);\n\n } else {\n this.broadcastCompleted = false;\n }\n\n // download.trial-connection-head-method\n if (downloadTrialConnectionHeadMethod != null) {\n if (!downloadTrialConnectionHeadMethod.equals(TRUE_STRING)\n && !downloadTrialConnectionHeadMethod.equals(FALSE_STRING)) {\n throw new IllegalStateException(\n FileDownloadUtils.formatString(\"the value of '%s' must be '%s' or '%s'\",\n KEY_TRIAL_CONNECTION_HEAD_METHOD, TRUE_STRING, FALSE_STRING));\n }\n this.trialConnectionHeadMethod = downloadTrialConnectionHeadMethod.equals(TRUE_STRING);\n } else {\n this.trialConnectionHeadMethod = false;\n }\n\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.i(FileDownloadProperties.class, \"init properties %d\\n load properties:\"\n + \" %s=%B; %s=%B; %s=%d; %s=%d; %s=%d; %s=%B; %s=%B; %s=%B\",\n System.currentTimeMillis() - start,\n KEY_HTTP_LENIENT, this.httpLenient,\n KEY_PROCESS_NON_SEPARATE, this.processNonSeparate,\n KEY_DOWNLOAD_MIN_PROGRESS_STEP, this.downloadMinProgressStep,\n KEY_DOWNLOAD_MIN_PROGRESS_TIME, this.downloadMinProgressTime,\n KEY_DOWNLOAD_MAX_NETWORK_THREAD_COUNT, this.downloadMaxNetworkThreadCount,\n KEY_FILE_NON_PRE_ALLOCATION, this.fileNonPreAllocation,\n KEY_BROADCAST_COMPLETED, this.broadcastCompleted,\n KEY_TRIAL_CONNECTION_HEAD_METHOD, this.trialConnectionHeadMethod);\n }\n }\n\n public static int getValidNetworkThreadCount(int requireCount) {\n int maxValidNetworkThreadCount = 12;\n int minValidNetworkThreadCount = 1;\n\n if (requireCount > maxValidNetworkThreadCount) {\n FileDownloadLog.w(FileDownloadProperties.class, \"require the count of network thread \"\n + \"is %d, what is more than the max valid count(%d), so adjust to %d \"\n + \"auto\",\n requireCount, maxValidNetworkThreadCount, maxValidNetworkThreadCount);\n return maxValidNetworkThreadCount;\n } else if (requireCount < minValidNetworkThreadCount) {\n FileDownloadLog.w(FileDownloadProperties.class, \"require the count of network thread \"\n + \"is %d, what is less than the min valid count(%d), so adjust to %d\"\n + \" auto\",\n requireCount, minValidNetworkThreadCount, minValidNetworkThreadCount);\n return minValidNetworkThreadCount;\n }\n\n return requireCount;\n }\n}", "@SuppressWarnings({\"SameParameterValue\", \"WeakerAccess\"})\npublic class FileDownloadUtils {\n\n private static int minProgressStep = 65536;\n private static long minProgressTime = 2000;\n\n /**\n * @param minProgressStep The minimum bytes interval in per step to sync to the file and the\n * database.\n * <p>\n * Used for adjudging whether is time to sync the downloaded so far bytes\n * to database and make sure sync the downloaded buffer to local file.\n * <p/>\n * More smaller more frequently, then download more slowly, but will more\n * safer in scene of the process is killed unexpected.\n * <p/>\n * Default 65536, which follow the value in\n * com.android.providers.downloads.Constants.\n * @see com.liulishuo.filedownloader.download.DownloadStatusCallback#onProgress(long)\n * @see #setMinProgressTime(long)\n */\n public static void setMinProgressStep(int minProgressStep) throws IllegalAccessException {\n if (isDownloaderProcess(FileDownloadHelper.getAppContext())) {\n FileDownloadUtils.minProgressStep = minProgressStep;\n } else {\n throw new IllegalAccessException(\"This value is used in the :filedownloader process,\"\n + \" so set this value in your process is without effect. You can add \"\n + \"'process.non-separate=true' in 'filedownloader.properties' to share the main\"\n + \" process to FileDownloadService. Or you can configure this value in \"\n + \"'filedownloader.properties' by 'download.min-progress-step'.\");\n }\n }\n\n /**\n * @param minProgressTime The minimum millisecond interval in per time to sync to the file and\n * the database.\n * <p>\n * Used for adjudging whether is time to sync the downloaded so far bytes\n * to database and make sure sync the downloaded buffer to local file.\n * <p/>\n * More smaller more frequently, then download more slowly, but will more\n * safer in scene of the process is killed unexpected.\n * <p/>\n * Default 2000, which follow the value in\n * com.android.providers.downloads.Constants.\n * @see com.liulishuo.filedownloader.download.DownloadStatusCallback#onProgress(long)\n * @see #setMinProgressStep(int)\n */\n public static void setMinProgressTime(long minProgressTime) throws IllegalAccessException {\n if (isDownloaderProcess(FileDownloadHelper.getAppContext())) {\n FileDownloadUtils.minProgressTime = minProgressTime;\n } else {\n throw new IllegalAccessException(\"This value is used in the :filedownloader process,\"\n + \" so set this value in your process is without effect. You can add \"\n + \"'process.non-separate=true' in 'filedownloader.properties' to share the main\"\n + \" process to FileDownloadService. Or you can configure this value in \"\n + \"'filedownloader.properties' by 'download.min-progress-time'.\");\n }\n }\n\n public static int getMinProgressStep() {\n return minProgressStep;\n }\n\n public static long getMinProgressTime() {\n return minProgressTime;\n }\n\n /**\n * Checks whether the filename looks legitimate.\n */\n @SuppressWarnings({\"SameReturnValue\", \"UnusedParameters\"})\n public static boolean isFilenameValid(String filename) {\n// filename = filename.replaceFirst(\"/+\", \"/\"); // normalize leading\n // slashes\n// return filename.startsWith(Environment.getDownloadCacheDirectory()\n// .toString())\n// || filename.startsWith(Environment\n// .getExternalStorageDirectory().toString());\n return true;\n }\n\n private static String defaultSaveRootPath;\n\n public static String getDefaultSaveRootPath() {\n if (!TextUtils.isEmpty(defaultSaveRootPath)) {\n return defaultSaveRootPath;\n }\n\n boolean useExternalStorage = false;\n if (FileDownloadHelper.getAppContext().getExternalCacheDir() != null) {\n if (Environment.getExternalStorageState().equals(\"mounted\")) {\n if (Environment.getExternalStorageDirectory().getFreeSpace() > 0) {\n useExternalStorage = true;\n }\n }\n }\n\n if (useExternalStorage) {\n return FileDownloadHelper.getAppContext().getExternalCacheDir().getAbsolutePath();\n } else {\n return FileDownloadHelper.getAppContext().getCacheDir().getAbsolutePath();\n }\n }\n\n public static String getDefaultSaveFilePath(final String url) {\n return generateFilePath(getDefaultSaveRootPath(), generateFileName(url));\n }\n\n public static String generateFileName(final String url) {\n return md5(url);\n }\n\n /**\n * @see #getTargetFilePath(String, boolean, String)\n */\n public static String generateFilePath(String directory, String filename) {\n if (filename == null) {\n throw new IllegalStateException(\"can't generate real path, the file name is null\");\n }\n\n if (directory == null) {\n throw new IllegalStateException(\"can't generate real path, the directory is null\");\n }\n\n return formatString(\"%s%s%s\", directory, File.separator, filename);\n }\n\n /**\n * The path is used as the default directory in the case of the task without set path.\n *\n * @param path default root path for save download file.\n * @see com.liulishuo.filedownloader.BaseDownloadTask#setPath(String, boolean)\n */\n public static void setDefaultSaveRootPath(final String path) {\n defaultSaveRootPath = path;\n }\n\n /**\n * @param targetPath The target path for the download task.\n * @return The temp path is {@code targetPath} in downloading status; The temp path is used for\n * storing the file not completed downloaded yet.\n */\n public static String getTempPath(final String targetPath) {\n return FileDownloadUtils.formatString(\"%s.temp\", targetPath);\n }\n\n /**\n * @param url The downloading URL.\n * @param path The absolute file path.\n * @return The download id.\n */\n public static int generateId(final String url, final String path) {\n return CustomComponentHolder.getImpl().getIdGeneratorInstance()\n .generateId(url, path, false);\n }\n\n /**\n * @param url The downloading URL.\n * @param path If {@code pathAsDirectory} is {@code true}, {@code path} would be the absolute\n * directory to place the file;\n * If {@code pathAsDirectory} is {@code false}, {@code path} would be the absolute\n * file path.\n * @return The download id.\n */\n public static int generateId(final String url, final String path,\n final boolean pathAsDirectory) {\n return CustomComponentHolder.getImpl().getIdGeneratorInstance()\n .generateId(url, path, pathAsDirectory);\n }\n\n public static String md5(String string) {\n byte[] hash;\n try {\n hash = MessageDigest.getInstance(\"MD5\").digest(string.getBytes(\"UTF-8\"));\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(\"Huh, MD5 should be supported?\", e);\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Huh, UTF-8 should be supported?\", e);\n }\n\n StringBuilder hex = new StringBuilder(hash.length * 2);\n for (byte b : hash) {\n if ((b & 0xFF) < 0x10) hex.append(\"0\");\n hex.append(Integer.toHexString(b & 0xFF));\n }\n return hex.toString();\n }\n\n\n public static String getStack() {\n return getStack(true);\n }\n\n public static String getStack(final boolean printLine) {\n StackTraceElement[] stackTrace = new Throwable().getStackTrace();\n return getStack(stackTrace, printLine);\n }\n\n public static String getStack(final StackTraceElement[] stackTrace, final boolean printLine) {\n if ((stackTrace == null) || (stackTrace.length < 4)) {\n return \"\";\n }\n\n StringBuilder t = new StringBuilder();\n\n for (int i = 3; i < stackTrace.length; i++) {\n if (!stackTrace[i].getClassName().contains(\"com.liulishuo.filedownloader\")) {\n continue;\n }\n t.append(\"[\");\n t.append(stackTrace[i].getClassName()\n .substring(\"com.liulishuo.filedownloader\".length()));\n t.append(\":\");\n t.append(stackTrace[i].getMethodName());\n if (printLine) {\n t.append(\"(\").append(stackTrace[i].getLineNumber()).append(\")]\");\n } else {\n t.append(\"]\");\n }\n }\n return t.toString();\n }\n\n private static Boolean isDownloaderProcess;\n\n /**\n * @param context the context\n * @return {@code true} if the FileDownloadService is allowed to run on the current process,\n * {@code false} otherwise.\n */\n public static boolean isDownloaderProcess(final Context context) {\n if (isDownloaderProcess != null) {\n return isDownloaderProcess;\n }\n\n boolean result = false;\n do {\n if (FileDownloadProperties.getImpl().processNonSeparate) {\n result = true;\n break;\n }\n\n int pid = android.os.Process.myPid();\n final ActivityManager activityManager = (ActivityManager) context.\n getSystemService(Context.ACTIVITY_SERVICE);\n\n if (activityManager == null) {\n FileDownloadLog.w(FileDownloadUtils.class, \"fail to get the activity manager!\");\n return false;\n }\n\n final List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfoList =\n activityManager.getRunningAppProcesses();\n\n if (null == runningAppProcessInfoList || runningAppProcessInfoList.isEmpty()) {\n FileDownloadLog\n .w(FileDownloadUtils.class, \"The running app process info list from\"\n + \" ActivityManager is null or empty, maybe current App is not \"\n + \"running.\");\n return false;\n }\n\n for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcessInfoList) {\n if (processInfo.pid == pid) {\n result = processInfo.processName.endsWith(\":filedownloader\");\n break;\n }\n }\n\n } while (false);\n\n isDownloaderProcess = result;\n return isDownloaderProcess;\n }\n\n public static String[] convertHeaderString(final String nameAndValuesString) {\n final String[] lineString = nameAndValuesString.split(\"\\n\");\n final String[] namesAndValues = new String[lineString.length * 2];\n\n for (int i = 0; i < lineString.length; i++) {\n final String[] nameAndValue = lineString[i].split(\": \");\n /**\n * @see Headers#toString()\n * @see Headers#name(int)\n * @see Headers#value(int)\n */\n namesAndValues[i * 2] = nameAndValue[0];\n namesAndValues[i * 2 + 1] = nameAndValue[1];\n }\n\n return namesAndValues;\n }\n\n public static long getFreeSpaceBytes(final String path) {\n long freeSpaceBytes;\n final StatFs statFs = new StatFs(path);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {\n freeSpaceBytes = statFs.getAvailableBytes();\n } else {\n //noinspection deprecation\n freeSpaceBytes = statFs.getAvailableBlocks() * (long) statFs.getBlockSize();\n }\n\n return freeSpaceBytes;\n }\n\n public static String formatString(final String msg, Object... args) {\n return String.format(Locale.ENGLISH, msg, args);\n }\n\n private static final String INTERNAL_DOCUMENT_NAME = \"filedownloader\";\n private static final String OLD_FILE_CONVERTED_FILE_NAME = \".old_file_converted\";\n\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n public static void markConverted(final Context context) {\n final File file = getConvertedMarkedFile(context);\n try {\n file.getParentFile().mkdirs();\n file.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private static Boolean filenameConverted = null;\n\n /**\n * @return Whether has converted all files' name from 'filename'(in old architecture) to\n * 'filename.temp', if it's in downloading state.\n * <p>\n * If {@code true}, You can check whether the file has completed downloading with\n * {@link File#exists()} directly.\n * <p>\n * when {@link FileDownloadService#onCreate()} is invoked, This value will be assigned to\n * {@code true} only once since you upgrade the filedownloader version to 0.3.3 or higher.\n */\n public static boolean isFilenameConverted(final Context context) {\n if (filenameConverted == null) {\n filenameConverted = getConvertedMarkedFile(context).exists();\n }\n\n return filenameConverted;\n }\n\n public static File getConvertedMarkedFile(final Context context) {\n return new File(context.getFilesDir().getAbsolutePath() + File.separator\n + INTERNAL_DOCUMENT_NAME, OLD_FILE_CONVERTED_FILE_NAME);\n }\n\n // note on https://tools.ietf.org/html/rfc5987\n private static final Pattern CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN =\n Pattern.compile(\"attachment;\\\\s*filename\\\\*\\\\s*=\\\\s*\\\"*([^\\\"]*)'\\\\S*'([^\\\"]*)\\\"*\");\n // note on http://www.ietf.org/rfc/rfc1806.txt\n private static final Pattern CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN =\n Pattern.compile(\"attachment;\\\\s*filename\\\\s*=\\\\s*\\\"*([^\\\"\\\\n]*)\\\"*\");\n\n public static long parseContentRangeFoInstanceLength(String contentRange) {\n if (contentRange == null) return -1;\n\n final String[] session = contentRange.split(\"/\");\n if (session.length >= 2) {\n try {\n return Long.parseLong(session[1]);\n } catch (NumberFormatException e) {\n FileDownloadLog.w(FileDownloadUtils.class, \"parse instance length failed with %s\",\n contentRange);\n }\n }\n\n return -1;\n }\n\n /**\n * The same to com.android.providers.downloads.Helpers#parseContentDisposition.\n * </p>\n * Parse the Content-Disposition HTTP Header. The format of the header\n * is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html\n * This header provides a filename for content that is going to be\n * downloaded to the file system. We only support the attachment type.\n */\n public static String parseContentDisposition(String contentDisposition) {\n if (contentDisposition == null) {\n return null;\n }\n\n try {\n Matcher m = CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN.matcher(contentDisposition);\n if (m.find()) {\n String charset = m.group(1);\n String encodeFileName = m.group(2);\n return URLDecoder.decode(encodeFileName, charset);\n }\n\n m = CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN.matcher(contentDisposition);\n if (m.find()) {\n return m.group(1);\n }\n } catch (IllegalStateException | UnsupportedEncodingException ignore) {\n // This function is defined as returning null when it can't parse the header\n }\n return null;\n }\n\n /**\n * @param path If {@code pathAsDirectory} is true, the {@code path} would be the\n * absolute directory to settle down the file;\n * If {@code pathAsDirectory} is false, the {@code path} would be the\n * absolute file path.\n * @param pathAsDirectory whether the {@code path} is a directory.\n * @param filename the file's name.\n * @return the absolute path of the file. If can't find by params, will return {@code null}.\n */\n public static String getTargetFilePath(String path, boolean pathAsDirectory, String filename) {\n if (path == null) {\n return null;\n }\n\n if (pathAsDirectory) {\n if (filename == null) {\n return null;\n }\n\n return FileDownloadUtils.generateFilePath(path, filename);\n } else {\n return path;\n }\n }\n\n /**\n * The same to {@link File#getParent()}, for non-creating a file object.\n *\n * @return this file's parent pathname or {@code null}.\n */\n public static String getParent(final String path) {\n int length = path.length(), firstInPath = 0;\n if (File.separatorChar == '\\\\' && length > 2 && path.charAt(1) == ':') {\n firstInPath = 2;\n }\n int index = path.lastIndexOf(File.separatorChar);\n if (index == -1 && firstInPath > 0) {\n index = 2;\n }\n if (index == -1 || path.charAt(length - 1) == File.separatorChar) {\n return null;\n }\n if (path.indexOf(File.separatorChar) == index\n && path.charAt(firstInPath) == File.separatorChar) {\n return path.substring(0, index + 1);\n }\n return path.substring(0, index);\n }\n\n private static final String FILEDOWNLOADER_PREFIX = \"FileDownloader\";\n\n public static String getThreadPoolName(String name) {\n return FILEDOWNLOADER_PREFIX + \"-\" + name;\n }\n\n public static boolean isNetworkNotOnWifiType() {\n final ConnectivityManager manager = (ConnectivityManager) FileDownloadHelper.getAppContext()\n .\n getSystemService(Context.CONNECTIVITY_SERVICE);\n\n if (manager == null) {\n FileDownloadLog.w(FileDownloadUtils.class, \"failed to get connectivity manager!\");\n return true;\n }\n\n //noinspection MissingPermission, because we check permission accessable when invoked\n final NetworkInfo info = manager.getActiveNetworkInfo();\n\n return info == null || info.getType() != ConnectivityManager.TYPE_WIFI;\n }\n\n public static boolean checkPermission(String permission) {\n final int perm = FileDownloadHelper.getAppContext()\n .checkCallingOrSelfPermission(permission);\n return perm == PackageManager.PERMISSION_GRANTED;\n }\n\n public static long convertContentLengthString(String s) {\n if (s == null) return -1;\n try {\n return Long.parseLong(s);\n } catch (NumberFormatException e) {\n return -1;\n }\n }\n\n public static String findEtag(final int id, FileDownloadConnection connection) {\n if (connection == null) {\n throw new RuntimeException(\"connection is null when findEtag\");\n }\n\n final String newEtag = connection.getResponseHeaderField(\"Etag\");\n\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class, \"etag find %s for task(%d)\", newEtag, id);\n }\n\n return newEtag;\n }\n\n // accept range is effect by response code and Accept-Ranges header field.\n public static boolean isAcceptRange(int responseCode, FileDownloadConnection connection) {\n if (responseCode == HttpURLConnection.HTTP_PARTIAL\n || responseCode == FileDownloadConnection.RESPONSE_CODE_FROM_OFFSET) return true;\n\n final String acceptRanges = connection.getResponseHeaderField(\"Accept-Ranges\");\n return \"bytes\".equals(acceptRanges);\n }\n\n // because of we using one of two HEAD method to request or using range:0-0 to trial connection\n // only if connection api not support, so we test content-range first and then test\n // content-length.\n public static long findInstanceLengthForTrial(FileDownloadConnection connection) {\n long length = findInstanceLengthFromContentRange(connection);\n if (length < 0) {\n length = TOTAL_VALUE_IN_CHUNKED_RESOURCE;\n FileDownloadLog.w(FileDownloadUtils.class, \"don't get instance length from\"\n + \"Content-Range header\");\n }\n // the response of HEAD method is not very canonical sometimes(it depends on server\n // implementation)\n // so that it's uncertain the content-length is the same as the response of GET method if\n // content-length=0, so we have to filter this case in here.\n if (length == 0 && FileDownloadProperties.getImpl().trialConnectionHeadMethod) {\n length = TOTAL_VALUE_IN_CHUNKED_RESOURCE;\n }\n\n return length;\n }\n\n public static long findInstanceLengthFromContentRange(FileDownloadConnection connection) {\n return parseContentRangeFoInstanceLength(getContentRangeHeader(connection));\n }\n\n private static String getContentRangeHeader(FileDownloadConnection connection) {\n return connection.getResponseHeaderField(\"Content-Range\");\n }\n\n public static long findContentLength(final int id, FileDownloadConnection connection) {\n long contentLength = convertContentLengthString(\n connection.getResponseHeaderField(\"Content-Length\"));\n final String transferEncoding = connection.getResponseHeaderField(\"Transfer-Encoding\");\n\n if (contentLength < 0) {\n final boolean isEncodingChunked = transferEncoding != null && transferEncoding\n .equals(\"chunked\");\n if (!isEncodingChunked) {\n // not chunked transfer encoding data\n if (FileDownloadProperties.getImpl().httpLenient) {\n // do not response content-length either not chunk transfer encoding,\n // but HTTP lenient is true, so handle as the case of transfer encoding chunk\n contentLength = TOTAL_VALUE_IN_CHUNKED_RESOURCE;\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog\n .d(FileDownloadUtils.class, \"%d response header is not legal but \"\n + \"HTTP lenient is true, so handle as the case of \"\n + \"transfer encoding chunk\", id);\n }\n } else {\n throw new FileDownloadGiveUpRetryException(\"can't know the size of the \"\n + \"download file, and its Transfer-Encoding is not Chunked \"\n + \"either.\\nyou can ignore such exception by add \"\n + \"http.lenient=true to the filedownloader.properties\");\n }\n } else {\n contentLength = TOTAL_VALUE_IN_CHUNKED_RESOURCE;\n }\n }\n\n return contentLength;\n }\n\n public static long findContentLengthFromContentRange(FileDownloadConnection connection) {\n final String contentRange = getContentRangeHeader(connection);\n long contentLength = parseContentLengthFromContentRange(contentRange);\n if (contentLength < 0) contentLength = TOTAL_VALUE_IN_CHUNKED_RESOURCE;\n return contentLength;\n }\n\n public static long parseContentLengthFromContentRange(String contentRange) {\n if (contentRange == null || contentRange.length() == 0) return -1;\n final String pattern = \"bytes (\\\\d+)-(\\\\d+)/\\\\d+\";\n try {\n final Pattern r = Pattern.compile(pattern);\n final Matcher m = r.matcher(contentRange);\n if (m.find()) {\n final long rangeStart = Long.parseLong(m.group(1));\n final long rangeEnd = Long.parseLong(m.group(2));\n return rangeEnd - rangeStart + 1;\n }\n } catch (Exception e) {\n FileDownloadLog.e(FileDownloadUtils.class, e, \"parse content length\"\n + \" from content range error\");\n }\n return -1;\n }\n\n public static String findFilename(FileDownloadConnection connection, String url)\n throws FileDownloadSecurityException {\n String filename = FileDownloadUtils.parseContentDisposition(connection.\n getResponseHeaderField(\"Content-Disposition\"));\n\n if (TextUtils.isEmpty(filename)) {\n filename = findFileNameFromUrl(url);\n }\n\n if (TextUtils.isEmpty(filename)) {\n filename = FileDownloadUtils.generateFileName(url);\n } else if (filename.contains(\"../\")) {\n throw new FileDownloadSecurityException(FileDownloadUtils.formatString(\n \"The filename [%s] from the response is not allowable, because it contains \"\n + \"'../', which can raise the directory traversal vulnerability\",\n filename));\n }\n\n return filename;\n }\n\n public static FileDownloadOutputStream createOutputStream(final String path)\n throws IOException {\n\n if (TextUtils.isEmpty(path)) {\n throw new RuntimeException(\"found invalid internal destination path, empty\");\n }\n\n //noinspection ConstantConditions\n if (!FileDownloadUtils.isFilenameValid(path)) {\n throw new RuntimeException(\n FileDownloadUtils.formatString(\"found invalid internal destination filename\"\n + \" %s\", path));\n }\n\n File file = new File(path);\n\n if (file.exists() && file.isDirectory()) {\n throw new RuntimeException(\n FileDownloadUtils.formatString(\"found invalid internal destination path[%s],\"\n + \" & path is directory[%B]\", path, file.isDirectory()));\n }\n if (!file.exists()) {\n if (!file.createNewFile()) {\n throw new IOException(\n FileDownloadUtils.formatString(\"create new file error %s\",\n file.getAbsolutePath()));\n }\n }\n\n return CustomComponentHolder.getImpl().createOutputStream(file);\n }\n\n public static boolean isBreakpointAvailable(final int id, final FileDownloadModel model) {\n return isBreakpointAvailable(id, model, null);\n }\n\n /**\n * @return can resume by break point\n */\n public static boolean isBreakpointAvailable(final int id, final FileDownloadModel model,\n final Boolean outputStreamSupportSeek) {\n if (model == null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class, \"can't continue %d model == null\", id);\n }\n return false;\n }\n\n if (model.getTempFilePath() == null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog\n .d(FileDownloadUtils.class, \"can't continue %d temp path == null\", id);\n }\n return false;\n }\n\n return isBreakpointAvailable(id, model, model.getTempFilePath(), outputStreamSupportSeek);\n }\n\n public static boolean isBreakpointAvailable(final int id, final FileDownloadModel model,\n final String path,\n final Boolean outputStreamSupportSeek) {\n boolean result = false;\n\n do {\n if (path == null) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class, \"can't continue %d path = null\", id);\n }\n break;\n }\n\n File file = new File(path);\n final boolean isExists = file.exists();\n final boolean isDirectory = file.isDirectory();\n\n if (!isExists || isDirectory) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class,\n \"can't continue %d file not suit, exists[%B], directory[%B]\",\n id, isExists, isDirectory);\n }\n break;\n }\n\n final long fileLength = file.length();\n final long currentOffset = model.getSoFar();\n\n if (model.getConnectionCount() <= 1 && currentOffset == 0) {\n // the sofar is stored on connection table\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class,\n \"can't continue %d the downloaded-record is zero.\",\n id);\n }\n break;\n }\n\n final long totalLength = model.getTotal();\n if (fileLength < currentOffset\n || (totalLength != TOTAL_VALUE_IN_CHUNKED_RESOURCE // not chunk transfer\n && (fileLength > totalLength || currentOffset >= totalLength))\n ) {\n // dirty data.\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class, \"can't continue %d dirty data\"\n + \" fileLength[%d] sofar[%d] total[%d]\",\n id, fileLength, currentOffset, totalLength);\n }\n break;\n }\n\n if (outputStreamSupportSeek != null && !outputStreamSupportSeek\n && totalLength == fileLength) {\n if (FileDownloadLog.NEED_LOG) {\n FileDownloadLog.d(FileDownloadUtils.class, \"can't continue %d, because of the \"\n + \"output stream doesn't support seek, but the task has \"\n + \"already pre-allocated, so we only can download it from the\"\n + \" very beginning.\",\n id);\n }\n break;\n }\n\n result = true;\n } while (false);\n\n\n return result;\n }\n\n public static void deleteTaskFiles(String targetFilepath, String tempFilePath) {\n deleteTempFile(tempFilePath);\n deleteTargetFile(targetFilepath);\n }\n\n public static void deleteTempFile(String tempFilePath) {\n if (tempFilePath != null) {\n final File tempFile = new File(tempFilePath);\n if (tempFile.exists()) {\n //noinspection ResultOfMethodCallIgnored\n tempFile.delete();\n }\n }\n }\n\n public static void deleteTargetFile(String targetFilePath) {\n if (targetFilePath != null) {\n final File targetFile = new File(targetFilePath);\n if (targetFile.exists()) {\n //noinspection ResultOfMethodCallIgnored\n targetFile.delete();\n }\n }\n }\n\n public static boolean isNeedSync(long bytesDelta, long timestampDelta) {\n return bytesDelta > FileDownloadUtils.getMinProgressStep()\n && timestampDelta > FileDownloadUtils.getMinProgressTime();\n }\n\n public static String defaultUserAgent() {\n return formatString(\"FileDownloader/%s\", BuildConfig.VERSION_NAME);\n }\n\n private static boolean isAppOnForeground(Context context) {\n ActivityManager activityManager = (ActivityManager) context.getApplicationContext()\n .getSystemService(Context.ACTIVITY_SERVICE);\n if (activityManager == null) return false;\n\n List<ActivityManager.RunningAppProcessInfo> appProcesses =\n activityManager.getRunningAppProcesses();\n if (appProcesses == null) return false;\n\n PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);\n if (pm == null) return false;\n if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {\n if (!pm.isInteractive()) return false;\n } else {\n if (!pm.isScreenOn()) return false;\n }\n\n String packageName = context.getApplicationContext().getPackageName();\n for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {\n // The name of the process that this object is associated with.\n if (appProcess.processName.equals(packageName) && appProcess.importance\n == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {\n return true;\n }\n\n }\n return false;\n }\n\n public static boolean needMakeServiceForeground(Context context) {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !isAppOnForeground(context);\n }\n\n static String findFileNameFromUrl(String url) {\n if (url == null || url.isEmpty()) {\n return null;\n }\n try {\n final URL parseUrl = new URL(url);\n final String path = parseUrl.getPath();\n String fileName = path.substring(path.lastIndexOf('/') + 1);\n if (fileName.isEmpty()) return null;\n return fileName;\n } catch (MalformedURLException ignore) {\n }\n return null;\n }\n}" ]
import com.liulishuo.filedownloader.util.FileDownloadProperties; import com.liulishuo.filedownloader.util.FileDownloadUtils; import java.io.File; import java.util.List; import android.app.Application; import android.app.Notification; import android.content.ComponentName; import android.content.Context; import android.content.ServiceConnection; import android.os.IBinder; import com.liulishuo.filedownloader.download.CustomComponentHolder; import com.liulishuo.filedownloader.event.DownloadServiceConnectChangedEvent; import com.liulishuo.filedownloader.model.FileDownloadStatus; import com.liulishuo.filedownloader.model.FileDownloadTaskAtom; import com.liulishuo.filedownloader.services.DownloadMgrInitialParams; import com.liulishuo.filedownloader.util.FileDownloadHelper; import com.liulishuo.filedownloader.util.FileDownloadLog;
/* * Copyright (c) 2015 LingoChamp 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.liulishuo.filedownloader; /** * The basic entrance for FileDownloader. * * @see com.liulishuo.filedownloader.services.FileDownloadService The service for FileDownloader. * @see FileDownloadProperties */ @SuppressWarnings("WeakerAccess") public class FileDownloader { /** * You can invoke this method anytime before you using the FileDownloader. * <p> * If you want to register your own customize components please using * {@link #setupOnApplicationOnCreate(Application)} on the {@link Application#onCreate()} * instead. * * @param context the context of Application or Activity etc.. */ public static void setup(Context context) { FileDownloadHelper.holdContext(context.getApplicationContext()); } /** * Using this method to setup the FileDownloader only you want to register your own customize * components for Filedownloader, otherwise just using {@link #setup(Context)} instead. * <p/> * Please invoke this method on the {@link Application#onCreate()} because of the customize * components must be assigned before FileDownloader is running. * <p/> * Such as: * <p/> * class MyApplication extends Application { * ... * public void onCreate() { * ... * FileDownloader.setupOnApplicationOnCreate(this) * .idGenerator(new MyIdGenerator()) * .database(new MyDatabase()) * ... * .commit(); * ... * } * ... * } * @param application the application. * @return the customize components maker. */ public static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate( Application application) { final Context context = application.getApplicationContext(); FileDownloadHelper.holdContext(context); DownloadMgrInitialParams.InitCustomMaker customMaker = new DownloadMgrInitialParams.InitCustomMaker(); CustomComponentHolder.getImpl().setInitCustomMaker(customMaker); return customMaker; } /** * @deprecated please use {@link #setup(Context)} instead. */ public static void init(final Context context) { if (context == null) { throw new IllegalArgumentException("the provided context must not be null!"); } setup(context); } /** * @deprecated please using {@link #setupOnApplicationOnCreate(Application)} instead. */ public static void init(final Context context, final DownloadMgrInitialParams.InitCustomMaker maker) { if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(FileDownloader.class, "init Downloader with params: %s %s", context, maker); } if (context == null) { throw new IllegalArgumentException("the provided context must not be null!"); } FileDownloadHelper.holdContext(context.getApplicationContext()); CustomComponentHolder.getImpl().setInitCustomMaker(maker); } private static final class HolderClass { private static final FileDownloader INSTANCE = new FileDownloader(); } public static FileDownloader getImpl() { return HolderClass.INSTANCE; } /** * For avoiding missing screen frames. * <p/> * This mechanism is used for avoid methods in {@link FileDownloadListener} is invoked too * frequent in result the system missing screen frames in the main thread. * <p> * We wrap the message package which size is {@link FileDownloadMessageStation#SUB_PACKAGE_SIZE} * and post the package to the main thread with the interval: * {@link FileDownloadMessageStation#INTERVAL} milliseconds. * <p/> * The default interval is 10ms, if {@code intervalMillisecond} equal to or less than 0, each * callback in {@link FileDownloadListener} will be posted to the main thread immediately. * * @param intervalMillisecond The time interval between posting two message packages. * @see #enableAvoidDropFrame() * @see #disableAvoidDropFrame() * @see #setGlobalHandleSubPackageSize(int) */ public static void setGlobalPost2UIInterval(final int intervalMillisecond) { FileDownloadMessageStation.INTERVAL = intervalMillisecond; } /** * For avoiding missing screen frames. * <p/> * This mechanism is used for avoid methods in {@link FileDownloadListener} is invoked too * frequent in result the system missing screen frames in the main thread. * <p> * We wrap the message package which size is {@link FileDownloadMessageStation#SUB_PACKAGE_SIZE} * and post the package to the main thread with the interval: * {@link FileDownloadMessageStation#INTERVAL} milliseconds. * <p> * The default count of message for a message package is 5. * * @param packageSize The count of message for a message package. * @see #setGlobalPost2UIInterval(int) */ public static void setGlobalHandleSubPackageSize(final int packageSize) { if (packageSize <= 0) { throw new IllegalArgumentException("sub package size must more than 0"); } FileDownloadMessageStation.SUB_PACKAGE_SIZE = packageSize; } /** * Avoid missing screen frames, this leads to all callbacks in {@link FileDownloadListener} do * not be invoked at once when it has already achieved to ensure callbacks don't be too frequent * * @see #isEnabledAvoidDropFrame() * @see #setGlobalPost2UIInterval(int) */ public static void enableAvoidDropFrame() { setGlobalPost2UIInterval(FileDownloadMessageStation.DEFAULT_INTERVAL); } /** * Disable avoiding missing screen frames, let all callbacks in {@link FileDownloadListener} * can be invoked at once when it achieve. * * @see #isEnabledAvoidDropFrame() * @see #setGlobalPost2UIInterval(int) */ public static void disableAvoidDropFrame() { setGlobalPost2UIInterval(-1); } /** * @return {@code true} if enabled the function of avoiding missing screen frames. * @see #enableAvoidDropFrame() * @see #disableAvoidDropFrame() * @see #setGlobalPost2UIInterval(int) */ public static boolean isEnabledAvoidDropFrame() { return FileDownloadMessageStation.isIntervalValid(); } /** * Create a download task. */ public BaseDownloadTask create(final String url) { return new DownloadTask(url); } /** * Start the download queue by the same listener. * * @param listener Used to assemble tasks which is bound by the same {@code listener} * @param isSerial Whether start tasks one by one rather than parallel. * @return {@code true} if start tasks successfully. */ public boolean start(final FileDownloadListener listener, final boolean isSerial) { if (listener == null) { FileDownloadLog.w(this, "Tasks with the listener can't start, because the listener " + "provided is null: [null, %B]", isSerial); return false; } return isSerial ? getQueuesHandler().startQueueSerial(listener) : getQueuesHandler().startQueueParallel(listener); } /** * Pause the download queue by the same {@code listener}. * * @param listener the listener. * @see #pause(int) */ public void pause(final FileDownloadListener listener) { FileDownloadTaskLauncher.getImpl().expire(listener); final List<BaseDownloadTask.IRunningTask> taskList = FileDownloadList.getImpl().copy(listener); for (BaseDownloadTask.IRunningTask task : taskList) { task.getOrigin().pause(); } } /** * Pause all tasks running in FileDownloader. */ public void pauseAll() { FileDownloadTaskLauncher.getImpl().expireAll(); final BaseDownloadTask.IRunningTask[] downloadList = FileDownloadList.getImpl().copy(); for (BaseDownloadTask.IRunningTask task : downloadList) { task.getOrigin().pause(); } // double check, for case: File Download progress alive but ui progress has died and relived // so FileDownloadList not always contain all running task exactly. if (FileDownloadServiceProxy.getImpl().isConnected()) { FileDownloadServiceProxy.getImpl().pauseAllTasks(); } else { PauseAllMarker.createMarker(); } } /** * Pause downloading tasks with the {@code id}. * * @param id the {@code id} . * @return The size of tasks has been paused. * @see #pause(FileDownloadListener) */ public int pause(final int id) { List<BaseDownloadTask.IRunningTask> taskList = FileDownloadList.getImpl() .getDownloadingList(id); if (null == taskList || taskList.isEmpty()) { FileDownloadLog.w(this, "request pause but not exist %d", id); return 0; } for (BaseDownloadTask.IRunningTask task : taskList) { task.getOrigin().pause(); } return taskList.size(); } /** * Clear the data with the provided {@code id}. * Normally used to deleting the data in filedownloader database, when it is paused or in * downloading status. If you want to re-download it clearly. * <p/> * <strong>Note:</strong> YOU NO NEED to clear the data when it is already completed downloading * because the data would be deleted when it completed downloading automatically by * FileDownloader. * <p> * If there are tasks with the {@code id} in downloading, will be paused first; * If delete the data with the {@code id} in the filedownloader database successfully, will try * to delete its intermediate downloading file and downloaded file. * * @param id the download {@code id}. * @param targetFilePath the target path. * @return {@code true} if the data with the {@code id} in filedownloader database was deleted, * and tasks with the {@code id} was paused; {@code false} otherwise. */ public boolean clear(final int id, final String targetFilePath) { pause(id); if (FileDownloadServiceProxy.getImpl().clearTaskData(id)) { // delete the task data in the filedownloader database successfully or no data with the // id in filedownloader database.
final File intermediateFile = new File(FileDownloadUtils.getTempPath(targetFilePath));
8
Azure/azure-storage-android
microsoft-azure-storage/src/com/microsoft/azure/storage/blob/CloudBlobContainer.java
[ "public final class Constants {\n /**\n * Defines constants for ServiceProperties requests.\n */\n public static class AnalyticsConstants {\n\n /**\n * The XML element for the CORS Rule AllowedHeaders\n */\n public static final String ALLOWED_HEADERS_ELEMENT = \"AllowedHeaders\";\n\n /**\n * The XML element for the CORS Rule AllowedMethods\n */\n public static final String ALLOWED_METHODS_ELEMENT = \"AllowedMethods\";\n\n /**\n * The XML element for the CORS Rule AllowedOrigins\n */\n public static final String ALLOWED_ORIGINS_ELEMENT = \"AllowedOrigins\";\n\n /**\n * The XML element for the CORS\n */\n public static final String CORS_ELEMENT = \"Cors\";\n\n /**\n * The XML element for the CORS Rules\n */\n public static final String CORS_RULE_ELEMENT = \"CorsRule\";\n\n /**\n * The XML element for the RetentionPolicy Days.\n */\n public static final String DAYS_ELEMENT = \"Days\";\n\n /**\n * The XML element for the Default Service Version.\n */\n public static final String DEFAULT_SERVICE_VERSION = \"DefaultServiceVersion\";\n\n /**\n * The XML element for the Logging Delete type.\n */\n public static final String DELETE_ELEMENT = \"Delete\";\n\n /**\n * The XML element for the RetentionPolicy Enabled.\n */\n public static final String ENABLED_ELEMENT = \"Enabled\";\n\n /**\n * The XML element for the CORS Rule ExposedHeaders\n */\n public static final String EXPOSED_HEADERS_ELEMENT = \"ExposedHeaders\";\n\n /**\n * The XML element for the Hour Metrics\n */\n public static final String HOUR_METRICS_ELEMENT = \"HourMetrics\";\n\n /**\n * The XML element for the Metrics IncludeAPIs.\n */\n public static final String INCLUDE_APIS_ELEMENT = \"IncludeAPIs\";\n\n /**\n * Constant for the logs container.\n */\n public static final String LOGS_CONTAINER = \"$logs\";\n\n /**\n * The XML element for the Logging\n */\n public static final String LOGGING_ELEMENT = \"Logging\";\n\n /**\n * The XML element for the CORS Rule MaxAgeInSeconds\n */\n public static final String MAX_AGE_IN_SECONDS_ELEMENT = \"MaxAgeInSeconds\";\n\n /**\n * Constant for the blob capacity metrics table.\n */\n public static final String METRICS_CAPACITY_BLOB = \"$MetricsCapacityBlob\";\n\n /**\n * Constant for the blob service primary location hourly metrics table.\n */\n public static final String METRICS_HOUR_PRIMARY_TRANSACTIONS_BLOB = \"$MetricsHourPrimaryTransactionsBlob\";\n\n /**\n * Constant for the file service primary location hourly metrics table.\n */\n public static final String METRICS_HOUR_PRIMARY_TRANSACTIONS_FILE = \"$MetricsHourPrimaryTransactionsFile\";\n\n /**\n * Constant for the table service primary location hourly metrics table.\n */\n public static final String METRICS_HOUR_PRIMARY_TRANSACTIONS_TABLE = \"$MetricsHourPrimaryTransactionsTable\";\n\n /**\n * Constant for the queue service primary location hourly metrics table.\n */\n public static final String METRICS_HOUR_PRIMARY_TRANSACTIONS_QUEUE = \"$MetricsHourPrimaryTransactionsQueue\";\n\n /**\n * Constant for the blob service primary location minute metrics table.\n */\n public static final String METRICS_MINUTE_PRIMARY_TRANSACTIONS_BLOB = \"$MetricsMinutePrimaryTransactionsBlob\";\n\n /**\n * Constant for the file service primary location minute metrics table.\n */\n public static final String METRICS_MINUTE_PRIMARY_TRANSACTIONS_FILE = \"$MetricsMinutePrimaryTransactionsFile\";\n\n /**\n * Constant for the table service primary location minute metrics table.\n */\n public static final String METRICS_MINUTE_PRIMARY_TRANSACTIONS_TABLE = \"$MetricsMinutePrimaryTransactionsTable\";\n\n /**\n * Constant for the queue service primary location minute metrics table.\n */\n public static final String METRICS_MINUTE_PRIMARY_TRANSACTIONS_QUEUE = \"$MetricsMinutePrimaryTransactionsQueue\";\n\n /**\n * Constant for the blob service secondary location hourly metrics table.\n */\n public static final String METRICS_HOUR_SECONDARY_TRANSACTIONS_BLOB = \"$MetricsHourSecondaryTransactionsBlob\";\n\n /**\n * Constant for the file service secondary location hourly metrics table.\n */\n public static final String METRICS_HOUR_SECONDARY_TRANSACTIONS_FILE = \"$MetricsHourSecondaryTransactionsFile\";\n\n /**\n * Constant for the table service secondary location hourly metrics table.\n */\n public static final String METRICS_HOUR_SECONDARY_TRANSACTIONS_TABLE = \"$MetricsHourSecondaryTransactionsTable\";\n\n /**\n * Constant for the queue service secondary location hourly metrics table.\n */\n public static final String METRICS_HOUR_SECONDARY_TRANSACTIONS_QUEUE = \"$MetricsHourSecondaryTransactionsQueue\";\n\n /**\n * Constant for the blob service secondary location minute metrics table.\n */\n public static final String METRICS_MINUTE_SECONDARY_TRANSACTIONS_BLOB = \"$MetricsMinuteSecondaryTransactionsBlob\";\n\n /**\n * Constant for the file service secondary location minute metrics table.\n */\n public static final String METRICS_MINUTE_SECONDARY_TRANSACTIONS_FILE = \"$MetricsMinuteSecondaryTransactionsFile\";\n\n /**\n * Constant for the table service secondary location minute metrics table.\n */\n public static final String METRICS_MINUTE_SECONDARY_TRANSACTIONS_TABLE = \"$MetricsMinuteSecondaryTransactionsTable\";\n\n /**\n * Constant for the queue service secondary location minute metrics table.\n */\n public static final String METRICS_MINUTE_SECONDARY_TRANSACTIONS_QUEUE = \"$MetricsMinuteSecondaryTransactionsQueue\";\n\n /**\n * The XML element for the Minute Metrics\n */\n public static final String MINUTE_METRICS_ELEMENT = \"MinuteMetrics\";\n\n /**\n * The XML element for the Logging Read type.\n */\n public static final String READ_ELEMENT = \"Read\";\n\n /**\n * The XML element for the RetentionPolicy.\n */\n public static final String RETENTION_POLICY_ELEMENT = \"RetentionPolicy\";\n\n /**\n * The XML element for the StorageServiceProperties\n */\n public static final String STORAGE_SERVICE_PROPERTIES_ELEMENT = \"StorageServiceProperties\";\n\n /**\n * The XML element for the StorageServiceStats\n */\n public static final String STORAGE_SERVICE_STATS = \"StorageServiceStats\";\n\n /**\n * The XML element for the Version\n */\n public static final String VERSION_ELEMENT = \"Version\";\n\n /**\n * The XML element for the Logging Write type.\n */\n public static final String WRITE_ELEMENT = \"Write\";\n\n }\n\n /**\n * Defines constants for use with HTTP headers.\n */\n public static class HeaderConstants {\n /**\n * The Accept header.\n */\n public static final String ACCEPT = \"Accept\";\n\n /**\n * The Accept-Charset header.\n */\n public static final String ACCEPT_CHARSET = \"Accept-Charset\";\n\n /**\n * The Accept-Encoding header.\n */\n public static final String ACCEPT_ENCODING = \"Accept-Encoding\";\n\n /**\n * The Authorization header.\n */\n public static final String AUTHORIZATION = \"Authorization\";\n\n /**\n * The format string for specifying ranges with only begin offset.\n */\n public static final String BEGIN_RANGE_HEADER_FORMAT = \"bytes=%d-\";\n \n /**\n * The format string for specifying the blob append offset.\n */\n public static final String BLOB_APPEND_OFFSET = PREFIX_FOR_STORAGE_HEADER + \"blob-append-offset\";\n \n /**\n * The header that specifies committed block count.\n */\n public static final String BLOB_COMMITTED_BLOCK_COUNT = PREFIX_FOR_STORAGE_HEADER + \"blob-committed-block-count\";\n \n /**\n * The header that specifies blob sequence number.\n */\n public static final String BLOB_SEQUENCE_NUMBER = PREFIX_FOR_STORAGE_HEADER + \"blob-sequence-number\";\n \n /**\n * The CacheControl header.\n */\n public static final String CACHE_CONTROL = \"Cache-Control\";\n\n /**\n * The header that specifies blob caching control.\n */\n public static final String CACHE_CONTROL_HEADER = PREFIX_FOR_STORAGE_HEADER + \"blob-cache-control\";\n\n /**\n * The header that indicates the client request ID.\n */\n public static final String CLIENT_REQUEST_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + \"client-request-id\";\n\n /**\n * The ContentDisposition header.\n */\n public static final String CONTENT_DISPOSITION = \"Content-Disposition\";\n\n /**\n * The ContentEncoding header.\n */\n public static final String CONTENT_ENCODING = \"Content-Encoding\";\n\n /**\n * The ContentLangauge header.\n */\n public static final String CONTENT_LANGUAGE = \"Content-Language\";\n\n /**\n * The ContentLength header.\n */\n public static final String CONTENT_LENGTH = \"Content-Length\";\n\n /**\n * The ContentMD5 header.\n */\n public static final String CONTENT_MD5 = \"Content-MD5\";\n\n /**\n * The ContentRange header.\n */\n public static final String CONTENT_RANGE = \"Content-Range\";\n\n /**\n * The ContentType header.\n */\n public static final String CONTENT_TYPE = \"Content-Type\";\n\n /**\n * The value of the copy action header that signifies an abort operation.\n */\n public static final String COPY_ACTION_ABORT = \"abort\";\n\n /**\n * Header that specifies the copy action.\n */\n public static final String COPY_ACTION_HEADER = PREFIX_FOR_STORAGE_HEADER + \"copy-action\";\n\n /**\n * The header that specifies copy completion time.\n */\n public static final String COPY_COMPLETION_TIME = PREFIX_FOR_STORAGE_HEADER + \"copy-completion-time\";\n\n /**\n * The header that specifies copy id.\n */\n public static final String COPY_ID = PREFIX_FOR_STORAGE_HEADER + \"copy-id\";\n\n /**\n * The header that specifies copy progress.\n */\n public static final String COPY_PROGRESS = PREFIX_FOR_STORAGE_HEADER + \"copy-progress\";\n\n /**\n * The header that specifies copy source.\n */\n public static final String COPY_SOURCE = PREFIX_FOR_STORAGE_HEADER + \"copy-source\";\n\n /**\n * The header for copy source.\n */\n public static final String COPY_SOURCE_HEADER = PREFIX_FOR_STORAGE_HEADER + \"copy-source\";\n\n /**\n * The header that specifies copy status.\n */\n public static final String COPY_STATUS = PREFIX_FOR_STORAGE_HEADER + \"copy-status\";\n\n /**\n * The header that specifies copy status description.\n */\n public static final String COPY_STATUS_DESCRIPTION = PREFIX_FOR_STORAGE_HEADER + \"copy-status-description\";\n\n /**\n * The header that specifies copy type.\n */\n public static final String INCREMENTAL_COPY = PREFIX_FOR_STORAGE_HEADER + \"incremental-copy\";\n\n /**\n * The header that specifies the snapshot ID of the last successful incremental snapshot.\n */\n public static final String COPY_DESTINATION_SNAPSHOT_ID = PREFIX_FOR_STORAGE_HEADER + \"copy-destination-snapshot\";\n\n /**\n * The header that specifies the date.\n */\n public static final String DATE = PREFIX_FOR_STORAGE_HEADER + \"date\";\n\n /**\n * The header to delete snapshots.\n */\n public static final String DELETE_SNAPSHOT_HEADER = PREFIX_FOR_STORAGE_HEADER + \"delete-snapshots\";\n\n /**\n * The ETag header.\n */\n public static final String ETAG = \"ETag\";\n\n /**\n * An unused HTTP code used internally to indicate a non-http related failure when constructing\n * {@link StorageException} objects\n */\n public static final int HTTP_UNUSED_306 = 306;\n\n /**\n * The blob append position equal header.\n */\n public static final String IF_APPEND_POSITION_EQUAL_HEADER = PREFIX_FOR_STORAGE_HEADER + \"blob-condition-appendpos\";\n \n /**\n * The IfMatch header.\n */\n public static final String IF_MATCH = \"If-Match\";\n \n /**\n * The blob maxsize condition header.\n */\n public static final String IF_MAX_SIZE_LESS_THAN_OR_EQUAL = PREFIX_FOR_STORAGE_HEADER + \"blob-condition-maxsize\";\n\n /**\n * The IfModifiedSince header.\n */\n public static final String IF_MODIFIED_SINCE = \"If-Modified-Since\";\n\n /**\n * The IfNoneMatch header.\n */\n public static final String IF_NONE_MATCH = \"If-None-Match\";\n\n /**\n * The IfUnmodifiedSince header.\n */\n public static final String IF_UNMODIFIED_SINCE = \"If-Unmodified-Since\";\n \n /**\n * The blob sequence number less than or equal condition header.\n */\n public static final String IF_SEQUENCE_NUMBER_LESS_THAN_OR_EQUAL = PREFIX_FOR_STORAGE_HEADER + \"if-sequence-number-le\";\n \n /**\n * The blob sequence number less than condition header.\n */\n public static final String IF_SEQUENCE_NUMBER_LESS_THAN = PREFIX_FOR_STORAGE_HEADER + \"if-sequence-number-lt\";\n \n /**\n * The blob sequence number equal condition header.\n */\n public static final String IF_SEQUENCE_NUMBER_EQUAL = PREFIX_FOR_STORAGE_HEADER + \"if-sequence-number-eq\";\n\n /**\n * Specifies snapshots are to be included.\n */\n public static final String INCLUDE_SNAPSHOTS_VALUE = \"include\";\n \n /**\n * The header that specifies the lease action to perform\n */\n public static final String LEASE_ACTION_HEADER = PREFIX_FOR_STORAGE_HEADER + \"lease-action\";\n\n /**\n * The header that specifies the break period of a lease\n */\n public static final String LEASE_BREAK_PERIOD_HEADER = PREFIX_FOR_STORAGE_HEADER + \"lease-break-period\";\n\n /**\n * The header that specifies lease duration.\n */\n public static final String LEASE_DURATION = PREFIX_FOR_STORAGE_HEADER + \"lease-duration\";\n\n /**\n * The header that specifies lease ID.\n */\n public static final String LEASE_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + \"lease-id\";\n\n /**\n * The header that specifies lease state.\n */\n public static final String LEASE_STATE = PREFIX_FOR_STORAGE_HEADER + \"lease-state\";\n\n /**\n * The header that specifies lease status.\n */\n public static final String LEASE_STATUS = PREFIX_FOR_STORAGE_HEADER + \"lease-status\";\n\n /**\n * The header that specifies the remaining lease time\n */\n public static final String LEASE_TIME_HEADER = PREFIX_FOR_STORAGE_HEADER + \"lease-time\";\n\n /**\n * The header that specifies the pop receipt.\n */\n public static final String POP_RECEIPT_HEADER = PREFIX_FOR_STORAGE_HEADER + \"popreceipt\";\n\n /**\n * The header prefix for metadata.\n */\n public static final String PREFIX_FOR_STORAGE_METADATA = \"x-ms-meta-\";\n\n /**\n * The header prefix for properties.\n */\n public static final String PREFIX_FOR_STORAGE_PROPERTIES = \"x-ms-prop-\";\n\n /**\n * The header that specifies the proposed lease ID for a leasing operation\n */\n public static final String PROPOSED_LEASE_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + \"proposed-lease-id\";\n\n /**\n * The Range header.\n */\n public static final String RANGE = \"Range\";\n\n /**\n * The header that specifies if the request will populate the ContentMD5 header for range gets.\n */\n public static final String RANGE_GET_CONTENT_MD5 = PREFIX_FOR_STORAGE_HEADER + \"range-get-content-md5\";\n\n /**\n * The format string for specifying ranges.\n */\n public static final String RANGE_HEADER_FORMAT = \"bytes=%d-%d\";\n\n /**\n * The header that indicates the request ID.\n */\n public static final String REQUEST_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + \"request-id\";\n\n /**\n * The header field value received that indicates which server was accessed\n */\n public static final String SERVER = \"Server\";\n\n /**\n * The header that specifies whether a resource is fully encrypted server-side\n */\n public static final String SERVER_ENCRYPTED = PREFIX_FOR_STORAGE_HEADER + \"server-encrypted\";\n\n /**\n * The header that acknowledges data used for a write operation is encrypted server-side\n */\n public static final String SERVER_REQUEST_ENCRYPTED = PREFIX_FOR_STORAGE_HEADER + \"request-server-encrypted\";\n\n /**\n * The header that specifies the snapshot ID.\n */\n public static final String SNAPSHOT_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + \"snapshot\";\n\n /**\n * The header for the If-Match condition.\n */\n public static final String SOURCE_IF_MATCH_HEADER = PREFIX_FOR_STORAGE_HEADER + \"source-if-match\";\n\n /**\n * The header for the If-Modified-Since condition.\n */\n public static final String SOURCE_IF_MODIFIED_SINCE_HEADER = PREFIX_FOR_STORAGE_HEADER\n + \"source-if-modified-since\";\n\n /**\n * The header for the If-None-Match condition.\n */\n public static final String SOURCE_IF_NONE_MATCH_HEADER = PREFIX_FOR_STORAGE_HEADER + \"source-if-none-match\";\n\n /**\n * The header for the If-Unmodified-Since condition.\n */\n public static final String SOURCE_IF_UNMODIFIED_SINCE_HEADER = PREFIX_FOR_STORAGE_HEADER\n + \"source-if-unmodified-since\";\n\n /**\n * The header for the source lease id.\n */\n public static final String SOURCE_LEASE_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + \"source-lease-id\";\n\n /**\n * The header for data ranges.\n */\n public static final String STORAGE_RANGE_HEADER = PREFIX_FOR_STORAGE_HEADER + \"range\";\n\n /**\n * The header for storage version.\n */\n public static final String STORAGE_VERSION_HEADER = PREFIX_FOR_STORAGE_HEADER + \"version\";\n\n /**\n * The current storage version header value.\n */\n public static final String TARGET_STORAGE_VERSION = \"2017-04-17\";\n\n /**\n * The header that specifies the next visible time for a queue message.\n */\n public static final String TIME_NEXT_VISIBLE_HEADER = PREFIX_FOR_STORAGE_HEADER + \"time-next-visible\";\n\n /**\n * The UserAgent header.\n */\n public static final String USER_AGENT = \"User-Agent\";\n\n /**\n * Specifies the value to use for UserAgent header.\n */\n public static final String USER_AGENT_PREFIX = \"Azure-Storage\";\n\n /**\n * Specifies the value to use for UserAgent header.\n */\n public static final String USER_AGENT_VERSION = \"2.0.0\";\n\n /**\n * The default type for content-type and accept\n */\n public static final String XML_TYPE = \"application/xml\";\n }\n\n /**\n * Defines constants for use with query strings.\n */\n public static class QueryConstants {\n /**\n * The query component for the api version.\n */\n public static final String API_VERSION = \"api-version\";\n\n /**\n * Query component for SAS cache control.\n */\n public static final String CACHE_CONTROL = \"rscc\";\n\n /**\n * Query component for SAS content type.\n */\n public static final String CONTENT_TYPE = \"rsct\";\n\n /**\n * Query component for SAS content encoding.\n */\n public static final String CONTENT_ENCODING = \"rsce\";\n\n /**\n * Query component for SAS content language.\n */\n public static final String CONTENT_LANGUAGE = \"rscl\";\n\n /**\n * Query component for SAS content disposition.\n */\n public static final String CONTENT_DISPOSITION = \"rscd\";\n\n /**\n * Query component for the operation (component) to access.\n */\n public static final String COMPONENT = \"comp\";\n\n /**\n * Query component for copy.\n */\n public static final String COPY = \"copy\";\n\n /**\n * Query component for the copy ID.\n */\n public static final String COPY_ID = \"copyid\";\n\n /**\n * The query component for the SAS end partition key.\n */\n public static final String END_PARTITION_KEY = \"epk\";\n\n /**\n * The query component for the SAS end row key.\n */\n public static final String END_ROW_KEY = \"erk\";\n\n /**\n * Query component value for list.\n */\n public static final String LIST = \"list\";\n\n /**\n * Query component value for properties.\n */\n public static final String PROPERTIES = \"properties\";\n\n /**\n * Query component for resource type.\n */\n public static final String RESOURCETYPE = \"restype\";\n\n /**\n * The query component for the SAS table name.\n */\n public static final String SAS_TABLE_NAME = \"tn\";\n\n /**\n * The query component for the SAS signature.\n */\n public static final String SIGNATURE = \"sig\";\n\n /**\n * The query component for the signed SAS expiry time.\n */\n public static final String SIGNED_EXPIRY = \"se\";\n\n /**\n * The query component for the signed SAS identifier.\n */\n public static final String SIGNED_IDENTIFIER = \"si\";\n\n /**\n * The query component for the signed SAS IP address.\n */\n public static final String SIGNED_IP = \"sip\";\n\n /**\n * The query component for the signing SAS key.\n */\n public static final String SIGNED_KEY = \"sk\";\n\n /**\n * The query component for the signed SAS permissions.\n */\n public static final String SIGNED_PERMISSIONS = \"sp\";\n\n /**\n * The query component for the signed SAS Internet protocols.\n */\n public static final String SIGNED_PROTOCOLS = \"spr\";\n\n /**\n * The query component for the signed SAS resource.\n */\n public static final String SIGNED_RESOURCE = \"sr\";\n\n /**\n * The query component for the signed SAS resource type.\n */\n public static final String SIGNED_RESOURCE_TYPE = \"srt\";\n\n /**\n * The query component for the signed SAS service.\n */\n public static final String SIGNED_SERVICE = \"ss\";\n\n /**\n * The query component for the signed SAS start time.\n */\n public static final String SIGNED_START = \"st\";\n\n /**\n * The query component for the signed SAS version.\n */\n public static final String SIGNED_VERSION = \"sv\";\n\n /**\n * The query component for snapshot time.\n */\n public static final String SNAPSHOT = \"snapshot\";\n\n /**\n * The query component for snapshot time.\n */\n public static final String SHARE_SNAPSHOT = \"sharesnapshot\";\n\n /**\n * The query component for the SAS start partition key.\n */\n public static final String START_PARTITION_KEY = \"spk\";\n\n /**\n * The query component for the SAS start row key.\n */\n public static final String START_ROW_KEY = \"srk\";\n\n /**\n * The query component for stats.\n */\n public static final String STATS = \"stats\";\n\n /**\n * The query component for delimiter.\n */\n public static final String DELIMITER = \"delimiter\";\n\n /**\n * The query component for include.\n */\n public static final String INCLUDE = \"include\";\n\n /**\n * The query component for marker.\n */\n public static final String MARKER = \"marker\";\n\n /**\n * The query component for max results.\n */\n public static final String MAX_RESULTS = \"maxresults\";\n\n /**\n * The query component for metadata.\n */\n public static final String METADATA = \"metadata\";\n\n /**\n * The query component for prefix.\n */\n public static final String PREFIX = \"prefix\";\n\n /**\n * The query component for acl.\n */\n public static final String ACL = \"acl\";\n }\n\n /**\n * The master Microsoft Azure Storage header prefix.\n */\n public static final String PREFIX_FOR_STORAGE_HEADER = \"x-ms-\";\n\n /**\n * Constant representing a kilobyte (Non-SI version).\n */\n public static final int KB = 1024;\n\n /**\n * Constant representing a megabyte (Non-SI version).\n */\n public static final int MB = 1024 * KB;\n\n /**\n * Constant representing a gigabyte (Non-SI version).\n */\n public static final int GB = 1024 * MB;\n\n /**\n * XML element for an access policy.\n */\n public static final String ACCESS_POLICY = \"AccessPolicy\";\n\n /**\n * XML element for access tier.\n */\n public static final String ACCESS_TIER = \"AccessTier\";\n\n /**\n * XML element for the archive status.\n */\n public static final String ARCHIVE_STATUS = \"ArchiveStatus\";\n\n /**\n * Buffer width used to copy data to output streams.\n */\n public static final int BUFFER_COPY_LENGTH = 8 * KB;\n\n /**\n * XML element for the copy completion time.\n */\n public static final String COPY_COMPLETION_TIME_ELEMENT = \"CopyCompletionTime\";\n\n /**\n * XML element for the copy id.\n */\n public static final String COPY_ID_ELEMENT = \"CopyId\";\n\n /**\n * XML element for the copy progress.\n */\n public static final String COPY_PROGRESS_ELEMENT = \"CopyProgress\";\n\n /**\n * XML element for the copy source .\n */\n public static final String COPY_SOURCE_ELEMENT = \"CopySource\";\n\n /**\n * XML element for the copy status description.\n */\n public static final String COPY_STATUS_DESCRIPTION_ELEMENT = \"CopyStatusDescription\";\n\n /**\n * XML element for the copy status.\n */\n public static final String COPY_STATUS_ELEMENT = \"CopyStatus\";\n\n /**\n * XML element for the copy type.\n */\n public static final String INCREMENTAL_COPY_ELEMENT = \"IncrementalCopy\";\n\n /**\n * XML element for the snapshot ID for the last successful incremental copy.\n */\n public static final String COPY_DESTINATION_SNAPSHOT_ID_ELEMENT = \"CopyDestinationSnapshot\";\n\n /**\n * Default read timeout. 5 min * 60 seconds * 1000 ms\n */\n public static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000;\n \n /**\n * XML element for delimiters.\n */\n public static final String DELIMITER_ELEMENT = \"Delimiter\";\n\n /**\n * Http GET method.\n */\n public static final String HTTP_GET = \"GET\";\n\n /**\n * Http PUT method.\n */\n public static final String HTTP_PUT = \"PUT\";\n\n /**\n * Http DELETE method.\n */\n public static final String HTTP_DELETE = \"DELETE\";\n\n /**\n * Http HEAD method.\n */\n public static final String HTTP_HEAD = \"HEAD\";\n\n /**\n * Http POST method.\n */\n public static final String HTTP_POST = \"POST\";\n\n /**\n * An empty <code>String</code> to use for comparison.\n */\n public static final String EMPTY_STRING = \"\";\n\n /**\n * XML element for page range end elements.\n */\n public static final String END_ELEMENT = \"End\";\n\n /**\n * XML element for error codes.\n */\n public static final String ERROR_CODE = \"Code\";\n\n /**\n * XML element for exception details.\n */\n public static final String ERROR_EXCEPTION = \"ExceptionDetails\";\n\n /**\n * XML element for exception messages.\n */\n public static final String ERROR_EXCEPTION_MESSAGE = \"ExceptionMessage\";\n\n /**\n * XML element for stack traces.\n */\n public static final String ERROR_EXCEPTION_STACK_TRACE = \"StackTrace\";\n\n /**\n * XML element for error messages.\n */\n public static final String ERROR_MESSAGE = \"Message\";\n\n /**\n * XML root element for errors.\n */\n public static final String ERROR_ROOT_ELEMENT = \"Error\";\n\n /**\n * XML element for the ETag.\n */\n public static final String ETAG_ELEMENT = \"Etag\";\n\n /**\n * XML element for the end time of an access policy.\n */\n public static final String EXPIRY = \"Expiry\";\n\n /**\n * Constant for False.\n */\n public static final String FALSE = \"false\";\n\n /**\n * Constant for bootstrap geo-replication status.\n */\n public static final String GEO_BOOTSTRAP_VALUE = \"bootstrap\";\n\n /**\n * Constant for live geo-replication status.\n */\n public static final String GEO_LIVE_VALUE = \"live\";\n\n /**\n * Constant for unavailable geo-replication status.\n */\n public static final String GEO_UNAVAILABLE_VALUE = \"unavailable\";\n\n /**\n * Specifies HTTP.\n */\n public static final String HTTP = \"http\";\n\n /**\n * Specifies HTTPS.\n */\n public static final String HTTPS = \"https\";\n\n /**\n * Specifies both HTTPS and HTTP.\n */\n public static final String HTTPS_HTTP = \"https,http\";\n\n /**\n * XML attribute for IDs.\n */\n public static final String ID = \"Id\";\n\n /**\n * XML element for an invalid metadata name.\n */\n public static final String INVALID_METADATA_NAME = \"x-ms-invalid-name\";\n\n /**\n * XML element for the last modified date.\n */\n public static final String LAST_MODIFIED_ELEMENT = \"Last-Modified\";\n\n /**\n * Lease break period max in seconds.\n */\n public static final int LEASE_BREAK_PERIOD_MAX = 60;\n\n /**\n * Lease break period min in seconds.\n */\n public static final int LEASE_BREAK_PERIOD_MIN = 0;\n\n /**\n * XML element for the lease duration.\n */\n public static final String LEASE_DURATION_ELEMENT = \"LeaseDuration\";\n\n /**\n * Lease duration max in seconds.\n */\n public static final int LEASE_DURATION_MAX = 60;\n\n /**\n * Lease duration min in seconds.\n */\n public static final int LEASE_DURATION_MIN = 15;\n \n /**\n * XML element for the lease state.\n */\n public static final String LEASE_STATE_ELEMENT = \"LeaseState\";\n\n /**\n * XML element for the lease status.\n */\n public static final String LEASE_STATUS_ELEMENT = \"LeaseStatus\";\n\n /**\n * Constant signaling the resource is locked.\n */\n public static final String LOCKED_VALUE = \"Locked\";\n\n /**\n * Tag that will be used for this application if logging is enabled.\n */\n public static final String LOG_TAG = \"WindowsAzureStorageSDK\";\n\n /**\n * The maximum size of a single block.\n */\n public static int MAX_BLOCK_SIZE = 4 * MB;\n\n /**\n * XML element for a marker.\n */\n public static final String MARKER_ELEMENT = \"Marker\";\n\n /**\n * The default write size, in bytes, used by {@link BlobOutputStream} or {@link FileOutputStream}.\n */\n public static final int DEFAULT_STREAM_WRITE_IN_BYTES = Constants.MAX_BLOCK_SIZE;\n\n /**\n * The default minimum read size, in bytes, for a {@link BlobInputStream} or {@link FileInputStream}.\n */\n public static final int DEFAULT_MINIMUM_READ_SIZE_IN_BYTES = Constants.MAX_BLOCK_SIZE;\n\n /**\n * The maximum size, in bytes, of a given stream mark operation.\n */\n // Note if BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES is updated then this needs to be as well.\n public static final int MAX_MARK_LENGTH = 64 * MB;\n\n /**\n * XML element for maximum results.\n */\n public static final String MAX_RESULTS_ELEMENT = \"MaxResults\";\n\n /**\n * Maximum number of shared access policy identifiers supported by server.\n */\n public static final int MAX_SHARED_ACCESS_POLICY_IDENTIFIERS = 5;\n\n /**\n * Number of default concurrent requests for parallel operation.\n */\n public static final int MAXIMUM_SEGMENTED_RESULTS = 5000;\n\n /**\n * XML element for the metadata.\n */\n public static final String METADATA_ELEMENT = \"Metadata\";\n\n /**\n * XML element for names.\n */\n public static final String NAME_ELEMENT = \"Name\";\n\n /**\n * XML element for the next marker.\n */\n public static final String NEXT_MARKER_ELEMENT = \"NextMarker\";\n\n /**\n * The size of a page, in bytes, in a page blob.\n */\n public static final int PAGE_SIZE = 512;\n\n /**\n * XML element for the permission of an access policy.\n */\n public static final String PERMISSION = \"Permission\";\n\n /**\n * XML element for a prefix.\n */\n public static final String PREFIX_ELEMENT = \"Prefix\";\n\n /**\n * XML element for properties.\n */\n public static final String PROPERTIES = \"Properties\";\n\n /**\n * XML element for public access\n */\n public static final String PUBLIC_ACCESS_ELEMENT = \"PublicAccess\";\n\n /**\n * XML element for the server encryption status.\n */\n public static final String SERVER_ENCRYPTION_STATUS_ELEMENT = \"ServerEncrypted\";\n \n /**\n * XML element for a signed identifier.\n */\n public static final String SIGNED_IDENTIFIER_ELEMENT = \"SignedIdentifier\";\n\n /**\n * XML element for signed identifiers.\n */\n public static final String SIGNED_IDENTIFIERS_ELEMENT = \"SignedIdentifiers\";\n\n /**\n * XML element for the start time of an access policy.\n */\n public static final String START = \"Start\";\n\n /**\n * Constant for True.\n */\n public static final String TRUE = \"true\";\n\n /**\n * Constant signaling the resource is unlocked.\n */\n public static final String UNLOCKED_VALUE = \"Unlocked\";\n\n /**\n * Constant signaling the resource lease duration, state or status is unspecified.\n */\n public static final String UNSPECIFIED_VALUE = \"Unspecified\";\n\n /**\n * XML element for the URL.\n */\n public static final String URL_ELEMENT = \"Url\";\n\n /**\n * The default type for content-type and accept\n */\n public static final String UTF8_CHARSET = \"UTF-8\";\n\n /**\n * Private Default Ctor\n */\n private Constants() {\n // No op\n }\n}", "public final class OperationContext {\n\n /**\n * The default log level, or null if disabled. The default can be overridden to turn on logging for an individual\n * operation context instance by using setLoggingEnabled.\n */\n private static Integer defaultLogLevel;\n\n /**\n * Indicates whether the client library should produce log entries by default. The default can be overridden to\n * enable logging for an individual operation context instance by using {@link #setLoggingEnabled}.\n */\n private static boolean enableLoggingByDefault = false;\n \n /**\n * Indicates whether the client library should use a proxy by default. The default can be overridden to\n * enable proxy for an individual operation context instance by using {@link #setProxy}.\n */\n private static Proxy proxyDefault;\n\n /**\n * Represents a proxy to be used when making a request.\n */\n private Proxy proxy;\n\n /**\n * Represents the operation latency, in milliseconds, from the client's perspective. This may include any potential\n * retries.\n */\n private long clientTimeInMs;\n\n /**\n * The UUID representing the client side trace ID.\n */\n private String clientRequestID;\n\n /**\n * The log level for a given operation context, null if disabled.\n */\n private Integer logLevel;\n\n /**\n * Represents request results, in the form of an <code>ArrayList</code> object that contains the\n * {@link RequestResult} objects, for each physical request that is made.\n */\n private final ArrayList<RequestResult> requestResults;\n\n /**\n * Represents additional headers on the request, for example, for proxy or logging information.\n */\n private HashMap<String, String> userHeaders;\n\n /**\n * Represents an event that is triggered before sending a\n * request.\n * \n * @see StorageEvent\n * @see StorageEventMultiCaster\n * @see SendingRequestEvent\n */\n private static StorageEventMultiCaster<SendingRequestEvent, StorageEvent<SendingRequestEvent>> globalSendingRequestEventHandler = new StorageEventMultiCaster<SendingRequestEvent, StorageEvent<SendingRequestEvent>>();\n\n /**\n * Represents an event that is triggered when a response is received from the storage service while processing a request\n *\n * @see StorageEvent\n * @see StorageEventMultiCaster\n * @see ResponseReceivedEvent\n */\n private static StorageEventMultiCaster<ResponseReceivedEvent, StorageEvent<ResponseReceivedEvent>> globalResponseReceivedEventHandler = new StorageEventMultiCaster<ResponseReceivedEvent, StorageEvent<ResponseReceivedEvent>>();\n\n /**\n * Represents an event that is triggered when a network error occurs before the HTTP response status and headers are received.\n *\n * @see StorageEvent\n * @see StorageEventMultiCaster\n * @see ErrorReceivingResponseEvent\n */\n private static StorageEventMultiCaster<ErrorReceivingResponseEvent, StorageEvent<ErrorReceivingResponseEvent>> globalErrorReceivingResponseEventHandler = new StorageEventMultiCaster<ErrorReceivingResponseEvent, StorageEvent<ErrorReceivingResponseEvent>>();\n\n /**\n * Represents an event that is triggered when a response received from the service is fully processed.\n * \n * @see StorageEvent\n * @see StorageEventMultiCaster\n * @see RequestCompletedEvent\n */\n private static StorageEventMultiCaster<RequestCompletedEvent, StorageEvent<RequestCompletedEvent>> globalRequestCompletedEventHandler = new StorageEventMultiCaster<RequestCompletedEvent, StorageEvent<RequestCompletedEvent>>();\n\n /**\n * Represents an event that is triggered when a request is retried.\n * \n * @see StorageEvent\n * @see StorageEventMultiCaster\n * @see RetryingEvent\n */\n private static StorageEventMultiCaster<RetryingEvent, StorageEvent<RetryingEvent>> globalRetryingEventHandler = new StorageEventMultiCaster<RetryingEvent, StorageEvent<RetryingEvent>>();\n\n /**\n * Represents an event that is triggered before sending a request.\n * \n * @see StorageEvent\n * @see StorageEventMultiCaster\n * @see SendingRequestEvent\n */\n private StorageEventMultiCaster<SendingRequestEvent, StorageEvent<SendingRequestEvent>> sendingRequestEventHandler = new StorageEventMultiCaster<SendingRequestEvent, StorageEvent<SendingRequestEvent>>();\n\n /**\n * Represents an event that is triggered when a response is received from the storage service while processing a\n * request.\n * \n * @see StorageEvent\n * @see StorageEventMultiCaster\n * @see ResponseReceivedEvent\n */\n private StorageEventMultiCaster<ResponseReceivedEvent, StorageEvent<ResponseReceivedEvent>> responseReceivedEventHandler = new StorageEventMultiCaster<ResponseReceivedEvent, StorageEvent<ResponseReceivedEvent>>();\n\n /**\n * Represents an event that is triggered when a network error occurs before the HTTP response status and headers are received.\n *\n * @see StorageEvent\n * @see StorageEventMultiCaster\n * @see ErrorReceivingResponseEvent\n */\n private StorageEventMultiCaster<ErrorReceivingResponseEvent, StorageEvent<ErrorReceivingResponseEvent>> errorReceivingResponseEventHandler = new StorageEventMultiCaster<ErrorReceivingResponseEvent, StorageEvent<ErrorReceivingResponseEvent>>();\n\n /**\n * Represents an event that is triggered when a response received from the service is fully processed.\n * \n * @see StorageEvent\n * @see StorageEventMultiCaster\n * @see RequestCompletedEvent\n */\n private StorageEventMultiCaster<RequestCompletedEvent, StorageEvent<RequestCompletedEvent>> requestCompletedEventHandler = new StorageEventMultiCaster<RequestCompletedEvent, StorageEvent<RequestCompletedEvent>>();\n\n /**\n * Represents an event that is triggered when a response is received from the storage service while processing a\n * request.\n * \n * @see StorageEvent\n * @see StorageEventMultiCaster\n * @see RetryingEvent\n */\n private StorageEventMultiCaster<RetryingEvent, StorageEvent<RetryingEvent>> retryingEventHandler = new StorageEventMultiCaster<RetryingEvent, StorageEvent<RetryingEvent>>();\n\n /**\n * Creates an instance of the <code>OperationContext</code> class.\n */\n public OperationContext() {\n this.clientRequestID = UUID.randomUUID().toString();\n this.requestResults = new ArrayList<RequestResult>();\n }\n\n /**\n * Gets the client side trace ID.\n * \n * @return A <code>String</cod> which represents the client request ID.\n */\n public String getClientRequestID() {\n return this.clientRequestID;\n }\n\n /**\n * Gets the operation latency, in milliseconds, from the client's perspective. This may include any potential\n * retries.\n * \n * @return A <code>long</code> which contains the client latency time in milliseconds.\n */\n public long getClientTimeInMs() {\n return this.clientTimeInMs;\n }\n\n /**\n * Gets the last request result encountered for the operation.\n * \n * @return A {@link RequestResult} object which represents the last request result.\n */\n public synchronized RequestResult getLastResult() {\n if (this.requestResults == null || this.requestResults.size() == 0) {\n return null;\n }\n else {\n return this.requestResults.get(this.requestResults.size() - 1);\n }\n }\n\n /**\n * Gets a proxy which will be used when making a request. Default is <code>null</code>. To set a proxy to use by \n * default, use {@link #setDefaultProxy}\n * \n * @return A {@link java.net.Proxy} to use when making a request.\n */\n public Proxy getProxy() {\n return this.proxy;\n }\n\n /**\n * Gets any additional headers for the request, for example, for proxy or logging information.\n * \n * @return A <code>java.util.HashMap</code> which contains the the user headers for the request.\n */\n public HashMap<String, String> getUserHeaders() {\n return this.userHeaders;\n }\n\n /**\n * Returns the set of request results that the current operation has created.\n * \n * @return An <code>ArrayList</code> object that contains {@link RequestResult} objects that represent\n * the request results created by the current operation.\n */\n public ArrayList<RequestResult> getRequestResults() {\n return this.requestResults;\n }\n\n /**\n * Reserved for internal use. Appends a {@link RequestResult} object to the internal collection in a synchronized\n * manner.\n * \n * @param requestResult\n * A {@link RequestResult} to append.\n */\n public synchronized void appendRequestResult(RequestResult requestResult) {\n this.requestResults.add(requestResult);\n }\n\n /**\n * Gets an Integer indicating at what level the client library should produce log entries by default. The\n * default can be overridden to turn on logging for an individual operation context instance by using\n * {@link #setLogLevel(Integer)}.\n * \n * @return the <code>android.util.Log</code> level to log at, or null if disabled\n * @see <a href=\"http://developer.android.com/reference/android/util/Log.html#constants\">Android Log Constants</a>\n */\n public static Integer getDefaultLogLevel() {\n return defaultLogLevel;\n }\n\n /**\n * Gets a global event multi-caster that is triggered before sending a request. It allows event listeners to be\n * dynamically added and removed.\n * \n * @return A {@link StorageEventMultiCaster} object for the <code>globalSendingRequestEventHandler</code>.\n */\n public static StorageEventMultiCaster<SendingRequestEvent, StorageEvent<SendingRequestEvent>> getGlobalSendingRequestEventHandler() {\n return OperationContext.globalSendingRequestEventHandler;\n }\n\n /**\n * Gets a global event multi-caster that is triggered when a response is received. It allows event listeners to be\n * dynamically added and removed.\n * \n * @return A {@link StorageEventMultiCaster} object for the <code>globalResponseReceivedEventHandler</code>.\n */\n public static StorageEventMultiCaster<ResponseReceivedEvent, StorageEvent<ResponseReceivedEvent>> getGlobalResponseReceivedEventHandler() {\n return OperationContext.globalResponseReceivedEventHandler;\n }\n\n /**\n * Gets a global event multi-caster that is triggered when a network error occurs before the HTTP response status and headers are received.\n * It allows event listeners to be dynamically added and removed.\n *\n * @return A {@link StorageEventMultiCaster} object for the <code>globabErrorReceivingResponseEventHandler</code>.\n */\n public static StorageEventMultiCaster<ErrorReceivingResponseEvent, StorageEvent<ErrorReceivingResponseEvent>> getGlobalErrorReceivingResponseEventHandler() {\n return OperationContext.globalErrorReceivingResponseEventHandler;\n }\n\n /**\n * Gets a global event multi-caster that is triggered when a request is completed. It allows event listeners to be\n * dynamically added and removed.\n * \n * @return A {@link StorageEventMultiCaster} object for the <code>globalRequestCompletedEventHandler</code>.\n */\n public static StorageEventMultiCaster<RequestCompletedEvent, StorageEvent<RequestCompletedEvent>> getGlobalRequestCompletedEventHandler() {\n return OperationContext.globalRequestCompletedEventHandler;\n }\n\n /**\n * Gets a global event multi-caster that is triggered when a request is retried. It allows event listeners to be\n * dynamically added and removed.\n * \n * @return A {@link StorageEventMultiCaster} object for the <code>globalRetryingEventHandler</code>.\n */\n public static StorageEventMultiCaster<RetryingEvent, StorageEvent<RetryingEvent>> getGlobalRetryingEventHandler() {\n return OperationContext.globalRetryingEventHandler;\n }\n\n /**\n * Gets the log level for this operation context.\n * \n * @return the <code>android.util.Log</code> level to log at, or null if disabled\n * @see <a href=\"http://developer.android.com/reference/android/util/Log.html#constants\">Android Log Constants</a>\n */\n public Integer getLogLevel() {\n return this.logLevel;\n }\n\n /**\n * Gets an event multi-caster that is triggered before sending a request. It allows event listeners to be\n * dynamically added and removed.\n * \n * @return A {@link StorageEventMultiCaster} object for the <code>sendingRequestEventHandler</code>.\n */\n public StorageEventMultiCaster<SendingRequestEvent, StorageEvent<SendingRequestEvent>> getSendingRequestEventHandler() {\n return this.sendingRequestEventHandler;\n }\n\n /**\n * Gets an event multi-caster that is triggered when a response is received. It allows event listeners to be\n * dynamically added and removed.\n * \n * @return A {@link StorageEventMultiCaster} object for the <code>responseReceivedEventHandler</code>.\n */\n public StorageEventMultiCaster<ResponseReceivedEvent, StorageEvent<ResponseReceivedEvent>> getResponseReceivedEventHandler() {\n return this.responseReceivedEventHandler;\n }\n\n /**\n * Gets an event multi-caster that is triggered when a network error occurs before the HTTP response status and headers are received.\n * It allows event listeners to be dynamically added and removed.\n *\n * @return A {@link StorageEventMultiCaster} object for the <code>errorReceivingResponseEventHandler</code>.\n */\n public StorageEventMultiCaster<ErrorReceivingResponseEvent, StorageEvent<ErrorReceivingResponseEvent>> getErrorReceivingResponseEventHandler() {\n return this.errorReceivingResponseEventHandler;\n }\n\n /**\n * Gets an event multi-caster that is triggered when a request is completed. It allows event listeners to be\n * dynamically added and removed.\n * \n * @return A {@link StorageEventMultiCaster} object for the <code>requestCompletedEventHandler</code>.\n */\n public StorageEventMultiCaster<RequestCompletedEvent, StorageEvent<RequestCompletedEvent>> getRequestCompletedEventHandler() {\n return this.requestCompletedEventHandler;\n }\n\n /**\n * Gets an event multi-caster that is triggered when a request is retried. It allows event listeners to be\n * dynamically added and removed.\n * \n * @return A {@link StorageEventMultiCaster} object for the <code>retryingEventHandler</code>.\n */\n public StorageEventMultiCaster<RetryingEvent, StorageEvent<RetryingEvent>> getRetryingEventHandler() {\n return this.retryingEventHandler;\n }\n\n /**\n * Reserved for internal use. Initializes the <code>OperationContext</code> in order to begin processing a\n * new operation. All operation specific information is erased.\n */\n public void initialize() {\n this.setClientTimeInMs(0);\n this.requestResults.clear();\n }\n\n /**\n * Set the client side trace ID.\n * \n * @param clientRequestID\n * A <code>String</code> which contains the client request ID to set.\n */\n public void setClientRequestID(final String clientRequestID) {\n this.clientRequestID = clientRequestID;\n }\n\n /**\n * Reserved for internal use. Represents the operation latency, in milliseconds, from the client's perspective. This\n * may include any potential retries.\n * \n * @param clientTimeInMs\n * A <code>long</code> which contains the client operation latency in milliseconds.\n */\n public void setClientTimeInMs(final long clientTimeInMs) {\n this.clientTimeInMs = clientTimeInMs;\n }\n\n /**\n * Specifies an Integer indicating at what level the client library should produce log entries by default. The\n * default can be overridden to turn on logging for an individual operation context instance by using\n * {@link #setLogLevel(Integer)}.\n * \n * @param defaultLogLevel\n * the <code>android.util.Log</code> level to log at, or null if disabled\n * @see <a href=\"http://developer.android.com/reference/android/util/Log.html#constants\">Android Log Constants</a>\n */\n public static void setDefaultLogLevel(Integer defaultLogLevel) {\n OperationContext.defaultLogLevel = defaultLogLevel;\n }\n\n /**\n * Sets a proxy which will be used when making a request. Default is <code>null</code>. To set a proxy to use by \n * default, use {@link #setDefaultProxy}\n * \n * @param proxy\n * A {@link java.net.Proxy} to use when making a request.\n */\n public void setProxy(Proxy proxy) {\n this.proxy = proxy;\n }\n\n /**\n * Sets any additional headers for the request, for example, for proxy or logging information.\n * \n * @param userHeaders\n * A <code>java.util.HashMap</code> which contains any additional headers to set.\n */\n public void setUserHeaders(final HashMap<String, String> userHeaders) {\n this.userHeaders = userHeaders;\n }\n\n /**\n * Sets a global event multi-caster that is triggered before sending a request.\n * \n * @param globalSendingRequestEventHandler\n * The {@link StorageEventMultiCaster} object to set for the\n * <code>globalSendingRequestEventHandler</code>.\n */\n public static void setGlobalSendingRequestEventHandler(\n final StorageEventMultiCaster<SendingRequestEvent, StorageEvent<SendingRequestEvent>> globalSendingRequestEventHandler) {\n OperationContext.globalSendingRequestEventHandler = globalSendingRequestEventHandler;\n }\n\n /**\n * Sets a global event multi-caster that is triggered when a response is received.\n * \n * @param globalResponseReceivedEventHandler\n * The {@link StorageEventMultiCaster} object to set for the\n * <code>globalResponseReceivedEventHandler</code>.\n */\n public static void setGlobalResponseReceivedEventHandler(\n final StorageEventMultiCaster<ResponseReceivedEvent, StorageEvent<ResponseReceivedEvent>> globalResponseReceivedEventHandler) {\n OperationContext.globalResponseReceivedEventHandler = globalResponseReceivedEventHandler;\n }\n\n /**\n * Sets a global event multi-caster that is triggered when a network error occurs before the HTTP response status and headers are received.\n *\n * @param globalErrorReceivingResponseEventHandler\n * The {@link StorageEventMultiCaster} object to set for the <code>globalErrorReceivingResponseEventHandler</code>.\n */\n public static void setGlobalErrorReceivingResponseEventHandler(\n final StorageEventMultiCaster<ErrorReceivingResponseEvent, StorageEvent<ErrorReceivingResponseEvent>> globalErrorReceivingResponseEventHandler) {\n OperationContext.globalErrorReceivingResponseEventHandler = globalErrorReceivingResponseEventHandler;\n }\n\n /**\n * Sets a global event multi-caster that is triggered when a request is completed.\n * \n * @param globalRequestCompletedEventHandler\n * The {@link StorageEventMultiCaster} object to set for the\n * <code>globalRequestCompletedEventHandler</code>.\n */\n public static void setGlobalRequestCompletedEventHandler(\n final StorageEventMultiCaster<RequestCompletedEvent, StorageEvent<RequestCompletedEvent>> globalRequestCompletedEventHandler) {\n OperationContext.globalRequestCompletedEventHandler = globalRequestCompletedEventHandler;\n }\n\n /**\n * Sets a global event multi-caster that is triggered when a request is retried.\n * \n * @param globalRetryingEventHandler\n * The {@link StorageEventMultiCaster} object to set for the <code>globalRetryingEventHandler</code>.\n */\n public static void setGlobalRetryingEventHandler(\n final StorageEventMultiCaster<RetryingEvent, StorageEvent<RetryingEvent>> globalRetryingEventHandler) {\n OperationContext.globalRetryingEventHandler = globalRetryingEventHandler;\n }\n\n /**\n * Sets the log level for this operation context.\n * \n * @param logLevel\n * the <code>android.util.Log</code> level to log at, or null to disable\n * @see <a href=\"http://developer.android.com/reference/android/util/Log.html#constants\">Android Log Constants</a>\n */\n public void setLogLevel(Integer logLevel) {\n this.logLevel = logLevel;\n }\n\n /**\n * Sets an event multi-caster that is triggered before sending a request.\n * \n * @param sendingRequestEventHandler\n * The {@link StorageEventMultiCaster} object to set for the <code>sendingRequestEventHandler</code>.\n */\n public void setSendingRequestEventHandler(\n final StorageEventMultiCaster<SendingRequestEvent, StorageEvent<SendingRequestEvent>> sendingRequestEventHandler) {\n this.sendingRequestEventHandler = sendingRequestEventHandler;\n }\n\n /**\n * Sets an event multi-caster that is triggered when a response is received.\n * \n * @param responseReceivedEventHandler\n * The {@link StorageEventMultiCaster} object to set for the <code>responseReceivedEventHandler</code>.\n */\n public void setResponseReceivedEventHandler(\n final StorageEventMultiCaster<ResponseReceivedEvent, StorageEvent<ResponseReceivedEvent>> responseReceivedEventHandler) {\n this.responseReceivedEventHandler = responseReceivedEventHandler;\n }\n\n /**\n * Sets an event multi-caster that is triggered when a network error occurs before the HTTP response status and headers are received.\n *\n * @param errorReceivingResponseEventHandler\n * The {@link StorageEventMultiCaster} object to set for the <code>errorReceivingResponseEventHandler</code>.\n */\n public void setErrorReceivingResponseEventHandler(\n final StorageEventMultiCaster<ErrorReceivingResponseEvent, StorageEvent<ErrorReceivingResponseEvent>> errorReceivingResponseEventHandler) {\n this.errorReceivingResponseEventHandler = errorReceivingResponseEventHandler;\n }\n\n /**\n * Sets an event multi-caster that is triggered when a request is completed.\n * \n * @param requestCompletedEventHandler\n * The {@link StorageEventMultiCaster} object to set for the <code>requestCompletedEventHandler</code>.\n */\n public void setRequestCompletedEventHandler(\n final StorageEventMultiCaster<RequestCompletedEvent, StorageEvent<RequestCompletedEvent>> requestCompletedEventHandler) {\n this.requestCompletedEventHandler = requestCompletedEventHandler;\n }\n\n /**\n * Sets an event multi-caster that is triggered when a request is retried.\n * \n * @param retryingEventHandler\n * The {@link StorageEventMultiCaster} object to set for the <code>retryingEventHandler</code>.\n */\n public void setRetryingEventHandler(\n final StorageEventMultiCaster<RetryingEvent, StorageEvent<RetryingEvent>> retryingEventHandler) {\n this.retryingEventHandler = retryingEventHandler;\n }\n\n /**\n * Gets the default proxy used by the client library if enabled. The default can be overridden\n * to enable a proxy for an individual operation context instance by using {@link #setProxy}.\n * \n * @return The default {@link java.net.Proxy} if set; otherwise <code>null</code>\n */\n public static Proxy getDefaultProxy() {\n return OperationContext.proxyDefault;\n }\n\n /**\n * Specifies the proxy the client library should use by default. The default can be overridden\n * to turn on a proxy for an individual operation context instance by using {@link #setProxy}.\n * \n * @param defaultProxy\n * The {@link java.net.Proxy} to use by default, or <code>null</code> to not use a proxy.\n */\n public static void setDefaultProxy(Proxy defaultProxy) {\n OperationContext.proxyDefault = defaultProxy;\n }\n}", "public final class SharedAccessPolicySerializer {\n /**\n * RESERVED FOR INTERNAL USE. Writes a collection of shared access policies to the specified stream in XML format.\n *\n * @param <T>\n *\n * @param sharedAccessPolicies\n * A collection of shared access policies\n * @param outWriter\n * a sink to write the output to.\n * @throws IOException\n * if there is an error writing the shared access identifiers.\n * @throws IllegalStateException\n * if there is an error writing the shared access identifiers.\n * @throws IllegalArgumentException\n * if there is an error writing the shared access identifiers.\n */\n public static <T extends SharedAccessPolicy> void writeSharedAccessIdentifiersToStream(\n final HashMap<String, T> sharedAccessPolicies, final StringWriter outWriter)\n throws IllegalArgumentException, IllegalStateException, IOException {\n Utility.assertNotNull(\"sharedAccessPolicies\", sharedAccessPolicies);\n Utility.assertNotNull(\"outWriter\", outWriter);\n\n final XmlSerializer xmlw = Utility.getXmlSerializer(outWriter);\n\n if (sharedAccessPolicies.keySet().size() > Constants.MAX_SHARED_ACCESS_POLICY_IDENTIFIERS) {\n final String errorMessage = String.format(SR.TOO_MANY_SHARED_ACCESS_POLICY_IDENTIFIERS,\n sharedAccessPolicies.keySet().size(), Constants.MAX_SHARED_ACCESS_POLICY_IDENTIFIERS);\n\n throw new IllegalArgumentException(errorMessage);\n }\n\n // default is UTF8\n xmlw.startDocument(Constants.UTF8_CHARSET, true);\n xmlw.startTag(Constants.EMPTY_STRING, Constants.SIGNED_IDENTIFIERS_ELEMENT);\n\n for (final Entry<String, T> entry : sharedAccessPolicies.entrySet()) {\n final SharedAccessPolicy policy = entry.getValue();\n xmlw.startTag(Constants.EMPTY_STRING, Constants.SIGNED_IDENTIFIER_ELEMENT);\n\n // Set the identifier\n Utility.serializeElement(xmlw, Constants.ID, entry.getKey());\n\n xmlw.startTag(Constants.EMPTY_STRING, Constants.ACCESS_POLICY);\n\n // Set the Start Time\n Utility.serializeElement(xmlw, Constants.START, Utility\n .getUTCTimeOrEmpty(policy.getSharedAccessStartTime()).toString());\n\n // Set the Expiry Time\n Utility.serializeElement(xmlw, Constants.EXPIRY,\n Utility.getUTCTimeOrEmpty(policy.getSharedAccessExpiryTime()).toString());\n\n // Set the Permissions\n Utility.serializeElement(xmlw, Constants.PERMISSION, policy.permissionsToString());\n\n // end AccessPolicy\n xmlw.endTag(Constants.EMPTY_STRING, Constants.ACCESS_POLICY);\n // end SignedIdentifier\n xmlw.endTag(Constants.EMPTY_STRING, Constants.SIGNED_IDENTIFIER_ELEMENT);\n }\n\n // end SignedIdentifiers\n xmlw.endTag(Constants.EMPTY_STRING, Constants.SIGNED_IDENTIFIERS_ELEMENT);\n // end doc\n xmlw.endDocument();\n }\n}", "public final class StorageErrorCodeStrings {\n /**\n * The specified account already exists.\n */\n public static final String ACCOUNT_ALREADY_EXISTS = \"AccountAlreadyExists\";\n\n /**\n * The specified account is in the process of being created.\n */\n public static final String ACCOUNT_BEING_CREATED = \"AccountBeingCreated\";\n\n /**\n * The specified account is disabled.\n */\n public static final String ACCOUNT_IS_DISABLED = \"AccountIsDisabled\";\n\n /**\n * Authentication failed.\n */\n public static final String AUTHENTICATION_FAILED = \"AuthenticationFailed\";\n\n /**\n * The specified blob already exists.\n */\n public static final String BLOB_ALREADY_EXISTS = \"BlobAlreadyExists\";\n\n /**\n * The specified blob does not exist.\n */\n public static final String BLOB_NOT_FOUND = \"BlobNotFound\";\n\n /**\n * Could not verify the copy source within the specified time. Examine the HTTP status code and message for more\n * information about the failure.\n */\n public static final String CANNOT_VERIFY_COPY_SOURCE = \"CannotVerifyCopySource\";\n\n /**\n * The file or directory could not be deleted because it is in use by an SMB client.\n */\n public static final String CANNOT_DELETE_FILE_OR_DIRECTORY = \"CannotDeleteFileOrDirectory\";\n\n /**\n * The specified resource state could not be flushed from an SMB client in the specified time.\n */\n public static final String CLIENT_CACHE_FLUSH_DELAY = \"ClientCacheFlushDelay\";\n\n /**\n * Condition headers are not supported.\n */\n public static final String CONDITION_HEADERS_NOT_SUPPORTED = \"ConditionHeadersNotSupported\";\n\n /**\n * The specified condition was not met.\n */\n public static final String CONDITION_NOT_MET = \"ConditionNotMet\";\n\n /**\n * The specified container already exists.\n */\n public static final String CONTAINER_ALREADY_EXISTS = \"ContainerAlreadyExists\";\n\n /**\n * The specified container is being deleted.\n */\n public static final String CONTAINER_BEING_DELETED = \"ContainerBeingDeleted\";\n\n /**\n * The specified container is disabled.\n */\n public static final String CONTAINER_DISABLED = \"ContainerDisabled\";\n\n /**\n * The specified container was not found.\n */\n public static final String CONTAINER_NOT_FOUND = \"ContainerNotFound\";\n\n /**\n * The copy source account and destination account must be the same.\n */\n public static final String COPY_ACROSS_ACCOUNTS_NOT_SUPPORTED = \"CopyAcrossAccountsNotSupported\";\n\n /**\n * The specified copy ID did not match the copy ID for the pending copy operation.\n */\n public static final String COPY_ID_MISMATCH = \"CopyIdMismatch\";\n\n /**\n * The specified resource is marked for deletion by an SMB client.\n */\n public static final String DELETE_PENDING = \"DeletePending\";\n\n /**\n * The specified directory already exists.\n */\n public static final String DIRECTORY_ALREADY_EXISTS = \"DirectoryAlreadyExists\";\n\n /**\n * The specified directory is not empty.\n */\n public static final String DIRECTORY_NOT_EMPTY = \"DirectoryNotEmpty\";\n\n /**\n * A property is specified more than one time.\n */\n public static final String DUPLICATE_PROPERTIES_SPECIFIED = \"DuplicatePropertiesSpecified\";\n /**\n * The metadata key is empty.\n */\n public static final String EMPTY_METADATA_KEY = \"EmptyMetadataKey\";\n\n /**\n * The entity already exists\n */\n public static final String ENTITY_ALREADY_EXISTS = \"EntityAlreadyExists\";\n\n /**\n * The entity already exists\n */\n public static final String ENTITY_TOO_LARGE = \"EntityTooLarge\";\n\n /**\n * A portion of the specified file is locked by an SMB client.\n */\n public static final String FILE_LOCK_CONFLICT = \"FileLockConflict\";\n\n /**\n * The required host information is not present in the request. You must send a non-empty Host header or include the\n * absolute URI in the request line.\n */\n public static final String HOST_INFORMATION_NOT_PRESENT = \"HostInformationNotPresent\";\n\n /**\n * An incorrect blob type was specified.\n */\n public static final String INCORRECT_BLOB_TYPE = \"IncorrectBlobType\";\n\n /**\n * The lease ID matched, but the specified lease must be an infinite-duration lease.\n */\n public static final String INFINITE_LEASE_DURATION_REQUIRED = \"InfiniteLeaseDurationRequired\";\n\n /**\n * The account being accessed does not have sufficient permissions to execute this operation.\n */\n public static final String INSUFFICIENT_ACCOUNT_PERMISSIONS = \"InsufficientAccountPermissions\";\n\n /**\n * An internal error occurred.\n */\n public static final String INTERNAL_ERROR = \"InternalError\";\n\n /**\n * The authentication information was not provided in the correct format. Verify the value of Authorization header.\n */\n public static final String INVALID_AUTHENTICATION_INFO = \"InvalidAuthenticationInfo\";\n\n /**\n * Error code that may be returned when the specified append offset is invalid.\n */\n public static final String INVALID_APPEND_POSITION = \"AppendPositionConditionNotMet\";\n \n /**\n * An incorrect blob type was specified.\n */\n public static final String INVALID_BLOB_TYPE = \"InvalidBlobType\";\n\n /**\n * The specified blob or block content is invalid.\n */\n public static final String INVALID_BLOB_OR_BLOCK = \"InvalidBlobOrBlock\";\n\n /**\n * The specified block ID is invalid. The block ID must be Base64-encoded.\n */\n public static final String INVALID_BLOCK_ID = \"InvalidBlockId\";\n\n /**\n * The specified block list is invalid.\n */\n public static final String INVALID_BLOCK_LIST = \"InvalidBlockList\";\n\n /**\n * One or more header values are invalid.\n */\n public static final String INVALID_HEADER_VALUE = \"InvalidHeaderValue\";\n\n /**\n * The HTTP verb is invalid.\n */\n public static final String INVALID_HTTP_VERB = \"InvalidHttpVerb\";\n\n /**\n * The input is invalid.\n */\n public static final String INVALID_INPUT = \"InvalidInput\";\n\n /**\n * The specified marker is invalid.\n */\n public static final String INVALID_MARKER = \"InvalidMarker\";\n\n /**\n * Error code that may be returned when the specified max blob size is exceeded.\n */\n public static final String INVALID_MAX_BLOB_SIZE_CONDITION = \"MaxBlobSizeConditionNotMet\"; \n\n /**\n * The specified MD5 hash is invalid.\n */\n public static final String INVALID_MD5 = \"InvalidMd5\";\n\n /**\n * The specified metadata is invalid.\n */\n public static final String INVALID_METADATA = \"InvalidMetadata\";\n\n /**\n * The page range specified is invalid.\n */\n public static final String INVALID_PAGE_RANGE = \"InvalidPageRange\";\n\n /**\n * One or more query parameters are invalid.\n */\n public static final String INVALID_QUERY_PARAMETER_VALUE = \"InvalidQueryParameterValue\";\n\n /**\n * The specified range is invalid.\n */\n public static final String INVALID_RANGE = \"InvalidRange\";\n\n /**\n * The specified resource name contains invalid characters.\n */\n public static final String INVALID_RESOURCE_NAME = \"InvalidResourceName\";\n\n /**\n * The URI is invalid.\n */\n public static final String INVALID_URI = \"InvalidUri\";\n\n /**\n * The value specified is invalid.\n */\n public static final String INVALID_VALUE_TYPE = \"InvalidValueType\";\n\n /**\n * All operations on page blobs require at least version 2009-09-19.\n */\n public static final String INVALID_VERSION_FOR_PAGE_BLOB_OPERATION = \"InvalidVersionForPageBlobOperation\";\n\n /**\n * The specified XML document is invalid.\n */\n public static final String INVALID_XML_DOCUMENT = \"InvalidXmlDocument\";\n\n /**\n * The value provided for one of the XML nodes in the request body was not in the correct format.\n */\n public static final String INVALID_XML_NODE_VALUE = \"InvalidXmlNodeValue\";\n\n /**\n * The specified XML or Json document is invalid. Used for tables only.\n */\n public static final String INVALID_DOCUMENT = \"InvalidDocument\";\n\n /**\n * File or directory path is too long or file or directory path has too many subdirectories.\n */\n public static final String INVALID_FILE_OR_DIRECTORY_PATH_NAME = \"InvalidFileOrDirectoryPathName\";\n\n /**\n * The incorrect type was given. Used for tables only.\n */\n public static final String INVALID_TYPE = \"InvalidType\";\n\n /**\n * JSON format is not supported.\n */\n public static final String JSON_FORMAT_NOT_SUPPORTED = \"JsonFormatNotSupported\";\n\n /**\n * The lease is already broken.\n */\n public static final String LEASE_ALREADY_BROKEN = \"LeaseAlreadyBroken\";\n\n /**\n * The lease is already present.\n */\n public static final String LEASE_ALREADY_PRESENT = \"LeaseAlreadyPresent\";\n\n /**\n * The lease ID is incorrect with a blob operation.\n */\n public static final String LEASE_ID_MISMATCH_WITH_BLOB_OPERATION = \"LeaseIdMismatchWithBlobOperation\";\n\n /**\n * The lease ID is incorrect with a container operation.\n */\n public static final String LEASE_ID_MISMATCH_WITH_CONTAINER_OPERATION = \"LeaseIdMismatchWithContainerOperation\";\n\n /**\n * The lease ID is incorrect with a lease operation.\n */\n public static final String LEASE_ID_MISMATCH_WITH_LEASE_OPERATION = \"LeaseIdMismatchWithLeaseOperation\";\n\n /**\n * The lease ID is missing.\n */\n public static final String LEASE_ID_MISSING = \"LeaseIdMissing\";\n\n /**\n * The lease ID matched, but the lease has been broken explicitly and cannot be renewed.\n */\n public static final String LEASE_IS_BROKEN_AND_CANNOT_BE_RENEWED = \"LeaseIsBrokenAndCannotBeRenewed\";\n\n /**\n * The lease ID matched, but the lease is currently in breaking state and cannot be acquired until it is broken.\n */\n public static final String LEASE_IS_BREAKING_AND_CANNOT_BE_ACQUIRED = \"LeaseIsBreakingAndCannotBeAcquired\";\n\n /**\n * The lease ID matched, but the lease is currently in breaking state and cannot be changed.\n */\n public static final String LEASE_IS_BREAKING_AND_CANNOT_BE_CHANGED = \"LeaseIsBreakingAndCannotBeChanged\";\n\n /**\n * A lease ID was specified, but the lease for the blob/container has expired.\n */\n public static final String LEASE_LOST = \"LeaseLost\";\n\n /**\n * There is currently no lease on the blob.\n */\n public static final String LEASE_NOT_PRESENT_WITH_BLOB_OPERATION = \"LeaseNotPresentWithBlobOperation\";\n\n /**\n * There is currently no lease on the container.\n */\n public static final String LEASE_NOT_PRESENT_WITH_CONTAINER_OPERATION = \"LeaseNotPresentWithContainerOperation\";\n\n /**\n * There is currently no lease on the blob/container.\n */\n public static final String LEASE_NOT_PRESENT_WITH_LEASE_OPERATION = \"LeaseNotPresentWithLeaseOperation\";\n\n /**\n * The specified MD5 hash does not match the server value.\n */\n public static final String MD5_MISMATCH = \"Md5Mismatch\";\n\n /**\n * The message exceeds the maximum allowed size.\n */\n public static final String MESSAGE_TOO_LARGE = \"MessageTooLarge\";\n\n /**\n * The specified message does not exist.\n */\n public static final String MESSAGE_NOT_FOUND = \"MessageNotFound\";\n\n /**\n * The specified metadata is too large.\n */\n public static final String METADATA_TOO_LARGE = \"MetadataTooLarge\";\n\n /**\n * The requested method is not allowed on the specified resource.\n */\n public static final String METHOD_NOT_ALLOWED = \"MethodNotAllowed\";\n\n /**\n * The Content-Length header is required for this request.\n */\n public static final String MISSING_CONTENT_LENGTH_HEADER = \"MissingContentLengthHeader\";\n\n /**\n * A required header was missing.\n */\n public static final String MISSING_REQUIRED_HEADER = \"MissingRequiredHeader\";\n\n /**\n * A required query parameter is missing.\n */\n public static final String MISSING_REQUIRED_QUERY_PARAMETER = \"MissingRequiredQueryParameter\";\n\n /**\n * A required XML node was missing.\n */\n public static final String MISSING_REQUIRED_XML_NODE = \"MissingRequiredXmlNode\";\n\n /**\n * The MD5 hash is missing.\n */\n public static final String MISSING_MD5_HEADER = \"MissingContentMD5Header\";\n\n /**\n * Multiple condition headers are not supported.\n */\n public static final String MULTIPLE_CONDITION_HEADERS_NOT_SUPPORTED = \"MultipleConditionHeadersNotSupported\";\n\n /**\n * There is currently no pending copy operation.\n */\n public static final String NO_PENDING_COPY_OPERATION = \"NoPendingCopyOperation\";\n\n /**\n * The requested operation is not implemented on the specified resource.\n */\n public static final String NOT_IMPLEMENTED = \"NotImplemented\";\n\n /**\n * The operation timed out.\n */\n public static final String OPERATION_TIMED_OUT = \"OperationTimedOut\";\n\n /**\n * The input is out of range.\n */\n public static final String OUT_OF_RANGE_INPUT = \"OutOfRangeInput\";\n\n /**\n * One or more query parameters are out of range.\n */\n public static final String OUT_OF_RANGE_QUERY_PARAMETER_VALUE = \"OutOfRangeQueryParameterValue\";\n\n /**\n * The specified parent path does not exist.\n */\n public static final String PARENT_NOT_FOUND = \"ParentNotFound\";\n\n /**\n * There is currently a pending copy operation.\n */\n public static final String PENDING_COPY_OPERATION = \"PendingCopyOperation\";\n\n /**\n * The specified pop receipt did not match the pop receipt for a dequeued message.\n */\n public static final String POP_RECEIPT_MISMATCH = \"PopReceiptMismatch\";\n\n /**\n * Values have not been specified for all properties in the entity.\n */\n public static final String PROPERTIES_NEED_VALUE = \"PropertiesNeedValue\";\n\n /**\n * The property name is invalid.\n */\n public static final String PROPERTY_NAME_INVALID = \"PropertyNameInvalid\";\n\n /**\n * The property name exceeds the maximum allowed length.\n */\n public static final String PROPERTY_NAME_TOO_LONG = \"PropertyNameTooLong\";\n\n /**\n * The property value is larger than the maximum size permitted.\n */\n public static final String PROPERTY_VALUE_TOO_LARGE = \"PropertyValueTooLarge\";\n\n /**\n * The specified queue already exists.\n */\n public static final String QUEUE_ALREADY_EXISTS = \"QueueAlreadyExists\";\n\n /**\n * The specified queue is being deleted.\n */\n public static final String QUEUE_BEING_DELETED = \"QueueBeingDeleted\";\n\n /**\n * The specified queue has been disabled by the administrator.\n */\n public static final String QUEUE_DISABLED = \"QueueDisabled\";\n\n /**\n * The specified queue is not empty.\n */\n public static final String QUEUE_NOT_EMPTY = \"QueueNotEmpty\";\n\n /**\n * The specified queue does not exist.\n */\n public static final String QUEUE_NOT_FOUND = \"QueueNotFound\";\n\n /**\n * The specified resource is read-only and cannot be modified at this time.\n */\n public static final String READ_ONLY_ATTRIBUTE = \"ReadOnlyAttribute\";\n\n /**\n * The request body is too large.\n */\n public static final String REQUEST_BODY_TOO_LARGE = \"RequestBodyTooLarge\";\n\n /**\n * The url in the request could not be parsed.\n */\n public static final String REQUEST_URL_FAILED_TO_PARSE = \"RequestUrlFailedToParse\";\n\n /**\n * The specified resource was not found.\n */\n public static final String RESOURCE_NOT_FOUND = \"ResourceNotFound\";\n\n /**\n * The specified resource already exists.\n */\n public static final String RESOURCE_ALREADY_EXISTS = \"ResourceAlreadyExists\";\n\n /**\n * The specified resource type does not match the type of the existing resource.\n */\n public static final String RESOURCE_TYPE_MISMATCH = \"ResourceTypeMismatch\";\n\n /**\n * The sequence number condition specified was not met.\n */\n public static final String SEQUENCE_NUMBER_CONDITION_NOT_MET = \"SequenceNumberConditionNotMet\";\n\n /**\n * The sequence number increment cannot be performed because it would result in overflow of the sequence number.\n */\n public static final String SEQUENCE_NUMBER_INCREMENT_TOO_LARGE = \"SequenceNumberIncrementTooLarge\";\n\n /**\n * The server is busy.\n */\n public static final String SERVER_BUSY = \"ServerBusy\";\n\n /**\n * The specified share already exists.\n */\n public static final String SHARE_ALREADY_EXISTS = \"ShareAlreadyExists\";\n\n /**\n * The specified share is being deleted. Try operation later.\n */\n public static final String SHARE_BEING_DELETED = \"ShareBeingDeleted\";\n\n /**\n * The specified share is disabled by the administrator.\n */\n public static final String SHARE_DISABLED = \"ShareDisabled\";\n\n /**\n * The specified share contains snapshots.\n */\n public static final String SHARE_HAS_SNAPSHOTS = \"ShareHasSnapshots\";\n\n /**\n * The specified share was not found.\n */\n public static final String SHARE_NOT_FOUND = \"ShareNotFound\";\n\n /**\n * The specified resource may be in use by an SMB client.\n */\n public static final String SHARING_VIOLATION = \"SharingViolation\";\n\n /**\n * This operation is not permitted because the blob has snapshots.\n */\n public static final String SNAPSHOTS_PRESENT = \"SnapshotsPresent\";\n\n /**\n * The source condition specified using HTTP conditional header(s) is not met.\n */\n public static final String SOURCE_CONDITION_NOT_MET = \"SourceConditionNotMet\";\n\n /**\n * The target condition specified using HTTP conditional header(s) is not met.\n */\n public static final String TARGET_CONDITION_NOT_MET = \"TargetConditionNotMet\";\n\n /**\n * The table specified already exists.\n */\n public static final String TABLE_ALREADY_EXISTS = \"TableAlreadyExists\";\n\n /**\n * The specified table is being deleted.\n */\n public static final String TABLE_BEING_DELETED = \"TableBeingDeleted\";\n\n /**\n * The table specified does not exist.\n */\n public static final String TABLE_NOT_FOUND = \"TableNotFound\";\n\n /**\n * The entity contains more properties than allowed.\n */\n public static final String TOO_MANY_PROPERTIES = \"TooManyProperties\";\n\n /**\n * The update condition was not satisfied\n */\n public static final String UPDATE_CONDITION_NOT_SATISFIED = \"UpdateConditionNotSatisfied\";\n\n /**\n * One or more header values are not supported.\n */\n public static final String UNSUPPORTED_HEADER = \"UnsupportedHeader\";\n\n /**\n * One of the XML nodes specified in the request body is not supported.\n */\n public static final String UNSUPPORTED_XML_NODE = \"UnsupportedXmlNode\";\n\n /**\n * The specified HTTP verb is not supported.\n */\n public static final String UNSUPPORTED_HTTP_VERB = \"UnsupportedHttpVerb\";\n\n /**\n * One or more query parameters is not supported.\n */\n public static final String UNSUPPORTED_QUERY_PARAMETER = \"UnsupportedQueryParameter\";\n\n /**\n * More than one X-HTTP-Method is specified.\n */\n public static final String X_METHOD_INCORRECT_COUNT = \"XMethodIncorrectCount\";\n\n /**\n * The specified X-HTTP-Method is invalid.\n */\n public static final String X_METHOD_INCORRECT_VALUE = \"XMethodIncorrectValue\";\n\n /**\n * The request uses X-HTTP-Method with an HTTP verb other than POST.\n */\n public static final String X_METHOD_NOT_USING_POST = \"XMethodNotUsingPost\";\n\n /**\n * Private Default Constructor.\n */\n private StorageErrorCodeStrings() {\n // No op\n }\n}", "public final class ExecutionEngine {\n /**\n * Executes an operation and enforces a retrypolicy to handle any potential errors\n * \n * @param <CLIENT_TYPE>\n * The type of the service client\n * @param <PARENT_TYPE>\n * The type of the parent object, i.e. CloudBlobContainer for downloadAttributes etc.\n * @param <RESULT_TYPE>\n * The type of the expected result\n * @param client\n * the service client associated with the request\n * @param parentObject\n * the parent object\n * @param task\n * the StorageRequest to execute\n * @param policyFactory\n * the factory used to generate a new retry policy instance\n * @param opContext\n * an object used to track the execution of the operation\n * @return the result of the operation\n * @throws StorageException\n * an exception representing any error which occurred during the operation.\n */\n public static <CLIENT_TYPE, PARENT_TYPE, RESULT_TYPE> RESULT_TYPE executeWithRetry(final CLIENT_TYPE client,\n final PARENT_TYPE parentObject, final StorageRequest<CLIENT_TYPE, PARENT_TYPE, RESULT_TYPE> task,\n final RetryPolicyFactory policyFactory, final OperationContext opContext) throws StorageException {\n\n RetryPolicy policy = null;\n\n if (policyFactory == null) {\n policy = new RetryNoRetry();\n }\n else {\n policy = policyFactory.createInstance(opContext);\n\n // if the returned policy is null, set to not retry\n if (policy == null) {\n policy = new RetryNoRetry();\n }\n }\n\n int currentRetryCount = 0;\n StorageException translatedException = null;\n HttpURLConnection request = null;\n final long startTime = new Date().getTime();\n\n while (true) {\n try {\n // 1-4: setup the request\n request = setupStorageRequest(client, parentObject, task, currentRetryCount, opContext);\n\n Logger.info(opContext, LogConstants.START_REQUEST, request.getURL(),\n request.getRequestProperty(Constants.HeaderConstants.DATE));\n\n // 5. Potentially upload data\n boolean responseReceivedEventTriggered = false;\n try {\n if (task.getSendStream() != null) {\n Logger.info(opContext, LogConstants.UPLOAD);\n final StreamMd5AndLength descriptor = Utility.writeToOutputStream(task.getSendStream(),\n request.getOutputStream(), task.getLength(), false /* rewindStream */,\n false /* calculate MD5 */, opContext, task.getRequestOptions());\n\n task.validateStreamWrite(descriptor);\n Logger.info(opContext, LogConstants.UPLOADDONE);\n }\n\n Utility.logHttpRequest(request, opContext);\n\n // 6. Process the request - Get response\n RequestResult currResult = task.getResult();\n currResult.setStartDate(new Date());\n\n Logger.info(opContext, LogConstants.GET_RESPONSE);\n\n currResult.setStatusCode(request.getResponseCode());\n currResult.setStatusMessage(request.getResponseMessage());\n currResult.setStopDate(new Date());\n\n currResult.setServiceRequestID(BaseResponse.getRequestId(request));\n currResult.setEtag(BaseResponse.getEtag(request));\n currResult.setRequestDate(BaseResponse.getDate(request));\n currResult.setContentMD5(BaseResponse.getContentMD5(request));\n\n // 7. Fire ResponseReceived Event\n responseReceivedEventTriggered = true;\n ExecutionEngine.fireResponseReceivedEvent(opContext, request, task.getResult());\n\n Logger.info(opContext, LogConstants.RESPONSE_RECEIVED, currResult.getStatusCode(),\n currResult.getServiceRequestID(), currResult.getContentMD5(), currResult.getEtag(),\n currResult.getRequestDate());\n\n Utility.logHttpResponse(request, opContext);\n }\n finally {\n Logger.info(opContext, LogConstants.ERROR_RECEIVING_RESPONSE);\n if (!responseReceivedEventTriggered) {\n if (task.getResult().getStartDate() == null) {\n task.getResult().setStartDate(new Date());\n }\n\n ExecutionEngine.fireErrorReceivingResponseEvent(opContext, request, task.getResult());\n }\n }\n\n // 8. Pre-process response to check if there was an exception. Do Response parsing (headers etc).\n Logger.info(opContext, LogConstants.PRE_PROCESS);\n RESULT_TYPE result = task.preProcessResponse(parentObject, client, opContext);\n Logger.info(opContext, LogConstants.PRE_PROCESS_DONE);\n\n if (!task.isNonExceptionedRetryableFailure()) {\n\n // 9. Post-process response. Read stream from server.\n Logger.info(opContext, LogConstants.POST_PROCESS);\n result = task.postProcessResponse(request, parentObject, client, opContext, result);\n Logger.info(opContext, LogConstants.POST_PROCESS_DONE);\n\n // Success return result and drain the input stream.\n if ((task.getResult().getStatusCode() >= 200) && (task.getResult().getStatusCode() < 300)) {\n if (request != null) {\n InputStream inStream = request.getInputStream();\n // At this point, we already have a result / exception to return to the user.\n // This is just an optimization to improve socket reuse.\n try {\n Utility.writeToOutputStream(inStream, null, -1, false, false, null,\n task.getRequestOptions());\n }\n catch (final IOException ex) {\n }\n catch (StorageException e) {\n }\n finally {\n inStream.close();\n }\n }\n }\n Logger.info(opContext, LogConstants.COMPLETE);\n\n return result;\n }\n else {\n Logger.warn(opContext, LogConstants.UNEXPECTED_RESULT_OR_EXCEPTION);\n // The task may have already parsed an exception.\n translatedException = task.materializeException(opContext);\n task.getResult().setException(translatedException);\n\n // throw on non retryable status codes: 501, 505, blob type mismatch\n if (task.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_IMPLEMENTED\n || task.getResult().getStatusCode() == HttpURLConnection.HTTP_VERSION\n || translatedException.getErrorCode().equals(StorageErrorCodeStrings.INVALID_BLOB_TYPE)) {\n throw translatedException;\n }\n }\n }\n catch (final NetworkOnMainThreadException e) {\n // Non Retryable, just throw\n translatedException = new StorageException(\"NetworkOnMainThreadException\",\n SR.NETWORK_ON_MAIN_THREAD_EXCEPTION, -1, null, e);\n task.getResult().setException(translatedException);\n Logger.error(opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());\n throw translatedException;\n }\n catch (final StorageException e) {\n // In case of table batch error or internal error, the exception will contain a different\n // status code and message than the original HTTP response. Reset based on error values.\n task.getResult().setStatusCode(e.getHttpStatusCode());\n task.getResult().setStatusMessage(e.getMessage());\n task.getResult().setException(e);\n \n Logger.warn(opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());\n translatedException = e;\n }\n catch (final Exception e) {\n // Retryable, wrap\n Logger.warn(opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());\n translatedException = StorageException.translateException(task, e, opContext);\n task.getResult().setException(translatedException);\n }\n finally {\n opContext.setClientTimeInMs(new Date().getTime() - startTime);\n\n // 10. Fire RequestCompleted Event\n if (task.isSent()) {\n ExecutionEngine.fireRequestCompletedEvent(opContext, request, task.getResult());\n }\n }\n\n // Evaluate Retry Policy\n Logger.info(opContext, LogConstants.RETRY_CHECK, currentRetryCount, task.getResult().getStatusCode(),\n translatedException == null ? null : translatedException.getMessage());\n\n task.setCurrentLocation(getNextLocation(task.getCurrentLocation(), task.getLocationMode()));\n Logger.info(opContext, LogConstants.NEXT_LOCATION, task.getCurrentLocation(), task.getLocationMode());\n\n RetryContext retryContext = new RetryContext(currentRetryCount++, task.getResult(),\n task.getCurrentLocation(), task.getLocationMode());\n\n RetryInfo retryInfo = policy.evaluate(retryContext, opContext);\n\n if (retryInfo == null) {\n // policy does not allow for retry\n Logger.error(opContext, LogConstants.DO_NOT_RETRY_POLICY, translatedException == null ? null\n : translatedException.getMessage());\n throw translatedException;\n }\n else if (Utility.validateMaxExecutionTimeout(task.getRequestOptions().getOperationExpiryTimeInMs(),\n retryInfo.getRetryInterval())) {\n // maximum execution time would be exceeded by current time plus retry interval delay\n TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION);\n translatedException = new StorageException(StorageErrorCodeStrings.OPERATION_TIMED_OUT,\n SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION, Constants.HeaderConstants.HTTP_UNUSED_306, null,\n timeoutException);\n\n task.initialize(opContext);\n task.getResult().setException(translatedException);\n\n Logger.error(opContext, LogConstants.DO_NOT_RETRY_TIMEOUT, translatedException == null ? null\n : translatedException.getMessage());\n\n throw translatedException;\n }\n else {\n // attempt to retry\n task.setCurrentLocation(retryInfo.getTargetLocation());\n task.setLocationMode(retryInfo.getUpdatedLocationMode());\n Logger.info(opContext, LogConstants.RETRY_INFO, task.getCurrentLocation(), task.getLocationMode());\n\n try {\n ExecutionEngine.fireRetryingEvent(opContext, task.getConnection(), task.getResult(), retryContext);\n\n Logger.info(opContext, LogConstants.RETRY_DELAY, retryInfo.getRetryInterval());\n Thread.sleep(retryInfo.getRetryInterval());\n }\n catch (final InterruptedException e) {\n // Restore the interrupted status\n Thread.currentThread().interrupt();\n }\n }\n }\n }\n\n private static <CLIENT_TYPE, PARENT_TYPE, RESULT_TYPE> HttpURLConnection setupStorageRequest(\n final CLIENT_TYPE client, final PARENT_TYPE parentObject,\n final StorageRequest<CLIENT_TYPE, PARENT_TYPE, RESULT_TYPE> task, int currentRetryCount,\n final OperationContext opContext) throws StorageException {\n try {\n\n // reset result flags\n task.initialize(opContext);\n\n if (Utility.validateMaxExecutionTimeout(task.getRequestOptions().getOperationExpiryTimeInMs())) {\n // maximum execution time would be exceeded by current time\n TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION);\n throw new StorageException(StorageErrorCodeStrings.OPERATION_TIMED_OUT,\n SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION, Constants.HeaderConstants.HTTP_UNUSED_306, null,\n timeoutException);\n }\n\n // Run the recovery action if this is a retry. Else, initialize the location mode for the task. \n // For retries, it will be initialized in retry logic.\n if (currentRetryCount > 0) {\n task.recoveryAction(opContext);\n Logger.info(opContext, LogConstants.RETRY);\n }\n else {\n task.applyLocationModeToRequest();\n task.initializeLocation();\n Logger.info(opContext, LogConstants.STARTING);\n }\n\n task.setRequestLocationMode();\n\n // If the command only allows for a specific location, we should target\n // that location no matter what the retry policy says.\n task.validateLocation();\n\n Logger.info(opContext, LogConstants.INIT_LOCATION, task.getCurrentLocation(), task.getLocationMode());\n\n // 1. Build the request\n HttpURLConnection request = task.buildRequest(client, parentObject, opContext);\n\n // 2. Add headers\n task.setHeaders(request, parentObject, opContext);\n\n // Add any other custom headers that users have set on the opContext\n if (opContext.getUserHeaders() != null) {\n for (final Entry<String, String> entry : opContext.getUserHeaders().entrySet()) {\n request.setRequestProperty(entry.getKey(), entry.getValue());\n }\n }\n\n // 3. Fire sending request event\n ExecutionEngine.fireSendingRequestEvent(opContext, request, task.getResult());\n task.setIsSent(true);\n\n // 4. Sign the request\n task.signRequest(request, client, opContext);\n\n // set the connection on the task\n task.setConnection(request);\n\n return request;\n }\n catch (StorageException e) {\n throw e;\n }\n catch (Exception e) {\n throw new StorageException(null, e.getMessage(), Constants.HeaderConstants.HTTP_UNUSED_306, null, e);\n }\n }\n\n private static StorageLocation getNextLocation(StorageLocation lastLocation, LocationMode locationMode) {\n switch (locationMode) {\n case PRIMARY_ONLY:\n return StorageLocation.PRIMARY;\n\n case SECONDARY_ONLY:\n return StorageLocation.SECONDARY;\n\n case PRIMARY_THEN_SECONDARY:\n case SECONDARY_THEN_PRIMARY:\n return (lastLocation == StorageLocation.PRIMARY) ? StorageLocation.SECONDARY : StorageLocation.PRIMARY;\n\n default:\n return StorageLocation.PRIMARY;\n }\n }\n\n /**\n * Fires events representing that a request will be sent.\n */\n private static void fireSendingRequestEvent(OperationContext opContext, HttpURLConnection request,\n RequestResult result) {\n if (opContext.getSendingRequestEventHandler().hasListeners()\n || OperationContext.getGlobalSendingRequestEventHandler().hasListeners()) {\n SendingRequestEvent event = new SendingRequestEvent(opContext, request, result);\n opContext.getSendingRequestEventHandler().fireEvent(event);\n OperationContext.getGlobalSendingRequestEventHandler().fireEvent(event);\n }\n }\n\n /**\n * Fires events representing that a response has been received.\n */\n private static void fireResponseReceivedEvent(OperationContext opContext, HttpURLConnection request,\n RequestResult result) {\n if (opContext.getResponseReceivedEventHandler().hasListeners()\n || OperationContext.getGlobalResponseReceivedEventHandler().hasListeners()) {\n ResponseReceivedEvent event = new ResponseReceivedEvent(opContext, request, result);\n opContext.getResponseReceivedEventHandler().fireEvent(event);\n OperationContext.getGlobalResponseReceivedEventHandler().fireEvent(event);\n }\n }\n\n /**\n * Fires events representing that an error occurred when receiving the response.\n */\n private static void fireErrorReceivingResponseEvent(OperationContext opContext, HttpURLConnection request,\n RequestResult result) {\n if (opContext.getErrorReceivingResponseEventHandler().hasListeners()\n || OperationContext.getGlobalErrorReceivingResponseEventHandler().hasListeners()) {\n ErrorReceivingResponseEvent event = new ErrorReceivingResponseEvent(opContext, request, result);\n opContext.getErrorReceivingResponseEventHandler().fireEvent(event);\n OperationContext.getGlobalErrorReceivingResponseEventHandler().fireEvent(event);\n }\n }\n\n /**\n * Fires events representing that a response received from the service is fully processed.\n */\n private static void fireRequestCompletedEvent(OperationContext opContext, HttpURLConnection request,\n RequestResult result) {\n if (opContext.getRequestCompletedEventHandler().hasListeners()\n || OperationContext.getGlobalRequestCompletedEventHandler().hasListeners()) {\n RequestCompletedEvent event = new RequestCompletedEvent(opContext, request, result);\n opContext.getRequestCompletedEventHandler().fireEvent(event);\n OperationContext.getGlobalRequestCompletedEventHandler().fireEvent(event);\n }\n }\n\n /**\n * Fires events representing that a request will be retried.\n */\n private static void fireRetryingEvent(OperationContext opContext, HttpURLConnection request, RequestResult result,\n RetryContext retryContext) {\n if (opContext.getRetryingEventHandler().hasListeners()\n || OperationContext.getGlobalRetryingEventHandler().hasListeners()) {\n RetryingEvent event = new RetryingEvent(opContext, request, result, retryContext);\n opContext.getRetryingEventHandler().fireEvent(event);\n OperationContext.getGlobalRetryingEventHandler().fireEvent(event);\n }\n }\n}", "public class SR {\n public static final String ACCOUNT_NAME_NULL_OR_EMPTY = \"The account name is null or empty.\";\n public static final String ACCOUNT_NAME_MISMATCH = \"The account name does not match the existing account name on the credentials.\";\n public static final String APPEND_BLOB_MD5_NOT_POSSIBLE = \"MD5 cannot be calculated for an existing append blob because it would require reading the existing data. Please disable StoreFileContentMD5.\";\n public static final String ARGUMENT_NULL_OR_EMPTY = \"The argument must not be null or an empty string. Argument name: %s.\";\n public static final String ARGUMENT_OUT_OF_RANGE_ERROR = \"The argument is out of range. Argument name: %s, Value passed: %s.\";\n public static final String ATTEMPTED_TO_SERIALIZE_INACCESSIBLE_PROPERTY = \"An attempt was made to access an inaccessible member of the entity during serialization.\";\n public static final String BLOB = \"blob\";\n public static final String BLOB_DATA_CORRUPTED = \"Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s\";\n public static final String BLOB_ENDPOINT_NOT_CONFIGURED = \"No blob endpoint configured.\";\n public static final String BLOB_HASH_MISMATCH = \"Blob hash mismatch (integrity check failed), Expected value is %s, retrieved %s.\";\n public static final String BLOB_MD5_NOT_SUPPORTED_FOR_PAGE_BLOBS = \"Blob level MD5 is not supported for page blobs.\";\n public static final String BLOB_TYPE_NOT_DEFINED = \"The blob type is not defined. Allowed types are BlobType.BLOCK_BLOB and BlobType.Page_BLOB.\";\n public static final String CANNOT_CREATE_SAS_FOR_GIVEN_CREDENTIALS = \"Cannot create Shared Access Signature as the credentials does not have account name information. Please check that the credentials provided support creating Shared Access Signature.\";\n public static final String CANNOT_CREATE_SAS_FOR_SNAPSHOTS = \"Cannot create Shared Access Signature via references to blob snapshots. Please perform the given operation on the root blob instead.\";\n public static final String CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY = \"Cannot create Shared Access Signature unless the Account Key credentials are used by the ServiceClient.\";\n public static final String CANNOT_TRANSFORM_NON_HTTPS_URI_WITH_HTTPS_ONLY_CREDENTIALS = \"Cannot use HTTP with credentials that only support HTTPS.\";\n public static final String CONTAINER = \"container\";\n public static final String CONTENT_LENGTH_MISMATCH = \"An incorrect number of bytes was read from the connection. The connection may have been closed.\";\n public static final String CREATING_NETWORK_STREAM = \"Creating a NetworkInputStream and expecting to read %s bytes.\";\n public static final String CREDENTIALS_CANNOT_SIGN_REQUEST = \"CloudBlobClient, CloudQueueClient and CloudTableClient require credentials that can sign a request.\";\n public static final String CUSTOM_RESOLVER_THREW = \"The custom property resolver delegate threw an exception. Check the inner exception for more details.\";\n public static final String DEFAULT_SERVICE_VERSION_ONLY_SET_FOR_BLOB_SERVICE = \"DefaultServiceVersion can only be set for the Blob service.\";\n public static final String DELETE_SNAPSHOT_NOT_VALID_ERROR = \"The option '%s' must be 'None' to delete a specific snapshot specified by '%s'.\";\n public static final String DIRECTORY = \"directory\";\n public static final String EDMTYPE_WAS_NULL = \"EdmType cannot be null.\";\n public static final String ENUMERATION_ERROR = \"An error occurred while enumerating the result, check the original exception for details.\";\n public static final String EMPTY_BATCH_NOT_ALLOWED = \"Cannot execute an empty batch operation.\";\n public static final String ENDPOINT_INFORMATION_UNAVAILABLE = \"Endpoint information not available for Account using Shared Access Credentials.\";\n public static final String ENTITY_PROPERTY_CANNOT_BE_NULL_FOR_PRIMITIVES = \"EntityProperty cannot be set to null for primitive value types.\";\n public static final String ETAG_INVALID_FOR_DELETE = \"Delete requires a valid ETag (which may be the '*' wildcard).\";\n public static final String ETAG_INVALID_FOR_MERGE = \"Merge requires a valid ETag (which may be the '*' wildcard).\";\n public static final String ETAG_INVALID_FOR_UPDATE = \"Replace requires a valid ETag (which may be the '*' wildcard).\";\n public static final String ENUM_COULD_NOT_BE_PARSED = \"%s could not be parsed from '%s'.\";\n public static final String EXCEPTION_THROWN_DURING_DESERIALIZATION = \"The entity threw an exception during deserialization.\";\n public static final String EXCEPTION_THROWN_DURING_SERIALIZATION = \"The entity threw an exception during serialization.\";\n public static final String EXPECTED_A_FIELD_NAME = \"Expected a field name.\";\n public static final String EXPECTED_END_ARRAY = \"Expected the end of a JSON Array.\";\n public static final String EXPECTED_END_OBJECT = \"Expected the end of a JSON Object.\";\n public static final String EXPECTED_START_ARRAY = \"Expected the start of a JSON Array.\";\n public static final String EXPECTED_START_ELEMENT_TO_EQUAL_ERROR = \"Expected START_ELEMENT to equal error.\";\n public static final String EXPECTED_START_OBJECT = \"Expected the start of a JSON Object.\";\n public static final String FAILED_TO_PARSE_PROPERTY = \"Failed to parse property '%s' with value '%s' as type '%s'\";\n public static final String FILE = \"file\";\n public static final String FILE_ENDPOINT_NOT_CONFIGURED = \"No file endpoint configured.\";\n public static final String FILE_HASH_MISMATCH = \"File hash mismatch (integrity check failed), Expected value is %s, retrieved %s.\";\n public static final String FILE_MD5_NOT_POSSIBLE = \"MD5 cannot be calculated for an existing file because it would require reading the existing data. Please disable StoreFileContentMD5.\";\n public static final String INCORRECT_STREAM_LENGTH = \"An incorrect stream length was specified, resulting in an authentication failure. Please specify correct length, or -1.\";\n public static final String INPUT_STREAM_SHOULD_BE_MARKABLE = \"Input stream must be markable.\";\n public static final String INVALID_ACCOUNT_NAME = \"Invalid account name.\";\n public static final String INVALID_ACL_ACCESS_TYPE = \"Invalid acl public access type returned '%s'. Expected blob or container.\";\n public static final String INVALID_BLOB_TYPE = \"Incorrect Blob type, please use the correct Blob type to access a blob on the server. Expected %s, actual %s.\";\n public static final String INVALID_BLOCK_ID = \"Invalid blockID, blockID must be a valid Base64 String.\";\n public static final String INVALID_BLOCK_SIZE = \"Append block data should not exceed the maximum blob size condition value.\";\n public static final String INVALID_CONDITIONAL_HEADERS = \"The conditionals specified for this operation did not match server.\";\n public static final String INVALID_CONNECTION_STRING = \"Invalid connection string.\";\n public static final String INVALID_CONNECTION_STRING_DEV_STORE_NOT_TRUE = \"Invalid connection string, the UseDevelopmentStorage key must always be paired with 'true'. Remove the flag entirely otherwise.\";\n public static final String INVALID_CONTENT_LENGTH = \"ContentLength must be set to -1 or positive Long value.\";\n public static final String INVALID_CONTENT_TYPE = \"An incorrect Content-Type was returned from the server.\";\n public static final String INVALID_CORS_RULE = \"A CORS rule must contain at least one allowed origin and allowed method, and MaxAgeInSeconds cannot have a value less than zero.\";\n public static final String INVALID_DATE_STRING = \"Invalid Date String: %s.\";\n public static final String INVALID_EDMTYPE_VALUE = \"Invalid value '%s' for EdmType.\";\n public static final String INVALID_FILE_LENGTH = \"File length must be greater than or equal to 0 bytes.\";\n public static final String INVALID_GEO_REPLICATION_STATUS = \"Null or Invalid geo-replication status in response: %s.\";\n public static final String INVALID_IP_ADDRESS = \"Error when parsing IPv4 address: IP address '%s' is invalid.\";\n public static final String INVALID_KEY = \"Storage Key is not a valid base64 encoded string.\";\n public static final String INVALID_LISTING_DETAILS = \"Invalid blob listing details specified.\";\n public static final String INVALID_LOGGING_LEVEL = \"Invalid logging operations specified.\";\n public static final String INVALID_MAX_WRITE_SIZE = \"Max write size is 4MB. Please specify a smaller range.\";\n public static final String INVALID_MESSAGE_LENGTH = \"The message size cannot be larger than %s bytes.\";\n public static final String INVALID_MIME_RESPONSE = \"Invalid MIME response received.\";\n public static final String INVALID_NUMBER_OF_BYTES_IN_THE_BUFFER = \"Page data must be a multiple of 512 bytes. Buffer currently contains %d bytes.\";\n public static final String INVALID_OPERATION_FOR_A_SNAPSHOT = \"Cannot perform this operation on a blob representing a snapshot.\";\n public static final String INVALID_OPERATION_FOR_A_SHARE_SNAPSHOT = \"Cannot perform this operation on a share representing a snapshot.\";\n public static final String INVALID_PAGE_BLOB_LENGTH = \"Page blob length must be multiple of 512.\";\n public static final String INVALID_PAGE_START_OFFSET = \"Page start offset must be multiple of 512.\";\n public static final String INVALID_RANGE_CONTENT_MD5_HEADER = \"Cannot specify x-ms-range-get-content-md5 header on ranges larger than 4 MB. Either use a BlobReadStream via openRead, or disable TransactionalMD5 via the BlobRequestOptions.\";\n public static final String INVALID_RESOURCE_NAME = \"Invalid %s name. Check MSDN for more information about valid naming.\";\n public static final String INVALID_RESOURCE_NAME_LENGTH = \"Invalid %s name length. The name must be between %s and %s characters long.\";\n public static final String INVALID_RESOURCE_RESERVED_NAME = \"Invalid %s name. This name is reserved.\";\n public static final String INVALID_RESPONSE_RECEIVED = \"The response received is invalid or improperly formatted.\";\n public static final String INVALID_STORAGE_PROTOCOL_VERSION = \"Storage protocol version prior to 2009-09-19 do not support shared key authentication.\";\n public static final String INVALID_STORAGE_SERVICE = \"Invalid storage service specified.\";\n public static final String INVALID_STREAM_LENGTH = \"Invalid stream length; stream must be between 0 and %s MB in length.\";\n public static final String ITERATOR_EMPTY = \"There are no more elements in this enumeration.\";\n public static final String LEASE_CONDITION_ON_SOURCE = \"A lease condition cannot be specified on the source of a copy.\";\n public static final String LOG_STREAM_END_ERROR = \"Error parsing log record: unexpected end of stream.\";\n public static final String LOG_STREAM_DELIMITER_ERROR = \"Error parsing log record: unexpected delimiter encountered.\";\n public static final String LOG_STREAM_QUOTE_ERROR = \"Error parsing log record: unexpected quote character encountered.\";\n public static final String LOG_VERSION_UNSUPPORTED = \"A storage log version of %s is unsupported.\";\n public static final String MARK_EXPIRED = \"Stream mark expired.\";\n public static final String MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION = \"The client could not finish the operation within specified maximum execution timeout.\";\n public static final String METADATA_KEY_INVALID = \"The key for one of the metadata key-value pairs is null, empty, or whitespace.\";\n public static final String METADATA_VALUE_INVALID = \"The value for one of the metadata key-value pairs is null, empty, or whitespace.\";\n public static final String MISSING_CREDENTIALS = \"No credentials provided.\";\n public static final String MISSING_MANDATORY_DATE_HEADER = \"Canonicalization did not find a non-empty x-ms-date header in the request. Please use a request with a valid x-ms-date header in RFC 123 format.\";\n public static final String MISSING_MANDATORY_PARAMETER_FOR_SAS = \"Missing mandatory parameters for valid Shared Access Signature.\";\n public static final String MISSING_MD5 = \"ContentMD5 header is missing in the response.\";\n public static final String MISSING_NULLARY_CONSTRUCTOR = \"Class type must contain contain a nullary constructor.\";\n public static final String MULTIPLE_CREDENTIALS_PROVIDED = \"Cannot provide credentials as part of the address and as constructor parameter. Either pass in the address or use a different constructor.\";\n public static final String NETWORK_ON_MAIN_THREAD_EXCEPTION = \"Network operations may not be performed on the main thread.\";\n public static final String OPS_IN_BATCH_MUST_HAVE_SAME_PARTITION_KEY = \"All entities in a given batch must have the same partition key.\";\n public static final String PARAMETER_NOT_IN_RANGE = \"The value of the parameter '%s' should be between %s and %s.\";\n public static final String PARAMETER_SHOULD_BE_GREATER = \"The value of the parameter '%s' should be greater than %s.\";\n public static final String PARAMETER_SHOULD_BE_GREATER_OR_EQUAL = \"The value of the parameter '%s' should be greater than or equal to %s.\";\n public static final String PARTITIONKEY_MISSING_FOR_DELETE = \"Delete requires a partition key.\";\n public static final String PARTITIONKEY_MISSING_FOR_MERGE = \"Merge requires a partition key.\";\n public static final String PARTITIONKEY_MISSING_FOR_UPDATE = \"Replace requires a partition key.\";\n public static final String PARTITIONKEY_MISSING_FOR_INSERT = \"Insert requires a partition key.\";\n public static final String PATH_STYLE_URI_MISSING_ACCOUNT_INFORMATION = \"Missing account name information inside path style URI. Path style URIs should be of the form http://<IPAddress:Port>/<accountName>\";\n public static final String PRIMARY_ONLY_COMMAND = \"This operation can only be executed against the primary storage location.\";\n public static final String PROPERTY_CANNOT_BE_SERIALIZED_AS_GIVEN_EDMTYPE = \"Property %s with Edm Type %s cannot be de-serialized.\";\n public static final String PRECONDITION_FAILURE_IGNORED = \"Pre-condition failure on a retry is being ignored since the request should have succeeded in the first attempt.\";\n public static final String QUERY_PARAMETER_NULL_OR_EMPTY = \"Cannot encode a query parameter with a null or empty key.\";\n public static final String QUERY_REQUIRES_VALID_CLASSTYPE_OR_RESOLVER = \"Query requires a valid class type or resolver.\";\n public static final String QUEUE = \"queue\";\n public static final String QUEUE_ENDPOINT_NOT_CONFIGURED = \"No queue endpoint configured.\";\n public static final String RELATIVE_ADDRESS_NOT_PERMITTED = \"Address %s is a relative address. Only absolute addresses are permitted.\";\n public static final String RESOURCE_NAME_EMPTY = \"Invalid %s name. The name may not be null, empty, or whitespace only.\";\n public static final String RESPONSE_RECEIVED_IS_INVALID = \"The response received is invalid or improperly formatted.\";\n public static final String RETRIEVE_MUST_BE_ONLY_OPERATION_IN_BATCH = \"A batch transaction with a retrieve operation cannot contain any other operations.\";\n public static final String ROWKEY_MISSING_FOR_DELETE = \"Delete requires a row key.\";\n public static final String ROWKEY_MISSING_FOR_MERGE = \"Merge requires a row key.\";\n public static final String ROWKEY_MISSING_FOR_UPDATE = \"Replace requires a row key.\";\n public static final String ROWKEY_MISSING_FOR_INSERT = \"Insert requires a row key.\";\n public static final String SCHEME_NULL_OR_EMPTY = \"The protocol to use is null. Please specify whether to use http or https.\";\n public static final String SECONDARY_ONLY_COMMAND = \"This operation can only be executed against the secondary storage location.\";\n public static final String SHARE = \"share\";\n public static final String SNAPSHOT_LISTING_ERROR = \"Listing snapshots is only supported in flat mode (no delimiter). Consider setting useFlatBlobListing to true.\";\n public static final String SNAPSHOT_QUERY_OPTION_ALREADY_DEFINED = \"Snapshot query parameter is already defined in the blob URI. Either pass in a snapshotTime parameter or use a full URL with a snapshot query parameter.\";\n public static final String STORAGE_CREDENTIALS_NULL_OR_ANONYMOUS = \"StorageCredentials cannot be null or anonymous for this service.\";\n public static final String STORAGE_CLIENT_OR_SAS_REQUIRED = \"Either a SAS token or a service client must be specified.\";\n public static final String STORAGE_URI_MISSING_LOCATION = \"The URI for the target storage location is not specified. Please consider changing the request's location mode.\";\n public static final String STORAGE_URI_MUST_MATCH = \"Primary and secondary location URIs in a StorageUri must point to the same resource.\";\n public static final String STORAGE_URI_NOT_NULL = \"Primary and secondary location URIs in a StorageUri must not both be null.\";\n public static final String STOREAS_DIFFERENT_FOR_GETTER_AND_SETTER = \"StoreAs Annotation found for both getter and setter for property %s with unequal values.\";\n public static final String STOREAS_USED_ON_EMPTY_PROPERTY = \"StoreAs Annotation found for property %s with empty value.\";\n public static final String STREAM_CLOSED = \"Stream is already closed.\";\n public static final String STREAM_LENGTH_GREATER_THAN_4MB = \"Invalid stream length, length must be less than or equal to 4 MB in size.\";\n public static final String STREAM_LENGTH_NEGATIVE = \"Invalid stream length, specify -1 for unknown length stream, or a positive number of bytes.\";\n public static final String STRING_NOT_VALID = \"The String is not a valid Base64-encoded string.\";\n public static final String TABLE = \"table\";\n public static final String TABLE_ENDPOINT_NOT_CONFIGURED = \"No table endpoint configured.\";\n public static final String TABLE_OBJECT_RELATIVE_URIS_NOT_SUPPORTED = \"Table Object relative URIs not supported.\";\n public static final String TAKE_COUNT_ZERO_OR_NEGATIVE = \"Take count must be positive and greater than 0.\";\n public static final String TOO_MANY_PATH_SEGMENTS = \"The count of URL path segments (strings between '/' characters) as part of the blob name cannot exceed 254.\";\n public static final String TOO_MANY_SHARED_ACCESS_POLICY_IDENTIFIERS = \"Too many %d shared access policy identifiers provided. Server does not support setting more than %d on a single container, queue, or table.\";\n public static final String TOO_MANY_SHARED_ACCESS_POLICY_IDS = \"Too many %d shared access policy identifiers provided. Server does not support setting more than %d on a single container.\";\n public static final String TYPE_NOT_SUPPORTED = \"Type %s is not supported.\";\n public static final String UNEXPECTED_CONTINUATION_TYPE = \"The continuation type passed in is unexpected. Please verify that the correct continuation type is passed in. Expected {%s}, found {%s}.\";\n public static final String UNEXPECTED_FIELD_NAME = \"Unexpected field name. Expected: '%s'. Actual: '%s'.\";\n public static final String UNEXPECTED_STATUS_CODE_RECEIVED = \"Unexpected http status code received.\";\n public static final String UNEXPECTED_STREAM_READ_ERROR = \"Unexpected error. Stream returned unexpected number of bytes.\";\n public static final String UNKNOWN_TABLE_OPERATION = \"Unknown table operation.\";\n}", "public class SharedAccessSignatureHelper {\n /**\n * Get the signature hash embedded inside the Shared Access Signature for a {@link CloudStorageAccount}.\n * \n * @param policy\n * The shared access policy to hash.\n * @param ipRange\n * An optional range of IP addresses.\n * @param protocols\n * An optional restriction of allowed protocols.\n * @param signature\n * The signature to use.\n * \n * @return The finished query builder\n * @throws InvalidKeyException\n * @throws StorageException\n */\n public static UriQueryBuilder generateSharedAccessSignatureForAccount(\n final SharedAccessAccountPolicy policy, final String signature)\n throws StorageException {\n \n Utility.assertNotNull(\"policy\", policy);\n \n Utility.assertNotNull(\"signature\", signature);\n\n String permissions = null;\n Date startTime = null;\n Date expiryTime = null;\n IPRange ipRange = null;\n SharedAccessProtocols protocols = null;\n String services = null;\n String resourceTypes = null;\n if (policy != null) {\n permissions = policy.permissionsToString();\n startTime = policy.getSharedAccessStartTime();\n expiryTime = policy.getSharedAccessExpiryTime();\n ipRange = policy.getRange();\n protocols = policy.getProtocols();\n services = policy.servicesToString();\n resourceTypes = policy.resourceTypesToString();\n }\n\n final UriQueryBuilder builder = new UriQueryBuilder();\n\n builder.add(Constants.QueryConstants.SIGNED_VERSION, Constants.HeaderConstants.TARGET_STORAGE_VERSION);\n \n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_SERVICE, services);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_RESOURCE_TYPE, resourceTypes);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_PERMISSIONS, permissions);\n\n final String startString = Utility.getUTCTimeOrEmpty(startTime);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_START, startString);\n\n final String stopString = Utility.getUTCTimeOrEmpty(expiryTime);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_EXPIRY, stopString);\n\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_RESOURCE, resourceTypes);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_IP, ipRange != null ? ipRange.toString() : null);\n addIfNotNullOrEmpty(\n builder, Constants.QueryConstants.SIGNED_PROTOCOLS, protocols != null ? protocols.toString() : null);\n\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNATURE, signature);\n\n return builder;\n }\n \n /**\n * Get the complete query builder for creating the Shared Access Signature query.\n * \n * @param policy\n * The shared access policy for the shared access signature.\n * @param headers\n * The optional header values to set for a blob or file accessed with this shared access signature.\n * @param groupPolicyIdentifier\n * An optional identifier for the policy.\n * @param resourceType\n * Either \"b\" for blobs, \"c\" for containers, \"f\" for files, or \"s\" for shares.\n * @param ipRange\n * The range of IP addresses for the shared access signature.\n * @param protocols\n * The Internet protocols for the shared access signature.\n * @param signature\n * The signature to use.\n * \n * @return The finished query builder\n * @throws IllegalArgumentException\n * @throws StorageException\n */\n public static UriQueryBuilder generateSharedAccessSignatureForBlobAndFile(\n final SharedAccessPolicy policy, final SharedAccessHeaders headers, final String groupPolicyIdentifier,\n final String resourceType, final IPRange ipRange, final SharedAccessProtocols protocols, final String signature)\n throws StorageException {\n \n Utility.assertNotNullOrEmpty(\"resourceType\", resourceType);\n\n return generateSharedAccessSignatureHelper(policy, null /* startPartitionKey */, null /* startRowKey */,\n null /* endPartitionKey */, null /* endRowKey */, groupPolicyIdentifier, resourceType, ipRange,\n protocols, null /* tableName */, signature, headers);\n }\n\n /**\n * Get the complete query builder for creating the Shared Access Signature query.\n * \n * @param policy\n * The shared access policy for the shared access signature.\n * @param groupPolicyIdentifier\n * An optional identifier for the policy.\n * @param ipRange\n * The range of IP addresses for the shared access signature.\n * @param protocols\n * The Internet protocols for the shared access signature.\n * @param signature\n * The signature to use.\n * \n * @return The finished query builder\n * @throws IllegalArgumentException\n * @throws StorageException\n */\n public static UriQueryBuilder generateSharedAccessSignatureForQueue(\n final SharedAccessQueuePolicy policy, final String groupPolicyIdentifier, final IPRange ipRange,\n final SharedAccessProtocols protocols, final String signature)\n throws StorageException {\n\n return generateSharedAccessSignatureHelper(policy, null /* startPartitionKey */, null /* startRowKey */,\n null /* endPartitionKey */, null /* endRowKey */, groupPolicyIdentifier, null /* resourceType */,\n ipRange, protocols, null /* tableName */, signature, null /* headers */);\n }\n\n /**\n * Get the complete query builder for creating the Shared Access Signature query.\n * \n * @param policy\n * The shared access policy for the shared access signature.\n * @param startPartitionKey\n * An optional restriction of the beginning of the range of partition keys to include.\n * @param startRowKey\n * An optional restriction of the beginning of the range of row keys to include.\n * @param endPartitionKey\n * An optional restriction of the end of the range of partition keys to include.\n * @param endRowKey\n * An optional restriction of the end of the range of row keys to include.\n * @param accessPolicyIdentifier\n * An optional identifier for the policy.\n * @param ipRange\n * The range of IP addresses for the shared access signature.\n * @param protocols\n * The Internet protocols for the shared access signature.\n * @param tableName\n * The table name.\n * @param signature\n * The signature to use.\n * \n * @return The finished query builder\n * @throws IllegalArgumentException\n * @throws StorageException\n */\n public static UriQueryBuilder generateSharedAccessSignatureForTable(\n final SharedAccessTablePolicy policy, final String startPartitionKey, final String startRowKey,\n final String endPartitionKey, final String endRowKey, final String accessPolicyIdentifier,\n final IPRange ipRange, final SharedAccessProtocols protocols, final String tableName, final String signature)\n throws StorageException {\n \n Utility.assertNotNull(\"tableName\", tableName);\n return generateSharedAccessSignatureHelper(\n policy, startPartitionKey, startRowKey, endPartitionKey, endRowKey, accessPolicyIdentifier,\n null /* resourceType */, ipRange, protocols, tableName, signature, null /* headers */);\n }\n \n /**\n * Get the signature hash embedded inside the Shared Access Signature for a {@link CloudStorageAccount}.\n * \n * @param accountName\n * The name of the account to use for the SAS.\n * @param policy\n * The shared access policy to hash.\n * @param ipRange\n * An optional range of IP addresses.\n * @param protocols\n * An optional restriction of allowed protocols.\n * @param creds\n * The {@link StorageCredentials} associated with the object.\n * \n * @return The signature hash embedded inside the Shared Access Signature.\n * @throws InvalidKeyException\n * @throws StorageException\n */\n public static String generateSharedAccessSignatureHashForAccount(\n final String accountName, final SharedAccessAccountPolicy policy, final StorageCredentials creds)\n throws InvalidKeyException, StorageException {\n Utility.assertNotNullOrEmpty(\"resource\", accountName);\n Utility.assertNotNull(\"credentials\", creds);\n\n String permissions = null;\n Date startTime = null;\n Date expiryTime = null;\n IPRange ipRange = null;\n SharedAccessProtocols protocols = null;\n String services = null;\n String resourceTypes = null;\n \n if (policy != null) {\n permissions = policy.permissionsToString();\n startTime = policy.getSharedAccessStartTime();\n expiryTime = policy.getSharedAccessExpiryTime();\n ipRange = policy.getRange();\n protocols = policy.getProtocols();\n services = policy.servicesToString();\n resourceTypes = policy.resourceTypesToString();\n }\n \n \n String stringToSign = String.format(\"%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n\",\n accountName, permissions == null ? Constants.EMPTY_STRING : permissions, services, resourceTypes,\n Utility.getUTCTimeOrEmpty(startTime), Utility.getUTCTimeOrEmpty(expiryTime),\n ipRange == null ? Constants.EMPTY_STRING : ipRange.toString(),\n protocols == null ? Constants.EMPTY_STRING : protocols.toString(),\n Constants.HeaderConstants.TARGET_STORAGE_VERSION);\n\n return generateSharedAccessSignatureHashHelper(stringToSign, creds);\n }\n\n /**\n * Get the signature hash embedded inside the Shared Access Signature for the blob or file service.\n * \n * @param policy\n * The shared access policy to hash.\n * @param headers\n * The optional header values to set for a blob or file accessed with this shared access signature.\n * @param accessPolicyIdentifier\n * An optional identifier for the policy.\n * @param resourceName\n * The resource name.\n * @param ipRange\n * The range of IP addresses to hash.\n * @param protocols\n * The Internet protocols to hash.\n * @param client\n * The ServiceClient associated with the object.\n * \n * @return The signature hash embedded inside the Shared Access Signature.\n * @throws InvalidKeyException\n * @throws StorageException\n */\n public static String generateSharedAccessSignatureHashForBlobAndFile(final SharedAccessPolicy policy,\n SharedAccessHeaders headers, final String accessPolicyIdentifier, final String resourceName,\n final IPRange ipRange, final SharedAccessProtocols protocols, final ServiceClient client)\n throws InvalidKeyException, StorageException {\n \n String stringToSign = generateSharedAccessSignatureStringToSign(\n policy, resourceName, ipRange, protocols, accessPolicyIdentifier);\n\n String cacheControl = null;\n String contentDisposition = null;\n String contentEncoding = null;\n String contentLanguage = null;\n String contentType = null;\n if (headers != null) {\n cacheControl = headers.getCacheControl();\n contentDisposition = headers.getContentDisposition();\n contentEncoding = headers.getContentEncoding();\n contentLanguage = headers.getContentLanguage();\n contentType = headers.getContentType();\n }\n \n stringToSign = String.format(\"%s\\n%s\\n%s\\n%s\\n%s\\n%s\", stringToSign,\n cacheControl == null ? Constants.EMPTY_STRING : cacheControl,\n contentDisposition == null ? Constants.EMPTY_STRING : contentDisposition,\n contentEncoding == null ? Constants.EMPTY_STRING : contentEncoding,\n contentLanguage == null ? Constants.EMPTY_STRING : contentLanguage,\n contentType == null ? Constants.EMPTY_STRING : contentType);\n \n return generateSharedAccessSignatureHashHelper(stringToSign, client.getCredentials());\n }\n\n /**\n * Get the signature hash embedded inside the Shared Access Signature for queue service.\n * \n * @param policy\n * The shared access policy to hash.\n * @param accessPolicyIdentifier\n * An optional identifier for the policy.\n * @param resourceName\n * The resource name.\n * @param ipRange\n * The range of IP addresses to hash.\n * @param protocols\n * The Internet protocols to hash.\n * @param client\n * The ServiceClient associated with the object.\n * \n * @return The signature hash embedded inside the Shared Access Signature.\n * @throws InvalidKeyException\n * @throws StorageException\n */\n\n public static String generateSharedAccessSignatureHashForQueue(\n final SharedAccessQueuePolicy policy, final String accessPolicyIdentifier, final String resourceName,\n final IPRange ipRange, final SharedAccessProtocols protocols, final ServiceClient client)\n throws InvalidKeyException, StorageException {\n \n final String stringToSign = generateSharedAccessSignatureStringToSign(\n policy, resourceName, ipRange, protocols, accessPolicyIdentifier);\n \n return generateSharedAccessSignatureHashHelper(stringToSign, client.getCredentials());\n }\n\n /**\n * Get the signature hash embedded inside the Shared Access Signature for the table service.\n * \n * @param policy\n * The shared access policy to hash.\n * @param accessPolicyIdentifier\n * An optional identifier for the policy.\n * @param resourceName\n * The resource name.\n * @param ipRange\n * The range of IP addresses to hash.\n * @param protocols\n * The Internet protocols to hash.\n * @param startPartitionKey\n * An optional restriction of the beginning of the range of partition keys to hash.\n * @param startRowKey\n * An optional restriction of the beginning of the range of row keys to hash.\n * @param endPartitionKey\n * An optional restriction of the end of the range of partition keys to hash.\n * @param endRowKey\n * An optional restriction of the end of the range of row keys to hash.\n * @param client\n * The ServiceClient associated with the object.\n * \n * @return The signature hash embedded inside the Shared Access Signature.\n * @throws InvalidKeyException\n * @throws StorageException\n */\n public static String generateSharedAccessSignatureHashForTable(\n final SharedAccessTablePolicy policy, final String accessPolicyIdentifier, final String resourceName,\n final IPRange ipRange, final SharedAccessProtocols protocols, final String startPartitionKey,\n final String startRowKey, final String endPartitionKey, final String endRowKey, final ServiceClient client)\n throws InvalidKeyException, StorageException {\n\n String stringToSign = generateSharedAccessSignatureStringToSign(\n policy, resourceName, ipRange, protocols, accessPolicyIdentifier);\n \n stringToSign = String.format(\"%s\\n%s\\n%s\\n%s\\n%s\", stringToSign,\n startPartitionKey == null ? Constants.EMPTY_STRING : startPartitionKey,\n startRowKey == null ? Constants.EMPTY_STRING : startRowKey,\n endPartitionKey == null ? Constants.EMPTY_STRING : endPartitionKey,\n endRowKey == null ? Constants.EMPTY_STRING : endRowKey);\n \n return generateSharedAccessSignatureHashHelper(stringToSign, client.getCredentials());\n }\n\n /**\n * Parses the query parameters and populates a StorageCredentialsSharedAccessSignature object if one is present.\n * \n * @param completeUri\n * A {@link StorageUri} object which represents the complete Uri.\n * \n * @return The StorageCredentialsSharedAccessSignature if one is present, otherwise null.\n * @throws StorageException\n * An exception representing any error which occurred during the operation.\n */\n public static StorageCredentialsSharedAccessSignature parseQuery(final StorageUri completeUri) throws StorageException {\n final HashMap<String, String[]> queryParameters = PathUtility.parseQueryString(completeUri.getQuery());\n return parseQuery(queryParameters);\n }\n\n /**\n * Parses the query parameters and populates a StorageCredentialsSharedAccessSignature object if one is present.\n * \n * @param queryParams\n * The parameters to parse.\n * \n * @return The StorageCredentialsSharedAccessSignature if one is present, otherwise null.\n * @throws StorageException\n * An exception representing any error which occurred during the operation.\n */\n public static StorageCredentialsSharedAccessSignature parseQuery(final HashMap<String, String[]> queryParams)\n throws StorageException {\n \n boolean sasParameterFound = false;\n List<String> removeList = new ArrayList<String>();\n for (final Entry<String, String[]> entry : queryParams.entrySet()) {\n final String lowerKey = entry.getKey().toLowerCase(Utility.LOCALE_US);\n\n if (lowerKey.equals(Constants.QueryConstants.SIGNATURE)) {\n sasParameterFound = true;\n } else if (lowerKey.equals(Constants.QueryConstants.COMPONENT)) {\n removeList.add(entry.getKey());\n } else if (lowerKey.equals(Constants.QueryConstants.RESOURCETYPE)) {\n removeList.add(entry.getKey());\n } else if (lowerKey.equals(Constants.QueryConstants.SNAPSHOT)) {\n removeList.add(entry.getKey());\n } else if (lowerKey.equals(Constants.QueryConstants.API_VERSION)) {\n removeList.add(entry.getKey());\n } \n }\n \n for (String removeParam : removeList) {\n queryParams.remove(removeParam);\n }\n\n if (sasParameterFound) {\n final UriQueryBuilder builder = new UriQueryBuilder();\n \n StringBuilder values = new StringBuilder();\n for (final Entry<String, String[]> entry : queryParams.entrySet()) {\n values.setLength(0);\n for (int i = 0; i < entry.getValue().length; i++) {\n values.append(entry.getValue()[i]);\n values.append(',');\n }\n values.deleteCharAt(values.length() - 1);\n \n addIfNotNullOrEmpty(builder, entry.getKey().toLowerCase(), values.toString());\n }\n\n return new StorageCredentialsSharedAccessSignature(builder.toString());\n }\n\n return null;\n }\n\n /**\n * Helper to add a name/value pair to a <code>UriQueryBuilder</code> if the value is not null or empty.\n * \n * @param builder\n * The builder to add to.\n * @param name\n * The name to add.\n * @param val\n * The value to add if not null or empty.\n * \n * @throws StorageException\n * An exception representing any error which occurred during the operation.\n */\n private static void addIfNotNullOrEmpty(UriQueryBuilder builder, String name, String val) throws StorageException {\n if (!Utility.isNullOrEmpty(val)) {\n builder.add(name, val);\n }\n }\n\n /**\n * Get the complete query builder for creating the Shared Access Signature query.\n * \n * @param policy\n * A {@link SharedAccessPolicy} containing the permissions for the SAS.\n * @param startPartitionKey\n * The start partition key for a shared access signature URI.\n * @param startRowKey\n * The start row key for a shared access signature URI.\n * @param endPartitionKey\n * The end partition key for a shared access signature URI.\n * @param endRowKey\n * The end row key for a shared access signature URI.\n * @param accessPolicyIdentifier\n * An optional identifier for the policy.\n * @param resourceType\n * The resource type for a shared access signature URI.\n * @param ipRange\n * The range of IP addresses for the shared access signature.\n * @param protocols\n * The Internet protocols for the shared access signature.\n * @param tableName\n * The table name.\n * @param signature\n * The signature hash.\n * @param headers\n * Optional blob or file headers.\n * \n * @return The finished query builder.\n * @throws StorageException\n * An exception representing any error which occurred during the operation.\n */\n private static UriQueryBuilder generateSharedAccessSignatureHelper(\n final SharedAccessPolicy policy, final String startPartitionKey, final String startRowKey,\n final String endPartitionKey, final String endRowKey, final String accessPolicyIdentifier,\n final String resourceType, final IPRange ipRange, final SharedAccessProtocols protocols,\n final String tableName, final String signature, final SharedAccessHeaders headers)\n throws StorageException {\n \n Utility.assertNotNull(\"signature\", signature);\n\n String permissions = null;\n Date startTime = null;\n Date expiryTime = null;\n if (policy != null) {\n permissions = policy.permissionsToString();\n startTime = policy.getSharedAccessStartTime();\n expiryTime = policy.getSharedAccessExpiryTime();\n }\n\n final UriQueryBuilder builder = new UriQueryBuilder();\n\n builder.add(Constants.QueryConstants.SIGNED_VERSION, Constants.HeaderConstants.TARGET_STORAGE_VERSION);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_PERMISSIONS, permissions);\n\n final String startString = Utility.getUTCTimeOrEmpty(startTime);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_START, startString);\n\n final String stopString = Utility.getUTCTimeOrEmpty(expiryTime);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_EXPIRY, stopString);\n\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.START_PARTITION_KEY, startPartitionKey);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.START_ROW_KEY, startRowKey);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.END_PARTITION_KEY, endPartitionKey);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.END_ROW_KEY, endRowKey);\n\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_IDENTIFIER, accessPolicyIdentifier);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_RESOURCE, resourceType);\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNED_IP, ipRange != null ? ipRange.toString() : null);\n addIfNotNullOrEmpty(\n builder, Constants.QueryConstants.SIGNED_PROTOCOLS, protocols != null ? protocols.toString() : null);\n\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SAS_TABLE_NAME, tableName);\n\n if (headers != null) {\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.CACHE_CONTROL, headers.getCacheControl());\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.CONTENT_TYPE, headers.getContentType());\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.CONTENT_ENCODING, headers.getContentEncoding());\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.CONTENT_LANGUAGE, headers.getContentLanguage());\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.CONTENT_DISPOSITION, headers.getContentDisposition());\n }\n\n addIfNotNullOrEmpty(builder, Constants.QueryConstants.SIGNATURE, signature);\n\n return builder;\n }\n\n /**\n * Get the signature hash embedded inside the Shared Access Signature.\n *\n * @param stringToSign\n * The string to decode and hash\n * @param creds\n * Reference to the {@link StorageCredentials.}.\n * \n * @return The signature hash embedded inside the Shared Access Signature.\n * \n * @throws InvalidKeyException\n * @throws StorageException\n */\n private static String generateSharedAccessSignatureHashHelper(String stringToSign, final StorageCredentials creds)\n throws StorageException, InvalidKeyException {\n \n Utility.assertNotNull(\"credentials\", creds);\n \n Logger.debug(null, LogConstants.SIGNING, stringToSign);\n\n stringToSign = Utility.safeDecode(stringToSign);\n final String signature = StorageCredentialsHelper.computeHmac256(creds, stringToSign);\n\n Logger.verbose(null, LogConstants.SIGNING, stringToSign);\n \n return signature;\n }\n\n /**\n * Get the signature hash embedded inside the Shared Access Signature.\n * \n * @param policy\n * A {@link SharedAccessPolicy} containing the permissions for the SAS.\n * @param resource\n * The canonical resource (or resource type) string, unescaped.\n * @param ipRange\n * The range of IP addresses to hash.\n * @param protocols\n * The Internet protocols to hash.\n * @param headers\n * The optional header values to set for a blob or file accessed with this shared access signature.\n * @param accessPolicyIdentifier\n * An optional identifier for the policy.\n * \n * @return The signature hash embedded inside the Shared Access Signature.\n * \n * @throws InvalidKeyException\n * @throws StorageException\n */\n private static String generateSharedAccessSignatureStringToSign(\n final SharedAccessPolicy policy, final String resource, final IPRange ipRange,\n final SharedAccessProtocols protocols, final String accessPolicyIdentifier)\n throws InvalidKeyException, StorageException {\n \n Utility.assertNotNullOrEmpty(\"resource\", resource);\n\n String permissions = null;\n Date startTime = null;\n Date expiryTime = null;\n \n if (policy != null) {\n permissions = policy.permissionsToString();\n startTime = policy.getSharedAccessStartTime();\n expiryTime = policy.getSharedAccessExpiryTime();\n }\n \n String stringToSign = String.format(\"%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\",\n permissions == null ? Constants.EMPTY_STRING : permissions,\n Utility.getUTCTimeOrEmpty(startTime), Utility.getUTCTimeOrEmpty(expiryTime), resource,\n accessPolicyIdentifier == null ? Constants.EMPTY_STRING : accessPolicyIdentifier,\n ipRange == null ? Constants.EMPTY_STRING : ipRange.toString(),\n protocols == null ? Constants.EMPTY_STRING : protocols.toString(),\n Constants.HeaderConstants.TARGET_STORAGE_VERSION);\n\n return stringToSign;\n }\n \n /**\n * Private Default Ctor.\n */\n private SharedAccessSignatureHelper() {\n // No op\n }\n}", "public final class StorageCredentialsHelper {\n\n /**\n * RESERVED, for internal use only. Gets a value indicating whether a\n * request can be signed under the Shared Key authentication scheme using\n * the specified credentials.\n \n * @return <Code>true</Code> if a request can be signed with these\n * credentials; otherwise, <Code>false</Code>\n */\n public static boolean canCredentialsSignRequest(final StorageCredentials creds) {\n return creds.getClass().equals(StorageCredentialsAccountAndKey.class);\n }\n\n /**\n * RESERVED, for internal use only. Gets a value indicating whether a\n * client can be generated under the Shared Key or Shared Access Signature\n * authentication schemes using the specified credentials.\n * @return <Code>true</Code> if a client can be generated with these\n * credentials; otherwise, <Code>false</Code>\n */\n public static boolean canCredentialsGenerateClient(final StorageCredentials creds) {\n return canCredentialsSignRequest(creds) || creds.getClass().equals(StorageCredentialsSharedAccessSignature.class);\n }\n\n /**\n * Computes a signature for the specified string using the HMAC-SHA256 algorithm.\n * \n * @param value\n * The UTF-8-encoded string to sign.\n * \n * @return A <code>String</code> that contains the HMAC-SHA256-encoded signature.\n * \n * @throws InvalidKeyException\n * If the key is not a valid Base64-encoded string.\n */\n public static synchronized String computeHmac256(final StorageCredentials creds, final String value) throws InvalidKeyException {\n if (creds.getClass().equals(StorageCredentialsAccountAndKey.class)) {\n byte[] utf8Bytes = null;\n try {\n utf8Bytes = value.getBytes(Constants.UTF8_CHARSET);\n }\n catch (final UnsupportedEncodingException e) {\n throw new IllegalArgumentException(e);\n }\n return Base64.encode(((StorageCredentialsAccountAndKey) creds).getHmac256().doFinal(utf8Bytes));\n }\n else {\n return null;\n }\n }\n\n /**\n * Signs a request using the specified operation context under the Shared Key authentication scheme.\n * \n * @param request\n * An <code>HttpURLConnection</code> object that represents the request to sign.\n * @param contentLength\n * The length of the content written to the output stream. If unknown, specify -1.\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws InvalidKeyException\n * If the given key is invalid.\n * @throws StorageException\n * If a storage service error occurred.\n */\n public static void signBlobQueueAndFileRequest(final StorageCredentials creds,\n final java.net.HttpURLConnection request, final long contentLength, OperationContext opContext)\n throws InvalidKeyException, StorageException {\n \n if (creds.getClass().equals(StorageCredentialsAccountAndKey.class)) {\n opContext = opContext == null ? new OperationContext() : opContext;\n request.setRequestProperty(Constants.HeaderConstants.DATE, Utility.getGMTTime());\n final Canonicalizer canonicalizer = CanonicalizerFactory.getBlobQueueFileCanonicalizer(request);\n\n final String stringToSign = canonicalizer.canonicalize(request, creds.getAccountName(), contentLength);\n\n final String computedBase64Signature = StorageCredentialsHelper.computeHmac256(creds, stringToSign);\n\n Logger.debug(opContext, LogConstants.SIGNING, stringToSign);\n\n request.setRequestProperty(Constants.HeaderConstants.AUTHORIZATION,\n String.format(\"%s %s:%s\", \"SharedKey\", creds.getAccountName(), computedBase64Signature));\n }\n }\n \n /**\n * Signs a request using the specified operation context under the Shared Key authentication scheme.\n * \n * @param request\n * An <code>HttpURLConnection</code> object that represents the request to sign.\n * @param contentLength\n * The length of the content written to the output stream. If unknown, specify -1.\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * \n * @throws InvalidKeyException\n * If the given key is invalid.\n * @throws StorageException\n * If a storage service error occurred.\n */\n public static void signTableRequest(final StorageCredentials creds, final java.net.HttpURLConnection request,\n final long contentLength, OperationContext opContext) throws InvalidKeyException, StorageException {\n if (creds.getClass().equals(StorageCredentialsAccountAndKey.class)) {\n opContext = opContext == null ? new OperationContext() : opContext;\n request.setRequestProperty(Constants.HeaderConstants.DATE, Utility.getGMTTime());\n\n final Canonicalizer canonicalizer = CanonicalizerFactory.getTableCanonicalizer(request);\n\n final String stringToSign = canonicalizer.canonicalize(request, creds.getAccountName(), contentLength);\n\n final String computedBase64Signature = StorageCredentialsHelper.computeHmac256(creds, stringToSign);\n \n Logger.debug(opContext, LogConstants.SIGNING, stringToSign);\n\n request.setRequestProperty(Constants.HeaderConstants.AUTHORIZATION,\n String.format(\"%s %s:%s\", \"SharedKey\", creds.getAccountName(), computedBase64Signature));\n }\n }\n \n /**\n * A private default constructor. All methods of this class are static so no instances of it should ever be created.\n */\n private StorageCredentialsHelper() {\n //No op\n }\n}", "public final class Utility {\n\n /**\n * Stores a reference to the GMT time zone.\n */\n public static final TimeZone GMT_ZONE = TimeZone.getTimeZone(\"GMT\");\n\n /**\n * Stores a reference to the UTC time zone.\n */\n public static final TimeZone UTC_ZONE = TimeZone.getTimeZone(\"UTC\");\n\n /**\n * Stores a reference to the US locale.\n */\n public static final Locale LOCALE_US = Locale.US;\n\n /**\n * Stores a reference to the RFC1123 date/time pattern.\n */\n private static final String RFC1123_GMT_PATTERN = \"EEE, dd MMM yyyy HH:mm:ss 'GMT'\";\n\n /**\n * Stores a reference to the ISO8601 date/time pattern.\n */\n private static final String ISO8601_PATTERN_NO_SECONDS = \"yyyy-MM-dd'T'HH:mm'Z'\";\n\n /**\n * Stores a reference to the ISO8601 date/time pattern.\n */\n private static final String ISO8601_PATTERN = \"yyyy-MM-dd'T'HH:mm:ss'Z'\";\n\n /**\n * Stores a reference to the Java version of ISO8601_LONG date/time pattern. The full version cannot be used\n * because Java Dates have millisecond precision.\n */\n private static final String JAVA_ISO8601_PATTERN = \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\";\n \n /**\n * List of ports used for path style addressing.\n */\n private static final List<Integer> pathStylePorts = Arrays.asList(10000, 10001, 10002, 10003, 10004, 10100, 10101,\n 10102, 10103, 10104, 11000, 11001, 11002, 11003, 11004, 11100, 11101, 11102, 11103, 11104);\n\n /**\n * A factory to create SAXParser instances.\n */\n private static final SAXParserFactory factory = SAXParserFactory.newInstance();\n\n /**\n * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing.\n */\n private static final String MAX_PRECISION_PATTERN = \"yyyy-MM-dd'T'HH:mm:ss.SSS\";\n \n /**\n * The length of a datestring that matches the MAX_PRECISION_PATTERN.\n */\n private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll(\"'\", \"\").length();\n \n /**\n * \n * Determines the size of an input stream, and optionally calculates the MD5 hash for the stream.\n * \n * @param sourceStream\n * A <code>InputStream</code> object that represents the stream to measure.\n * @param writeLength\n * The number of bytes to read from the stream.\n * @param abandonLength\n * The number of bytes to read before the analysis is abandoned. Set this value to <code>-1</code> to\n * force the entire stream to be read. This parameter is provided to support upload thresholds.\n * @param rewindSourceStream\n * <code>true</code> if the stream should be rewound after it is read; otherwise, <code>false</code>.\n * @param calculateMD5\n * <code>true</code> if an MD5 hash will be calculated; otherwise, <code>false</code>.\n * \n * @return A {@link StreamMd5AndLength} object that contains the stream length, and optionally the MD5 hash.\n * \n * @throws IOException\n * If an I/O error occurs.\n * @throws StorageException\n * If a storage service error occurred.\n */\n public static StreamMd5AndLength analyzeStream(final InputStream sourceStream, long writeLength,\n long abandonLength, final boolean rewindSourceStream, final boolean calculateMD5) throws IOException,\n StorageException {\n if (abandonLength < 0) {\n abandonLength = Long.MAX_VALUE;\n }\n\n if (rewindSourceStream) {\n if (!sourceStream.markSupported()) {\n throw new IllegalArgumentException(SR.INPUT_STREAM_SHOULD_BE_MARKABLE);\n }\n\n sourceStream.mark(Constants.MAX_MARK_LENGTH);\n }\n\n MessageDigest digest = null;\n if (calculateMD5) {\n try {\n digest = MessageDigest.getInstance(\"MD5\");\n }\n catch (final NoSuchAlgorithmException e) {\n // This wont happen, throw fatal.\n throw Utility.generateNewUnexpectedStorageException(e);\n }\n }\n\n if (writeLength < 0) {\n writeLength = Long.MAX_VALUE;\n }\n\n final StreamMd5AndLength retVal = new StreamMd5AndLength();\n int count = -1;\n final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH];\n\n int nextCopy = (int) Math.min(retrievedBuff.length, writeLength - retVal.getLength());\n count = sourceStream.read(retrievedBuff, 0, nextCopy);\n\n while (nextCopy > 0 && count != -1) {\n if (calculateMD5) {\n digest.update(retrievedBuff, 0, count);\n }\n retVal.setLength(retVal.getLength() + count);\n\n if (retVal.getLength() > abandonLength) {\n // Abandon operation\n retVal.setLength(-1);\n retVal.setMd5(null);\n break;\n }\n\n nextCopy = (int) Math.min(retrievedBuff.length, writeLength - retVal.getLength());\n count = sourceStream.read(retrievedBuff, 0, nextCopy);\n }\n\n if (retVal.getLength() != -1 && calculateMD5) {\n retVal.setMd5(Base64.encode(digest.digest()));\n }\n\n if (retVal.getLength() != -1 && writeLength > 0) {\n retVal.setLength(Math.min(retVal.getLength(), writeLength));\n }\n\n if (rewindSourceStream) {\n sourceStream.reset();\n sourceStream.mark(Constants.MAX_MARK_LENGTH);\n }\n\n return retVal;\n }\n\n /**\n * Asserts a continuation token is of the specified type.\n * \n * @param continuationToken\n * A {@link ResultContinuation} object that represents the continuation token whose type is being\n * examined.\n * @param continuationType\n * A {@link ResultContinuationType} value that represents the continuation token type being asserted with\n * the specified continuation token.\n */\n public static void assertContinuationType(final ResultContinuation continuationToken,\n final ResultContinuationType continuationType) {\n if (continuationToken != null) {\n if (!(continuationToken.getContinuationType() == ResultContinuationType.NONE || continuationToken\n .getContinuationType() == continuationType)) {\n final String errorMessage = String.format(Utility.LOCALE_US, SR.UNEXPECTED_CONTINUATION_TYPE,\n continuationToken.getContinuationType(), continuationType);\n throw new IllegalArgumentException(errorMessage);\n }\n }\n }\n\n /**\n * Asserts that a value is not <code>null</code>.\n * \n * @param param\n * A <code>String</code> that represents the name of the parameter, which becomes the exception message\n * text if the <code>value</code> parameter is <code>null</code>.\n * @param value\n * An <code>Object</code> object that represents the value of the specified parameter. This is the value\n * being asserted as not <code>null</code>.\n */\n public static void assertNotNull(final String param, final Object value) {\n if (value == null) {\n throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.ARGUMENT_NULL_OR_EMPTY, param));\n }\n }\n\n /**\n * Asserts that the specified string is not <code>null</code> or empty.\n * \n * @param param\n * A <code>String</code> that represents the name of the parameter, which becomes the exception message\n * text if the <code>value</code> parameter is <code>null</code> or an empty string.\n * @param value\n * A <code>String</code> that represents the value of the specified parameter. This is the value being\n * asserted as not <code>null</code> and not an empty string.\n */\n public static void assertNotNullOrEmpty(final String param, final String value) {\n assertNotNull(param, value);\n\n if (Utility.isNullOrEmpty(value)) {\n throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.ARGUMENT_NULL_OR_EMPTY, param));\n }\n }\n\n /**\n * Asserts that the specified integer is in the valid range.\n * \n * @param param\n * A <code>String</code> that represents the name of the parameter, which becomes the exception message\n * text if the <code>value</code> parameter is out of bounds.\n * @param value\n * The value of the specified parameter.\n * @param min\n * The minimum value for the specified parameter.\n * @param max\n * The maximum value for the specified parameter.\n */\n public static void assertInBounds(final String param, final long value, final long min, final long max) {\n if (value < min || value > max) {\n throw new IllegalArgumentException(String.format(SR.PARAMETER_NOT_IN_RANGE, param, min, max));\n }\n }\n\n /**\n * Asserts that the specified value is greater than or equal to the min value.\n * \n * @param param\n * A <code>String</code> that represents the name of the parameter, which becomes the exception message\n * text if the <code>value</code> parameter is out of bounds.\n * @param value\n * The value of the specified parameter.\n * @param min\n * The minimum value for the specified parameter.\n */\n public static void assertGreaterThanOrEqual(final String param, final long value, final long min) {\n if (value < min) {\n throw new IllegalArgumentException(String.format(SR.PARAMETER_SHOULD_BE_GREATER_OR_EQUAL, param, min));\n }\n }\n\n /**\n * Returns a value representing whether the maximum execution time would be surpassed.\n * \n * @param operationExpiryTimeInMs\n * the time the request expires\n * @return <code>true</code> if the maximum execution time would be surpassed; otherwise, <code>false</code>.\n */\n public static boolean validateMaxExecutionTimeout(Long operationExpiryTimeInMs) {\n return validateMaxExecutionTimeout(operationExpiryTimeInMs, 0);\n }\n\n /**\n * Returns a value representing whether the maximum execution time would be surpassed.\n * \n * @param operationExpiryTimeInMs\n * the time the request expires\n * @param additionalInterval\n * any additional time required from now\n * @return <code>true</code> if the maximum execution time would be surpassed; otherwise, <code>false</code>.\n */\n public static boolean validateMaxExecutionTimeout(Long operationExpiryTimeInMs, long additionalInterval) {\n if (operationExpiryTimeInMs != null) {\n long currentTime = new Date().getTime();\n return operationExpiryTimeInMs < currentTime + additionalInterval;\n }\n return false;\n }\n\n /**\n * Returns a value representing the remaining time before the operation expires.\n * \n * @param operationExpiryTimeInMs\n * the time the request expires\n * @param timeoutIntervalInMs\n * the server side timeout interval\n * @return the remaining time before the operation expires\n * @throws StorageException\n * wraps a TimeoutException if there is no more time remaining\n */\n public static int getRemainingTimeout(Long operationExpiryTimeInMs, Integer timeoutIntervalInMs) throws StorageException {\n if (operationExpiryTimeInMs != null) {\n long remainingTime = operationExpiryTimeInMs - new Date().getTime();\n if (remainingTime > Integer.MAX_VALUE) {\n return Integer.MAX_VALUE;\n }\n else if (remainingTime > 0) {\n return (int) remainingTime;\n }\n else {\n TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION);\n StorageException translatedException = new StorageException(\n StorageErrorCodeStrings.OPERATION_TIMED_OUT, SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION,\n Constants.HeaderConstants.HTTP_UNUSED_306, null, timeoutException);\n throw translatedException;\n }\n }\n else if (timeoutIntervalInMs != null) {\n return timeoutIntervalInMs + Constants.DEFAULT_READ_TIMEOUT;\n }\n else {\n return Constants.DEFAULT_READ_TIMEOUT;\n }\n }\n\n /**\n * Returns a value that indicates whether a specified URI is a path-style URI.\n * \n * @param baseURI\n * A <code>java.net.URI</code> value that represents the URI being checked.\n * @return <code>true</code> if the specified URI is path-style; otherwise, <code>false</code>.\n */\n public static boolean determinePathStyleFromUri(final URI baseURI) {\n String path = baseURI.getPath();\n if (path != null && path.startsWith(\"/\")) {\n path = path.substring(1);\n }\n\n // if the path is null or empty, this is not path-style\n if (Utility.isNullOrEmpty(path)) {\n return false;\n }\n\n // if this contains a port or has a host which is not DNS, this is path-style\n return pathStylePorts.contains(baseURI.getPort()) || !isHostDnsName(baseURI);\n }\n\n /**\n * Returns a boolean indicating whether the host of the specified URI is DNS.\n * \n * @param uri\n * The URI whose host to evaluate.\n * @return <code>true</code> if the host is DNS; otherwise, <code>false</code>.\n */\n private static boolean isHostDnsName(URI uri) {\n String host = uri.getHost();\n for (int i = 0; i < host.length(); i++) {\n char hostChar = host.charAt(i);\n if (!Character.isDigit(hostChar) && !(hostChar == '.')) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Reads character data for the Etag element from an XML stream reader.\n * \n * @param xmlr\n * An <code>XMLStreamReader</code> object that represents the source XML stream reader.\n * \n * @return A <code>String</code> that represents the character data for the Etag element.\n */\n public static String formatETag(final String etag) {\n if (etag.startsWith(\"\\\"\") && etag.endsWith(\"\\\"\")) {\n return etag;\n }\n else {\n return String.format(\"\\\"%s\\\"\", etag);\n }\n }\n\n /**\n * Returns an unexpected storage exception.\n * \n * @param cause\n * An <code>Exception</code> object that represents the initial exception that caused the unexpected\n * error.\n * \n * @return A {@link StorageException} object that represents the unexpected storage exception being thrown.\n */\n public static StorageException generateNewUnexpectedStorageException(final Exception cause) {\n final StorageException exceptionRef = new StorageException(StorageErrorCode.NONE.toString(),\n \"Unexpected internal storage client error.\", 306, // unused\n null, null);\n exceptionRef.initCause(cause);\n return exceptionRef;\n }\n\n /**\n * Returns a byte array that represents the data of a <code>long</code> value.\n * \n * @param value\n * The value from which the byte array will be returned.\n * \n * @return A byte array that represents the data of the specified <code>long</code> value.\n */\n public static byte[] getBytesFromLong(final long value) {\n final byte[] tempArray = new byte[8];\n\n for (int m = 0; m < 8; m++) {\n tempArray[7 - m] = (byte) ((value >> (8 * m)) & 0xFF);\n }\n\n return tempArray;\n }\n\n /**\n * Returns the current GMT date/time String using the RFC1123 pattern.\n * \n * @return A <code>String</code> that represents the current GMT date/time using the RFC1123 pattern.\n */\n public static String getGMTTime() {\n return getGMTTime(new Date());\n }\n\n /**\n * Returns the GTM date/time String for the specified value using the RFC1123 pattern.\n *\n * @param date\n * A <code>Date</code> object that represents the date to convert to GMT date/time in the RFC1123\n * pattern.\n *\n * @return A <code>String</code> that represents the GMT date/time for the specified value using the RFC1123\n * pattern.\n */\n public static String getGMTTime(final Date date) {\n final DateFormat formatter = new SimpleDateFormat(RFC1123_GMT_PATTERN, LOCALE_US);\n formatter.setTimeZone(GMT_ZONE);\n return formatter.format(date);\n }\n\n /**\n * Returns the UTC date/time String for the specified value using Java's version of the ISO8601 pattern,\n * which is limited to millisecond precision.\n * \n * @param date\n * A <code>Date</code> object that represents the date to convert to UTC date/time in Java's version\n * of the ISO8601 pattern.\n * \n * @return A <code>String</code> that represents the UTC date/time for the specified value using Java's version\n * of the ISO8601 pattern.\n */\n public static String getJavaISO8601Time(Date date) {\n final DateFormat formatter = new SimpleDateFormat(JAVA_ISO8601_PATTERN, LOCALE_US);\n formatter.setTimeZone(UTC_ZONE);\n return formatter.format(date);\n }\n \n /**\n * Returns a namespace aware <code>SAXParser</code>.\n * \n * @return A <code>SAXParser</code> instance which is namespace aware\n * \n * @throws ParserConfigurationException\n * @throws SAXException\n */\n public static SAXParser getSAXParser() throws ParserConfigurationException, SAXException {\n factory.setNamespaceAware(true);\n return factory.newSAXParser();\n }\n \n /**\n * Returns the standard header value from the specified connection request, or an empty string if no header value\n * has been specified for the request.\n * \n * @param conn\n * An <code>HttpURLConnection</code> object that represents the request.\n * @param headerName\n * A <code>String</code> that represents the name of the header being requested.\n * \n * @return A <code>String</code> that represents the header value, or <code>null</code> if there is no corresponding\n * header value for <code>headerName</code>.\n */\n public static String getStandardHeaderValue(final HttpURLConnection conn, final String headerName) {\n final String headerValue = conn.getRequestProperty(headerName);\n\n // Coalesce null value\n return headerValue == null ? Constants.EMPTY_STRING : headerValue;\n }\n\n /**\n * Returns the UTC date/time for the specified value using the ISO8601 pattern.\n * \n * @param value\n * A <code>Date</code> object that represents the date to convert to UTC date/time in the ISO8601\n * pattern. If this value is <code>null</code>, this method returns an empty string.\n * \n * @return A <code>String</code> that represents the UTC date/time for the specified value using the ISO8601\n * pattern, or an empty string if <code>value</code> is <code>null</code>.\n */\n public static String getUTCTimeOrEmpty(final Date value) {\n if (value == null) {\n return Constants.EMPTY_STRING;\n }\n\n final DateFormat iso8601Format = new SimpleDateFormat(ISO8601_PATTERN, LOCALE_US);\n iso8601Format.setTimeZone(UTC_ZONE);\n\n return iso8601Format.format(value);\n }\n\n /**\n * Returns a <code>XmlSerializer</code> which outputs to the specified <code>StringWriter</code>\n * \n * @param outWriter\n * the <code>StringWriter</code> to output to\n * @return A <code>XmlSerializer</code> instance\n * \n * @throws IOException\n * if there is an error setting the output.\n * @throws IllegalStateException\n * if there is an error setting the output.\n * @throws IllegalArgumentException\n * if there is an error setting the output.\n */\n public static XmlSerializer getXmlSerializer(StringWriter outWriter) throws IllegalArgumentException,\n IllegalStateException, IOException {\n XmlSerializer serializer = Xml.newSerializer();\n serializer.setOutput(outWriter);\n\n return serializer;\n }\n\n /**\n * Creates an instance of the <code>IOException</code> class using the specified exception.\n * \n * @param ex\n * An <code>Exception</code> object that represents the exception used to create the IO exception.\n * \n * @return A <code>java.io.IOException</code> object that represents the created IO exception.\n */\n public static IOException initIOException(final Exception ex) {\n String message = null;\n if (ex != null && ex.getMessage() != null) {\n message = ex.getMessage() + \" Please see the cause for further information.\";\n }\n else {\n message = \"Please see the cause for further information.\";\n }\n\n final IOException retEx = new IOException(message, ex);\n return retEx;\n }\n\n /**\n * Returns a value that indicates whether the specified string is <code>null</code> or empty.\n * \n * @param value\n * A <code>String</code> being examined for <code>null</code> or empty.\n * \n * @return <code>true</code> if the specified value is <code>null</code> or empty; otherwise, <code>false</code>\n */\n public static boolean isNullOrEmpty(final String value) {\n return value == null || value.length() == 0;\n }\n\n /**\n * Returns a value that indicates whether the specified string is <code>null</code>, empty, or whitespace.\n * \n * @param value\n * A <code>String</code> being examined for <code>null</code>, empty, or whitespace.\n * \n * @return <code>true</code> if the specified value is <code>null</code>, empty, or whitespace; otherwise,\n * <code>false</code>\n */\n public static boolean isNullOrEmptyOrWhitespace(final String value) {\n return value == null || value.trim().length() == 0;\n }\n\n /**\n * Parses a connection string and returns its values as a hash map of key/value pairs.\n * \n * @param parseString\n * A <code>String</code> that represents the connection string to parse.\n * \n * @return A <code>java.util.HashMap</code> object that represents the hash map of the key / value pairs parsed from\n * the connection string.\n */\n public static HashMap<String, String> parseAccountString(final String parseString) {\n\n // 1. split name value pairs by splitting on the ';' character\n final String[] valuePairs = parseString.split(\";\");\n final HashMap<String, String> retVals = new HashMap<String, String>();\n\n // 2. for each field value pair parse into appropriate map entries\n for (int m = 0; m < valuePairs.length; m++) {\n if (valuePairs[m].length() == 0) {\n continue;\n }\n final int equalDex = valuePairs[m].indexOf(\"=\");\n if (equalDex < 1) {\n throw new IllegalArgumentException(SR.INVALID_CONNECTION_STRING);\n }\n\n final String key = valuePairs[m].substring(0, equalDex);\n final String value = valuePairs[m].substring(equalDex + 1);\n\n // 2.1 add to map\n retVals.put(key, value);\n }\n\n return retVals;\n }\n\n /**\n * Returns a GMT date in the specified format\n * \n * @param value\n * the string to parse\n * @return the GMT date, as a <code>Date</code>\n * @throws ParseException\n * If the specified string is invalid\n */\n public static Date parseDateFromString(final String value, final String pattern, final TimeZone timeZone)\n throws ParseException {\n final DateFormat rfc1123Format = new SimpleDateFormat(pattern, Utility.LOCALE_US);\n rfc1123Format.setTimeZone(timeZone);\n return rfc1123Format.parse(value);\n }\n\n /**\n * Returns a GMT date for the specified string in the RFC1123 pattern.\n * \n * @param value\n * A <code>String</code> that represents the string to parse.\n * \n * @return A <code>Date</code> object that represents the GMT date in the RFC1123 pattern.\n * \n * @throws ParseException\n * If the specified string is invalid.\n */\n public static Date parseRFC1123DateFromStringInGMT(final String value) throws ParseException {\n final DateFormat format = new SimpleDateFormat(RFC1123_GMT_PATTERN, Utility.LOCALE_US);\n format.setTimeZone(GMT_ZONE);\n return format.parse(value);\n }\n\n /**\n * Performs safe decoding of the specified string, taking care to preserve each <code>+</code> character, rather\n * than replacing it with a space character.\n * \n * @param stringToDecode\n * A <code>String</code> that represents the string to decode.\n * \n * @return A <code>String</code> that represents the decoded string.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public static String safeDecode(final String stringToDecode) throws StorageException {\n if (stringToDecode == null) {\n return null;\n }\n\n if (stringToDecode.length() == 0) {\n return Constants.EMPTY_STRING;\n }\n\n try {\n if (stringToDecode.contains(\"+\")) {\n final StringBuilder outBuilder = new StringBuilder();\n\n int startDex = 0;\n for (int m = 0; m < stringToDecode.length(); m++) {\n if (stringToDecode.charAt(m) == '+') {\n if (m > startDex) {\n outBuilder.append(URLDecoder.decode(stringToDecode.substring(startDex, m),\n Constants.UTF8_CHARSET));\n }\n\n outBuilder.append(\"+\");\n startDex = m + 1;\n }\n }\n\n if (startDex != stringToDecode.length()) {\n outBuilder.append(URLDecoder.decode(stringToDecode.substring(startDex, stringToDecode.length()),\n Constants.UTF8_CHARSET));\n }\n\n return outBuilder.toString();\n }\n else {\n return URLDecoder.decode(stringToDecode, Constants.UTF8_CHARSET);\n }\n }\n catch (final UnsupportedEncodingException e) {\n throw Utility.generateNewUnexpectedStorageException(e);\n }\n }\n\n /**\n * Performs safe encoding of the specified string, taking care to insert <code>%20</code> for each space character,\n * instead of inserting the <code>+</code> character.\n * \n * @param stringToEncode\n * A <code>String</code> that represents the string to encode.\n * \n * @return A <code>String</code> that represents the encoded string.\n * \n * @throws StorageException\n * If a storage service error occurred.\n */\n public static String safeEncode(final String stringToEncode) throws StorageException {\n if (stringToEncode == null) {\n return null;\n }\n if (stringToEncode.length() == 0) {\n return Constants.EMPTY_STRING;\n }\n\n try {\n final String tString = URLEncoder.encode(stringToEncode, Constants.UTF8_CHARSET);\n\n if (stringToEncode.contains(\" \")) {\n final StringBuilder outBuilder = new StringBuilder();\n\n int startDex = 0;\n for (int m = 0; m < stringToEncode.length(); m++) {\n if (stringToEncode.charAt(m) == ' ') {\n if (m > startDex) {\n outBuilder.append(URLEncoder.encode(stringToEncode.substring(startDex, m),\n Constants.UTF8_CHARSET));\n }\n\n outBuilder.append(\"%20\");\n startDex = m + 1;\n }\n }\n\n if (startDex != stringToEncode.length()) {\n outBuilder.append(URLEncoder.encode(stringToEncode.substring(startDex, stringToEncode.length()),\n Constants.UTF8_CHARSET));\n }\n\n return outBuilder.toString();\n }\n else {\n return tString;\n }\n\n }\n catch (final UnsupportedEncodingException e) {\n throw Utility.generateNewUnexpectedStorageException(e);\n }\n }\n\n /**\n * Determines the relative difference between the two specified URIs.\n * \n * @param baseURI\n * A <code>java.net.URI</code> object that represents the base URI for which <code>toUri</code> will be\n * made relative.\n * @param toUri\n * A <code>java.net.URI</code> object that represents the URI to make relative to <code>baseURI</code>.\n * \n * @return A <code>String</code> that either represents the relative URI of <code>toUri</code> to\n * <code>baseURI</code>, or the URI of <code>toUri</code> itself, depending on whether the hostname and\n * scheme are identical for <code>toUri</code> and <code>baseURI</code>. If the hostname and scheme of\n * <code>baseURI</code> and <code>toUri</code> are identical, this method returns an unencoded relative URI\n * such that if appended to <code>baseURI</code>, it will yield <code>toUri</code>. If the hostname or\n * scheme of <code>baseURI</code> and <code>toUri</code> are not identical, this method returns an unencoded\n * full URI specified by <code>toUri</code>.\n * \n * @throws URISyntaxException\n * If <code>baseURI</code> or <code>toUri</code> is invalid.\n */\n public static String safeRelativize(final URI baseURI, final URI toUri) throws URISyntaxException {\n // For compatibility followed\n // http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx\n\n // if host and scheme are not identical return from uri\n if (!baseURI.getHost().equals(toUri.getHost()) || !baseURI.getScheme().equals(toUri.getScheme())) {\n return toUri.toString();\n }\n\n final String basePath = baseURI.getPath();\n String toPath = toUri.getPath();\n\n int truncatePtr = 1;\n\n // Seek to first Difference\n // int maxLength = Math.min(basePath.length(), toPath.length());\n int m = 0;\n int ellipsesCount = 0;\n for (; m < basePath.length(); m++) {\n if (m >= toPath.length()) {\n if (basePath.charAt(m) == '/') {\n ellipsesCount++;\n }\n }\n else {\n if (basePath.charAt(m) != toPath.charAt(m)) {\n break;\n }\n else if (basePath.charAt(m) == '/') {\n truncatePtr = m + 1;\n }\n }\n }\n\n // ../containername and ../containername/{path} should increment the truncatePtr\n // otherwise toPath will incorrectly begin with /containername\n if (m < toPath.length() && toPath.charAt(m) == '/') {\n // this is to handle the empty directory case with the '/' delimiter\n // for example, ../containername/ and ../containername// should not increment the truncatePtr\n if (!(toPath.charAt(m - 1) == '/' && basePath.charAt(m - 1) == '/')) {\n truncatePtr = m + 1;\n }\n }\n\n if (m == toPath.length()) {\n // No path difference, return query + fragment\n return new URI(null, null, null, toUri.getQuery(), toUri.getFragment()).toString();\n }\n else {\n toPath = toPath.substring(truncatePtr);\n final StringBuilder sb = new StringBuilder();\n while (ellipsesCount > 0) {\n sb.append(\"../\");\n ellipsesCount--;\n }\n\n if (!Utility.isNullOrEmpty(toPath)) {\n sb.append(toPath);\n }\n\n if (!Utility.isNullOrEmpty(toUri.getQuery())) {\n sb.append(\"?\");\n sb.append(toUri.getQuery());\n }\n if (!Utility.isNullOrEmpty(toUri.getFragment())) {\n sb.append(\"#\");\n sb.append(toUri.getRawFragment());\n }\n\n return sb.toString();\n }\n }\n\n /**\n * Serializes the parsed StorageException. If an exception is encountered, returns empty string.\n * \n * @param ex\n * The StorageException to serialize.\n * @param opContext \n * The operation context which provides the logger.\n */\n public static void logHttpError(StorageException ex, OperationContext opContext) {\n if (Logger.shouldLog(opContext, Log.DEBUG)) {\n try {\n StringBuilder bld = new StringBuilder();\n bld.append(\"Error response received. \");\n \n bld.append(\"HttpStatusCode= \");\n bld.append(ex.getHttpStatusCode());\n \n bld.append(\", HttpStatusMessage= \");\n bld.append(ex.getMessage());\n \n bld.append(\", ErrorCode= \");\n bld.append(ex.getErrorCode());\n \n StorageExtendedErrorInformation extendedError = ex.getExtendedErrorInformation();\n if (extendedError != null) {\n bld.append(\", ExtendedErrorInformation= {ErrorMessage= \");\n bld.append(extendedError.getErrorMessage());\n \n HashMap<String, String[]> details = extendedError.getAdditionalDetails();\n if (details != null) {\n bld.append(\", AdditionalDetails= { \");\n for (Entry<String, String[]> detail : details.entrySet()) {\n bld.append(detail.getKey());\n bld.append(\"= \");\n \n for (String value : detail.getValue()) {\n bld.append(value);\n }\n bld.append(\",\");\n }\n bld.setCharAt(bld.length() - 1, '}');\n }\n bld.append(\"}\");\n }\n \n Logger.debug(opContext, bld.toString());\n } catch (Exception e) {\n // Do nothing\n }\n }\n }\n\n /**\n * Logs the HttpURLConnection request. If an exception is encountered, logs nothing.\n * \n * @param conn\n * The HttpURLConnection to serialize.\n * @param opContext \n * The operation context which provides the logger.\n */\n public static void logHttpRequest(HttpURLConnection conn, OperationContext opContext) throws IOException {\n if (Logger.shouldLog(opContext, Log.VERBOSE)) {\n try {\n StringBuilder bld = new StringBuilder();\n \n bld.append(conn.getRequestMethod());\n bld.append(\" \");\n bld.append(conn.getURL());\n bld.append(\"\\n\");\n \n // The Authorization header will not appear due to a security feature in HttpURLConnection\n for (Map.Entry<String, List<String>> header : conn.getRequestProperties().entrySet()) {\n if (header.getKey() != null) {\n bld.append(header.getKey());\n bld.append(\": \");\n }\n \n for (int i = 0; i < header.getValue().size(); i++) {\n bld.append(header.getValue().get(i));\n if (i < header.getValue().size() - 1) {\n bld.append(\",\");\n }\n }\n bld.append('\\n');\n }\n \n Logger.verbose(opContext, bld.toString());\n } catch (Exception e) {\n // Do nothing\n }\n }\n }\n\n /**\n * Logs the HttpURLConnection response. If an exception is encountered, logs nothing.\n * \n * @param conn\n * The HttpURLConnection to serialize.\n * @param opContext \n * The operation context which provides the logger.\n */\n public static void logHttpResponse(HttpURLConnection conn, OperationContext opContext) throws IOException {\n if (Logger.shouldLog(opContext, Log.VERBOSE)) {\n try {\n StringBuilder bld = new StringBuilder();\n \n // This map's null key will contain the response code and message\n for (Map.Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {\n if (header.getKey() != null) {\n bld.append(header.getKey());\n bld.append(\": \");\n }\n \n for (int i = 0; i < header.getValue().size(); i++) {\n bld.append(header.getValue().get(i));\n if (i < header.getValue().size() - 1) {\n bld.append(\",\");\n }\n }\n bld.append('\\n');\n }\n \n Logger.verbose(opContext, bld.toString());\n } catch (Exception e) {\n // Do nothing\n }\n }\n }\n\n /**\n * Trims the specified character from the end of a string.\n * \n * @param value\n * A <code>String</code> that represents the string to trim.\n * @param trimChar\n * The character to trim from the end of the string.\n * \n * @return The string with the specified character trimmed from the end.\n */\n protected static String trimEnd(final String value, final char trimChar) {\n int stopDex = value.length() - 1;\n while (stopDex > 0 && value.charAt(stopDex) == trimChar) {\n stopDex--;\n }\n\n return stopDex == value.length() - 1 ? value : value.substring(stopDex);\n }\n\n /**\n * Trims whitespace from the beginning of a string.\n * \n * @param value\n * A <code>String</code> that represents the string to trim.\n * \n * @return The string with whitespace trimmed from the beginning.\n */\n public static String trimStart(final String value) {\n int spaceDex = 0;\n while (spaceDex < value.length() && value.charAt(spaceDex) == ' ') {\n spaceDex++;\n }\n\n return value.substring(spaceDex);\n }\n\n /**\n * Reads data from an input stream and writes it to an output stream, calculates the length of the data written, and\n * optionally calculates the MD5 hash for the data.\n * \n * @param sourceStream\n * An <code>InputStream</code> object that represents the input stream to use as the source.\n * @param outStream\n * An <code>OutputStream</code> object that represents the output stream to use as the destination.\n * @param writeLength\n * The number of bytes to read from the stream.\n * @param rewindSourceStream\n * <code>true</code> if the input stream should be rewound <strong>before</strong> it is read; otherwise,\n * <code>false</code>\n * @param calculateMD5\n * <code>true</code> if an MD5 hash will be calculated; otherwise, <code>false</code>.\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * @param options\n * A {@link RequestOptions} object that specifies any additional options for the request. Namely, the\n * maximum execution time.\n * @return A {@link StreamMd5AndLength} object that contains the output stream length, and optionally the MD5 hash.\n * \n * @throws IOException\n * If an I/O error occurs.\n * @throws StorageException\n * If a storage service error occurred.\n */\n public static StreamMd5AndLength writeToOutputStream(final InputStream sourceStream, final OutputStream outStream,\n long writeLength, final boolean rewindSourceStream, final boolean calculateMD5, OperationContext opContext,\n final RequestOptions options) throws IOException, StorageException {\n return writeToOutputStream(sourceStream, outStream, writeLength, rewindSourceStream, calculateMD5, opContext,\n options, true);\n }\n\n /**\n * Reads data from an input stream and writes it to an output stream, calculates the length of the data written, and\n * optionally calculates the MD5 hash for the data.\n * \n * @param sourceStream\n * An <code>InputStream</code> object that represents the input stream to use as the source.\n * @param outStream\n * An <code>OutputStream</code> object that represents the output stream to use as the destination.\n * @param writeLength\n * The number of bytes to read from the stream.\n * @param rewindSourceStream\n * <code>true</code> if the input stream should be rewound <strong>before</strong> it is read; otherwise,\n * <code>false</code>\n * @param calculateMD5\n * <code>true</code> if an MD5 hash will be calculated; otherwise, <code>false</code>.\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * @param options\n * A {@link RequestOptions} object that specifies any additional options for the request. Namely, the\n * maximum execution time.\n * @return A {@link StreamMd5AndLength} object that contains the output stream length, and optionally the MD5 hash.\n * \n * @throws IOException\n * If an I/O error occurs.\n * @throws StorageException\n * If a storage service error occurred.\n */\n public static StreamMd5AndLength writeToOutputStream(final InputStream sourceStream, final OutputStream outStream,\n long writeLength, final boolean rewindSourceStream, final boolean calculateMD5, OperationContext opContext,\n final RequestOptions options, final Boolean shouldFlush) throws IOException, StorageException {\n return writeToOutputStream(sourceStream, outStream, writeLength, rewindSourceStream, calculateMD5, opContext,\n options, null /*StorageRequest*/, null /* descriptor */);\n }\n\n /**\n * Reads data from an input stream and writes it to an output stream, calculates the length of the data written, and\n * optionally calculates the MD5 hash for the data.\n * \n * @param sourceStream\n * An <code>InputStream</code> object that represents the input stream to use as the source.\n * @param outStream\n * An <code>OutputStream</code> object that represents the output stream to use as the destination.\n * @param writeLength\n * The number of bytes to read from the stream.\n * @param rewindSourceStream\n * <code>true</code> if the input stream should be rewound <strong>before</strong> it is read; otherwise,\n * <code>false</code>\n * @param calculateMD5\n * <code>true</code> if an MD5 hash will be calculated; otherwise, <code>false</code>.\n * @param opContext\n * An {@link OperationContext} object that represents the context for the current operation. This object\n * is used to track requests to the storage service, and to provide additional runtime information about\n * the operation.\n * @param options\n * A {@link RequestOptions} object that specifies any additional options for the request. Namely, the\n * maximum execution time.\n * @param request\n * Used by download resume to set currentRequestByteCount on the request. Otherwise, null is always used.\n * @param descriptor\n * A {@Link StreamMd5AndLength} object to append to in the case of recovery action or null if this is not called\n * from a recovery. This value needs to be passed for recovery in case part of the body has already been read,\n * the recovery will attempt to download the remaining bytes but will do MD5 validation on the originally\n * requested range size.\n * @return A {@link StreamMd5AndLength} object that contains the output stream length, and optionally the MD5 hash.\n * \n * @throws IOException\n * If an I/O error occurs.\n * @throws StorageException\n * If a storage service error occurred.\n */\n public static StreamMd5AndLength writeToOutputStream(final InputStream sourceStream, final OutputStream outStream,\n long writeLength, final boolean rewindSourceStream, final boolean calculateMD5, OperationContext opContext,\n final RequestOptions options, StorageRequest<?, ?, Integer> request, StreamMd5AndLength descriptor)\n throws IOException, StorageException {\n if (rewindSourceStream && sourceStream.markSupported()) {\n sourceStream.reset();\n sourceStream.mark(Constants.MAX_MARK_LENGTH);\n }\n\n if (descriptor == null) {\n descriptor = new StreamMd5AndLength();\n if (calculateMD5) {\n try {\n descriptor.setDigest(MessageDigest.getInstance(\"MD5\"));\n }\n catch (final NoSuchAlgorithmException e) {\n // This wont happen, throw fatal.\n throw Utility.generateNewUnexpectedStorageException(e);\n }\n }\n }\n else {\n descriptor.setMd5(null);\n }\n\n if (writeLength < 0) {\n writeLength = Long.MAX_VALUE;\n }\n\n final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH];\n int nextCopy = (int) Math.min(retrievedBuff.length, writeLength);\n int count = sourceStream.read(retrievedBuff, 0, nextCopy);\n\n while (nextCopy > 0 && count != -1) {\n\n // if maximum execution time would be exceeded\n if (Utility.validateMaxExecutionTimeout(options.getOperationExpiryTimeInMs())) {\n // throw an exception\n TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION);\n throw Utility.initIOException(timeoutException);\n }\n\n if (outStream != null) {\n outStream.write(retrievedBuff, 0, count);\n }\n\n if (calculateMD5) {\n descriptor.getDigest().update(retrievedBuff, 0, count);\n }\n\n descriptor.setLength(descriptor.getLength() + count);\n descriptor.setCurrentOperationByteCount(descriptor.getCurrentOperationByteCount() + count);\n\n if (request != null) {\n request.setCurrentRequestByteCount(request.getCurrentRequestByteCount() + count);\n request.setCurrentDescriptor(descriptor);\n }\n\n nextCopy = (int) Math.min(retrievedBuff.length, writeLength - descriptor.getLength());\n count = sourceStream.read(retrievedBuff, 0, nextCopy);\n }\n\n if (outStream != null) {\n outStream.flush();\n }\n\n return descriptor;\n }\n\n /**\n * Private Default Constructor.\n */\n private Utility() {\n // No op\n }\n\n public static void checkNullaryCtor(Class<?> clazzType) {\n Constructor<?> ctor = null;\n try {\n ctor = clazzType.getDeclaredConstructor((Class<?>[]) null);\n }\n catch (Exception e) {\n throw new IllegalArgumentException(SR.MISSING_NULLARY_CONSTRUCTOR);\n }\n\n if (ctor == null) {\n throw new IllegalArgumentException(SR.MISSING_NULLARY_CONSTRUCTOR);\n }\n }\n\n /**\n * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it\n * with up to millisecond precision. \n * \n * @param dateString\n * the <code>String</code> to be interpreted as a <code>Date</code>\n * \n * @return the corresponding <code>Date</code> object\n */\n public static Date parseDate(String dateString) {\n String pattern = MAX_PRECISION_PATTERN;\n switch(dateString.length()) {\n case 28: // \"yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'\"-> [2012-01-04T23:21:59.1234567Z] length = 28\n case 27: // \"yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'\"-> [2012-01-04T23:21:59.123456Z] length = 27\n case 26: // \"yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'\"-> [2012-01-04T23:21:59.12345Z] length = 26\n case 25: // \"yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'\"-> [2012-01-04T23:21:59.1234Z] length = 25\n case 24: // \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\"-> [2012-01-04T23:21:59.123Z] length = 24\n dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH);\n break;\n case 23: // \"yyyy-MM-dd'T'HH:mm:ss.SS'Z'\"-> [2012-01-04T23:21:59.12Z] length = 23\n // SS is assumed to be milliseconds, so a trailing 0 is necessary\n dateString = dateString.replace(\"Z\", \"0\");\n break;\n case 22: // \"yyyy-MM-dd'T'HH:mm:ss.S'Z'\"-> [2012-01-04T23:21:59.1Z] length = 22\n // S is assumed to be milliseconds, so trailing 0's are necessary\n dateString = dateString.replace(\"Z\", \"00\");\n break;\n case 20: // \"yyyy-MM-dd'T'HH:mm:ss'Z'\"-> [2012-01-04T23:21:59Z] length = 20\n pattern = Utility.ISO8601_PATTERN;\n break;\n case 17: // \"yyyy-MM-dd'T'HH:mm'Z'\"-> [2012-01-04T23:21Z] length = 17\n pattern = Utility.ISO8601_PATTERN_NO_SECONDS;\n break;\n default:\n throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString));\n }\n\n final DateFormat format = new SimpleDateFormat(pattern, Utility.LOCALE_US);\n format.setTimeZone(UTC_ZONE);\n try {\n return format.parse(dateString);\n }\n catch (final ParseException e) {\n throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString), e);\n }\n }\n \n /**\n * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it\n * with up to millisecond precision. Use {@link #parseDate(String)} instead unless\n * <code>dateBackwardCompatibility</code> is needed.\n * <p>\n * See <a href=\"http://go.microsoft.com/fwlink/?LinkId=523753\">here</a> for more details.\n * \n * @param dateString\n * the <code>String</code> to be interpreted as a <code>Date</code>\n * @param dateBackwardCompatibility\n * <code>true</code> to correct Date values that may have been written\n * using versions of this library prior to 0.4.0; otherwise, <code>false</code>\n * \n * @return the corresponding <code>Date</code> object\n */\n public static Date parseDate(String dateString, boolean dateBackwardCompatibility) {\n if (!dateBackwardCompatibility) {\n return parseDate(dateString);\n }\n\n final int beginMilliIndex = 20; // Length of \"yyyy-MM-ddTHH:mm:ss.\"\n final int endTenthMilliIndex = 24; // Length of \"yyyy-MM-ddTHH:mm:ss.SSSS\"\n\n // Check whether the millisecond and tenth of a millisecond digits are all 0.\n if (dateString.length() > endTenthMilliIndex &&\n \"0000\".equals(dateString.substring(beginMilliIndex, endTenthMilliIndex))) {\n // Remove the millisecond and tenth of a millisecond digits.\n // Treat the final three digits (ticks) as milliseconds.\n dateString = dateString.substring(0, beginMilliIndex) + dateString.substring(endTenthMilliIndex);\n }\n\n return parseDate(dateString);\n }\n\n /**\n * Determines which location can the listing command target by looking at the\n * continuation token.\n * \n * @param token\n * Continuation token\n * @return\n * Location mode\n */\n public static RequestLocationMode getListingLocationMode(ResultContinuation token) {\n if ((token != null) && token.getTargetLocation() != null) {\n switch (token.getTargetLocation()) {\n case PRIMARY:\n return RequestLocationMode.PRIMARY_ONLY;\n\n case SECONDARY:\n return RequestLocationMode.SECONDARY_ONLY;\n\n default:\n throw new IllegalArgumentException(String.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, \"token\",\n token.getTargetLocation()));\n }\n }\n\n return RequestLocationMode.PRIMARY_OR_SECONDARY;\n }\n\n /**\n * Writes an XML element to the <code>XmlSerializer</code> without a namespace.\n * \n * @param serializer\n * the <code>XmlSerializer</code> to write to\n * @param tag\n * the tag to use for the XML element\n * @param text\n * the text to write inside the XML tags\n * @throws IOException\n * if there is an error writing the output.\n * @throws IllegalStateException\n * if there is an error writing the output.\n * @throws IllegalArgumentException\n * if there is an error writing the output.\n */\n public static void serializeElement(XmlSerializer serializer, String tag, String text) throws IllegalArgumentException,\n IllegalStateException, IOException {\n serializer.startTag(Constants.EMPTY_STRING, tag);\n serializer.text(text);\n serializer.endTag(Constants.EMPTY_STRING, tag);\n }\n}" ]
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.security.InvalidKeyException; import java.util.Calendar; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import com.microsoft.azure.storage.AccessCondition; import com.microsoft.azure.storage.Constants; import com.microsoft.azure.storage.DoesServiceRequest; import com.microsoft.azure.storage.IPRange; import com.microsoft.azure.storage.OperationContext; import com.microsoft.azure.storage.ResultContinuation; import com.microsoft.azure.storage.ResultContinuationType; import com.microsoft.azure.storage.ResultSegment; import com.microsoft.azure.storage.SharedAccessPolicyHandler; import com.microsoft.azure.storage.SharedAccessPolicySerializer; import com.microsoft.azure.storage.SharedAccessProtocols; import com.microsoft.azure.storage.StorageCredentials; import com.microsoft.azure.storage.StorageCredentialsSharedAccessSignature; import com.microsoft.azure.storage.StorageErrorCodeStrings; import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.StorageUri; import com.microsoft.azure.storage.core.ExecutionEngine; import com.microsoft.azure.storage.core.LazySegmentedIterable; import com.microsoft.azure.storage.core.PathUtility; import com.microsoft.azure.storage.core.RequestLocationMode; import com.microsoft.azure.storage.core.SR; import com.microsoft.azure.storage.core.SegmentedStorageRequest; import com.microsoft.azure.storage.core.SharedAccessSignatureHelper; import com.microsoft.azure.storage.core.StorageCredentialsHelper; import com.microsoft.azure.storage.core.StorageRequest; import com.microsoft.azure.storage.core.UriQueryBuilder; import com.microsoft.azure.storage.core.Utility;
* @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public boolean exists(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { return this.exists(false, accessCondition, options, opContext); } @DoesServiceRequest private boolean exists(final boolean primaryOnly, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.existsImpl(primaryOnly, accessCondition, options), options.getRetryPolicyFactory(), opContext); } private StorageRequest<CloudBlobClient, CloudBlobContainer, Boolean> existsImpl(final boolean primaryOnly, final AccessCondition accessCondition, final BlobRequestOptions options) { final StorageRequest<CloudBlobClient, CloudBlobContainer, Boolean> getRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, Boolean>( options, this.getStorageUri()) { @Override public void setRequestLocationMode() { this.setRequestLocationMode(primaryOnly ? RequestLocationMode.PRIMARY_ONLY : RequestLocationMode.PRIMARY_OR_SECONDARY); } @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return BlobRequest.getContainerProperties( container.getTransformedAddress().getUri(this.getCurrentLocation()), options, context, accessCondition); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context); } @Override public Boolean preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_OK) { // Set attributes final BlobContainerAttributes attributes = BlobResponse.getBlobContainerAttributes( this.getConnection(), client.isUsePathStyleUris()); container.metadata = attributes.getMetadata(); container.properties = attributes.getProperties(); container.name = attributes.getName(); return Boolean.valueOf(true); } else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Boolean.valueOf(false); } else { this.setNonExceptionedRetryableFailure(true); // return false instead of null to avoid SCA issues return false; } } }; return getRequest; } /** * Returns a shared access signature for the container. Note this does not contain the leading "?". * * @param policy * An {@link SharedAccessBlobPolicy} object that represents the access policy for the shared access * signature. * @param groupPolicyIdentifier * A <code>String</code> which represents the container-level access policy. * * @return A <code>String</code> which represents a shared access signature for the container. * * @throws StorageException * If a storage service error occurred. * @throws InvalidKeyException * If the key is invalid. */ public String generateSharedAccessSignature(final SharedAccessBlobPolicy policy, final String groupPolicyIdentifier) throws InvalidKeyException, StorageException { return this.generateSharedAccessSignature( policy, groupPolicyIdentifier, null /* IP range */, null /* protocols */); } /** * Returns a shared access signature for the container. Note this does not contain the leading "?". * * @param policy * An {@link SharedAccessBlobPolicy} object that represents the access policy for the shared access * signature. * @param groupPolicyIdentifier * A <code>String</code> which represents the container-level access policy. * @param ipRange * A {@link IPRange} object containing the range of allowed IP addresses. * @param protocols * A {@link SharedAccessProtocols} representing the allowed Internet protocols. * * @return A <code>String</code> which represents a shared access signature for the container. * * @throws StorageException * If a storage service error occurred. * @throws InvalidKeyException * If the key is invalid. */ public String generateSharedAccessSignature(final SharedAccessBlobPolicy policy, final String groupPolicyIdentifier, final IPRange ipRange, final SharedAccessProtocols protocols) throws InvalidKeyException, StorageException {
if (!StorageCredentialsHelper.canCredentialsSignRequest(this.blobServiceClient.getCredentials())) {
7
tgobbens/fluffybalance
core/src/com/balanceball/system/PhysicsSystem.java
[ "public class GravityComponent implements Component {\n public Vector2 normalisedGravity = new Vector2();\n}", "public class GravityEntity extends Entity {\n\n public GravityEntity() {\n addComponent(new GravityComponent());\n }\n}", "public class PhysicsComponent implements Component {\n public Body body;\n}", "public class PositionComponent implements Component {\n public Vector2 position = new Vector2();\n}", "public class RotationComponent implements Component {\n public float degree;\n}", "public abstract class Entity implements GameLifecycleListener {\n private ObjectMap<String, Component> mComponents;\n\n public static final int STATE_BECOMING_ACTIVE = 0;\n public static final int STATE_ACTIVE = 1;\n public static final int STATE_BECOMING_PAUSED = 2;\n public static final int STATE_PAUSED = 3;\n\n private int mState = STATE_BECOMING_ACTIVE;\n\n protected Engine mEngine;\n\n public Entity() {\n mComponents = new ObjectMap<String, Component>(16);\n }\n\n protected final void addComponent(Component component) {\n mComponents.put(component.getClass().getName(), component);\n }\n\n void setEngine(Engine engine) {\n mEngine = engine;\n }\n\n public int getState() {\n return mState;\n }\n\n public void becomeActive() {\n mState = STATE_BECOMING_ACTIVE;\n }\n\n public void becomePaused() {\n mState = STATE_BECOMING_PAUSED;\n }\n\n @Override\n public void resume() {\n mState = STATE_ACTIVE;\n }\n\n @Override\n public void update() {\n // do nothing\n }\n\n @Override\n public void pause() {\n mState = STATE_PAUSED;\n }\n\n @Override\n public void create() {\n // do nothing\n }\n\n @Override\n public void dispose() {\n // do nothing\n }\n\n /**\n * check if the entity matches all required components\n * @param componentsType\n * @return boolean\n */\n final boolean matchesComponentTypes(Array<Class<? extends Component>> componentsType) {\n for (Class<? extends Component> componentType : componentsType) {\n if (getComponentByType(componentType) == null) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *\n * @param componentType\n * @param <T> get the component of a given type\n * @return T the component, null if not found\n */\n public final <T extends Component> T getComponentByType(Class<T> componentType) {\n Object o = mComponents.get(componentType.getName());\n return (o == null) ? null : (T) o;\n }\n}", "public abstract class System implements SystemInterface, GameLifecycleListener {\n\n protected Engine mEngine = null;\n\n // register all type it want to listen for\n private Array<Class<? extends Component>> mComponentsType;\n\n protected System() {\n mComponentsType = new Array<Class<? extends Component>>();\n }\n\n void setEngine(Engine engine) {\n mEngine = engine;\n }\n\n protected final void addComponentType(Class<? extends Component> componentType) {\n mComponentsType.add(componentType);\n }\n\n Array<Class<? extends Component>> getComponentsType() {\n return mComponentsType;\n }\n\n @Override\n public void create() {\n\n }\n\n @Override\n public void resume() {\n\n }\n\n @Override\n public void update() {\n\n }\n\n @Override\n public void pause() {\n\n }\n\n @Override\n public void dispose() {\n\n }\n}" ]
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Box2D; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.utils.Array; import com.balanceball.component.GravityComponent; import com.balanceball.enity.GravityEntity; import com.balanceball.component.PhysicsComponent; import com.balanceball.component.PositionComponent; import com.balanceball.component.RotationComponent; import com.sec.Entity; import com.sec.System;
package com.balanceball.system; /** * Created by tijs on 14/07/2017. */ public class PhysicsSystem extends System { public interface BallPointContactListener { void onPointContact(int type); } public final static int BODY_USER_DATA_TYPE_BALL = 0; public final static int BODY_USER_DATA_TYPE_POINT_LEFT = 1; public final static int BODY_USER_DATA_TYPE_POINT_RIGHT = 2; public final static int BODY_USER_DATA_TYPE_OTHER = 3; public static class BodyUserDate { public BodyUserDate(int type) { this.type = type; } int type = BODY_USER_DATA_TYPE_OTHER; } private final float BASE_GRAVITY = 150.f; private float mAccumulator = 0.f; private World mWorld; private boolean mIsPaused = false; private BallPointContactListener mBallPointContactListener = null; public PhysicsSystem(BallPointContactListener ballPointContactListener) { addComponentType(PhysicsComponent.class); mBallPointContactListener = ballPointContactListener; } public void setIsPaused(boolean isPaused) { mIsPaused = isPaused; } public World getWorld() { return mWorld; } @Override public void create() { Box2D.init(); mWorld = new World(new Vector2(0, BASE_GRAVITY), true); mWorld.setContactListener(new ContactListener() { @Override public void beginContact(Contact contact) { BodyUserDate userDateA = (BodyUserDate) contact.getFixtureA().getBody().getUserData(); BodyUserDate userDateB = (BodyUserDate) contact.getFixtureB().getBody().getUserData(); // check if there was a contact between the left or right point if (userDateA != null && userDateB != null) { if ((userDateA.type == BODY_USER_DATA_TYPE_POINT_LEFT && userDateB.type == BODY_USER_DATA_TYPE_BALL) || (userDateA.type == BODY_USER_DATA_TYPE_BALL && userDateB.type == BODY_USER_DATA_TYPE_POINT_LEFT)) { // touched left ball mBallPointContactListener.onPointContact(BODY_USER_DATA_TYPE_POINT_LEFT); } else if ((userDateA.type == BODY_USER_DATA_TYPE_POINT_RIGHT && userDateB.type == BODY_USER_DATA_TYPE_BALL) || (userDateA.type == BODY_USER_DATA_TYPE_BALL && userDateB.type == BODY_USER_DATA_TYPE_POINT_RIGHT)) { // touched right ball mBallPointContactListener.onPointContact(BODY_USER_DATA_TYPE_POINT_RIGHT); } } } @Override public void endContact(Contact contact) { } @Override public void preSolve(Contact contact, Manifold oldManifold) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { } }); } public void updateFromEntities(Array<Entity> entities) { // if the game is not running don't update the physics if (mIsPaused) { return; } GravityComponent gravityComponent = mEngine.getComponentFromFirstEntity(
GravityEntity.class, GravityComponent.class);
1
jaychang0917/SimpleRecyclerView
app/src/main/java/com/jaychang/demo/srv/DragAndDropActivity.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 abstract class SimpleCell<T, VH extends SimpleViewHolder> {\n\n public interface OnCellClickListener<T> {\n void onCellClicked(@NonNull T item);\n }\n\n public interface OnCellLongClickListener<T> {\n void onCellLongClicked(@NonNull T item);\n }\n\n private int spanSize = 1;\n private T item;\n private OnCellClickListener onCellClickListener;\n private OnCellLongClickListener onCellLongClickListener;\n\n public SimpleCell(@NonNull T item) {\n this.item = item;\n }\n\n @LayoutRes protected abstract int getLayoutRes();\n\n @NonNull protected abstract VH onCreateViewHolder(@NonNull ViewGroup parent, @NonNull View cellView);\n\n protected abstract void onBindViewHolder(@NonNull VH holder, int position, @NonNull Context context, Object payload);\n\n protected void onUnbindViewHolder(@NonNull VH holder) {\n }\n\n @NonNull public T getItem() {\n return item;\n }\n\n public void setItem(@NonNull T item) {\n this.item = item;\n }\n\n protected long getItemId() {\n return item.hashCode();\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 void setOnCellClickListener(@NonNull OnCellClickListener<T> onCellClickListener) {\n this.onCellClickListener = onCellClickListener;\n }\n\n public void setOnCellLongClickListener(@NonNull OnCellLongClickListener<T> onCellLongClickListener) {\n this.onCellLongClickListener = onCellLongClickListener;\n }\n\n public OnCellClickListener<T> getOnCellClickListener() {\n return onCellClickListener;\n }\n\n public OnCellLongClickListener<T> getOnCellLongClickListener() {\n return onCellLongClickListener;\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 SimpleCell<?, ?> cell = (SimpleCell<?, ?>) o;\n\n return getItemId() == cell.getItemId();\n\n }\n\n @Override\n public int hashCode() {\n return (int) (getItemId() ^ (getItemId() >>> 32));\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 DragAndDropCallback<T> {\n\n public boolean enableDefaultRaiseEffect() {\n return true;\n }\n\n public void onCellDragStarted(@NonNull SimpleRecyclerView simpleRecyclerView, @NonNull View itemView, @NonNull T item, int position) {\n }\n\n public void onCellMoved(@NonNull SimpleRecyclerView simpleRecyclerView, @NonNull View itemView, @NonNull T item, int fromPosition, int toPosition) {\n }\n\n public void onCellDropped(@NonNull SimpleRecyclerView simpleRecyclerView, @NonNull View itemView, @NonNull T item, int initialPosition, int toPosition) {\n }\n\n public void onCellDragCancelled(@NonNull SimpleRecyclerView simpleRecyclerView, @NonNull View itemView, @NonNull T item, int currentPosition) {\n }\n\n}" ]
import android.os.Bundle; import android.view.View; 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.srv.SimpleCell; import com.jaychang.srv.SimpleRecyclerView; import com.jaychang.srv.behavior.DragAndDropCallback; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick;
package com.jaychang.demo.srv; public class DragAndDropActivity extends BaseActivity { @BindView(R.id.linearRecyclerView) SimpleRecyclerView linearRecyclerView; @BindView(R.id.gridRecyclerView) SimpleRecyclerView gridRecyclerView; @BindView(R.id.resultView) TextView resultView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drag_and_drop); ButterKnife.bind(this); init(); bindBooks(linearRecyclerView, true); bindBooks(gridRecyclerView, false); } private void init() { DragAndDropCallback<Book> dragAndDropCallback = new DragAndDropCallback<Book>() { // Optional @Override public boolean enableDefaultRaiseEffect() { // return false if you manipulate custom drag effect in other 3 callbacks. return super.enableDefaultRaiseEffect(); } // Optional @Override public void onCellDragStarted(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int position) { resultView.setText("Started dragging " + item + " at position " + position); } // Optional @Override public void onCellMoved(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int fromPosition, int toPosition) { resultView.setText("Moved " + item + " from position " + fromPosition + " to position " + toPosition); } @Override public void onCellDropped(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int fromPosition, int toPosition) { resultView.setText("Dragged " + item + " from position " + fromPosition + " to position " + toPosition); } @Override public void onCellDragCancelled(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int currentPosition) { resultView.setText("Cancelled dragging " + item + " at position " + currentPosition); } }; linearRecyclerView.enableDragAndDrop(R.id.dragHandle, dragAndDropCallback); gridRecyclerView.enableDragAndDrop(dragAndDropCallback); } @OnClick(R.id.linearRadioButton) void showLinearRecyclerView() { linearRecyclerView.setVisibility(View.VISIBLE); gridRecyclerView.setVisibility(View.GONE); resultView.setText(""); } @OnClick(R.id.gridRadioButton) void showGridRecyclerView() { linearRecyclerView.setVisibility(View.GONE); gridRecyclerView.setVisibility(View.VISIBLE); resultView.setText(""); } private void bindBooks(SimpleRecyclerView simpleRecyclerView, boolean showHandle) { List<Book> books = DataUtils.getBooks(); List<SimpleCell> cells = new ArrayList<>(); for (Book book : books) {
BookCell cell = new BookCell(book);
0